Is it possible add fields to the model from another app?

Hi all,

I used to Odoo (OpenERP) for some times. It provide a function "_inherit" that can add fields to the model from another module (app). Is it possible to do it in Django? Since I want to create a plugin to add some fields into the models instead of edit the original app inside.

Thanks.

 

 

Qho

 

Guest June 28, 2017, 4:48 a.m. 1 Answer 

Django keep me login feature is not working

Hi,
I want a solution if any anyone can assist me.
When customer will login with Keep me logged in checked then session will not be expire, But if Keep me logged in is not checked then should expire as per bellow mentioned setting.py variable value.

So Now login without checked keep me logged in is working fine as we have set SESSION_SECURITY_WARN_AFTER and SESSION_SECURITY_EXPIRE_AFTER. And if keep me login is checked, I tried to disable by overriding above variable value or increase expire time using request.session.set_expiry(24*30*3600). But it is not working. Can you anyone advice how can I disable this expire time if keep me login is checked.

settings.py

EXPIRE_TIME = 60*10
SESSION_SECURITY_WARN_AFTER = EXPIRE_TIME
SESSION_SECURITY_EXPIRE_AFTER = EXPIRE_TIME + 180

rajeshdas.rp@gmail.com June 7, 2017, 5:19 a.m. 0 Answer 

save the variation of radio buttons django

Hello i have a form with three radio buttons they aren't a part of models.py. But when the user click on radio buttons i want to save their value in a variable called strategy in models.py. I defined in views : request.Post.get ('tabs') the name of radio buttons. But the error was **('WSGIRequest' object has no attribute 'Post')** Everything is saved excluding the value of radio buttons.

    class Parameters(models.Model):
        
    MARKET= ((1,'Nasdaq'),(2, 'Nyse'),(3,'Amex'),)  
        
        
    SECTOR_CHOICES = ((1,'Utilities'),(2, 'Basic Materials'),(3,'Healthcare'), (4,'Services'),(5,'Financial'),)

        
      
      
    user         = models.ForeignKey(User)
    title         = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters')
    type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest")
    strategy = models.CharField('Strategy', choices=STRATEGY_CHOICES, max_length=20,default="Long")
        

    #input characteristics
    price_1_min                = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
    price_1_max                = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)])
    stocks_num_2_min            = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)])
    stocks_num_2_max            = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),])
    holding_period                          = models.IntegerField('3. Holding Period', default=1, validators=[MinValueValidator(1),])
    
    
    volume                                  = models.IntegerField('4. Volume', default=0, validators=[MinValueValidator(0),])
    market = models.CharField('Market', max_length=30, null=True)
    sector= models.CharField('Sector', max_length=30, null=True)

Forms.py

    class BacktestForm(forms.ModelForm):

    period_start = forms.DateField(initial=datetime.datetime.today().date() - datetime.timedelta(days=365+16), widget=forms.widgets.DateInput(format="%Y/%m/%d"), input_formats=["%Y/%m/%d"])
    period_end     = forms.DateField(initial=datetime.datetime.today().date() - datetime.timedelta(days=16), widget=forms.widgets.DateInput(format="%Y/%m/%d"), input_formats=["%Y/%m/%d"])
        
        market = forms.MultipleChoiceField(label='Market', choices=Parameters.MARKET, widget=forms.CheckboxSelectMultiple)
        sector = forms.MultipleChoiceField(label='Sector', choices=Parameters.SECTOR_CHOICES, widget=forms.CheckboxSelectMultiple)
        
    
       
    
    class Meta:
        model = Parameters
        exclude = [
            'user',
            'type',
            'created_at', 
            'updated_at',
             'strategy',
                       
            ]
        widgets={
            'title': forms.TextInput(attrs={'placeholder':'for ex. highLimitLowPrice'}),
                        'sector': forms.CheckboxSelectMultiple(),
            }


The HTML:
 

     <div class="row">
        <div class='col-md-9'> 
                  <div id="tabs">

                   <input type="radio" name="tabs" id="toggle-tab1"  checked="checked" />
                   <label for="toggle-tab1">Long</label>

                   <input type="radio" name="tabs" id="toggle-tab2"    />
                   <label for="toggle-tab2">Short</label>

                   <input type="radio" name="tabs" id="toggle-tab3"   />
                   <label for="toggle-tab3">Long and Short</label>
                   <div id="tab1" class="tab"  >
            <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
                {% csrf_token %}
                 
                                
                {% include 'tags/parameters_form.html' %}
                <br />
                {% include 'tags/parameters_backtest_form.html' %}
                <br/>
                               
                                
                                {% if user.is_authenticated %}
                                <input type='submit' id='run' value='Run' class='btn btn-default'>
            
                    {% if user.profile.is_active %}
                        Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                    {% else %}
                        <p>
                        Expired account! you need to reactivate in order to save parameters.
                        </p>
                    {% endif %}
                {% else %}
                                         Please <a href="{% url 'auth_login' %}">login</a> in order to Run backtesting!
                     </br>
                     Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).   
                                      
                                  {% endif %}                        

                              
                        </form>

Views.py (for the save function):

    def backtest(request, pk=None):

    if pk is not None:
        param = get_object_or_404(Parameters, pk=pk, user=request.user)
        form = BacktestForm(request.POST or None, instance=param)
    else:
        form = BacktestForm(request.POST or None)
        
        if request.method == 'POST':
        if form.is_valid():
            if 'save' in request.POST:
                                obj = form.save(commit= False)
                                obj.user = request.user
                                
                             
                                obj.strategy=request.Post.get('tabs')
                                                              
                
                obj.type = "backtest"
                                
                    obj.save()
                                
                    messages.info(request, 'Saved!')
                return redirect(obj.get_backtest_url())

        

farah_chaaban@hotmail.com June 7, 2017, 3:50 a.m. 0 Answer 

Fetching API data in json format and inserting it into the django local database.

Hi i am new to Django, can you please guide me as to how i can fetch data from a companies database and insert it into my database. I have been reading about models.py and serializers.py and all tutorials and readings i came accross has online shown be how to display the database data onto the html and how to export data already in the database as json data.

Guest June 5, 2017, 2:21 a.m. 1 Answer 

django mongodg and pymongo

i am working on django mongodg and pymongo. i was wondering if someone has a django project (with mongodb and pymongo)  . I can't do  connect them. i will be grateful

Guest May 30, 2017, 7:54 a.m. 1 Answer 

Django Custom Field cleaning for Integer

I have this puzzling django form

Here is part of my views.py handling the POST request

def getUpdataBet(request, name):

    ..........

    elif request.method == 'POST':

         Bound_form = form_Net(request.POST, instance=obj)

         if Bound_form.is_valid():

                new_tag = Bound_form.save()

                return render(request, 'Account\Sucess.html', .........)

          else:

                 render(request, ......)

 

And my forms.py has this custom cleaning for the form page.

 

def clean_BetAccountBalance(self):

       Data = self.cleaned_data.get(BetAccountBalance)

       If Data > 800:

             raise forms.ValidationError("Value too Large")

       else:

               return data

 

My question is that, In my form page when i give a value greater than 800, it returns the validation error as usual. But when i input a value lesser than 800, the form page acts as bound_form.is_valid() is false

The most puzzling thing is that when i comment out the if and else statement, it works perfectly fine and returns the cleaned_data perfectly. Is it that you dont use an if statement in a custom clean method.?

yingikeme@yahoo.com May 25, 2017, 2:51 p.m. 0 Answer 

Validation issue with my Form

 I have this puzzling issue with my forms. Here is my part of my views.py handling the POST request.

elif request.method == 'POST':
        obj.BetAccountBalance += int(request.POST['BetAccountBalance'])
        
        bound_form = form_Net({'BetAccountBalance':obj.BetAccountBalance}, instance=obj)

        if bound_form.is_valid():
            new_tag = bound_form.save()
            NetObj.AccountBal -= int(request.POST['BetAccountBalance'])
            NetObj.save()
            return render(request, 'Account/Success.html', {'value':'Bet'})
            
        else:
            bound_form = form_Net(request.POST, instance=obj)
            context = {'NetObj':NetObj.AccountBal, 'form':bound_form, 'email':name}
            return render(request, template_name, context)

 

And here is my forms.py and it has a custom clean method for my IntegerField in my form

class TransferToMyBet(forms.ModelForm):
    class Meta:
        model = BetDetails
        fields = ['BetAccountBalance']

    def clean_BetAccountBalance(self):
        
        data = self.cleaned_data.get('BetAccountBalance')
        
        if data > 800:
              raise forms.ValidationError('Not Enough Money')
        else:
            return data

In my form page in the browser, when i give a value greater than 800, it raises the Validation error as expected. But when i give a value less than 800, the form page doesnt save. Infact it purely acts as if Bound_form.is_valid() is false.

 

Another thing is that, when i comment out the if statement in the forms.py custom clean method, It works perfectly fine. Does that mean that, if statement doesnt work well with an Integer custom field cleaning?

 

Guest May 25, 2017, 4:26 a.m. 0 Answer 

Django 1.5 + gunicorn - No module named website.wsgi?

I am taking over this django legacy project which was built on **1.5.12**. I have no idea why they decided to remove wsgi.py from the project. So I am trying to put it back it. 

wsgi.py

    import os
    
    # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
    # if running multiple sites in the same mod_wsgi process. To fix this, use
    # mod_wsgi daemon mode with each site in its own daemon process, or use
    # os.environ["DJANGO_SETTINGS_MODULE"] = "website.settings"
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings")
    
    # This application object is used by any WSGI server configured to use this
    # file. This includes Django's development server, if the WSGI_APPLICATION
    # setting points here.
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()


settings.py:

    try:
        from local_settings import *
    except ImportError:
        from default_settings import *

default_settings.py:

    ...
    ...
    ROOT_URLCONF = 'website.urls'
    
    # Python dotted path to the WSGI application used by Django's runserver.
    WSGI_APPLICATION = 'website.wsgi.application'

Then I compile the project with:

    $ python manage.py runserver 0.0.0.0:8000

    Validating models...
    
    0 errors found
    May 20, 2017 - 07:47:34
    Django version 1.5.12, using settings 'website.settings'
    Development server is running at http://0.0.0.0:8000/
    Quit the server with CONTROL-C.

It works fine and I can see `wsgi.pyc` is generated.

But when I run it with `gunicorn`, I get this error:

    No module named website.wsgi

Details output:

    $ gunicorn website.wsgi:application                 
    2017-05-20 07:50:00 [4552] [INFO] Starting gunicorn 18.0
    2017-05-20 07:50:00 [4552] [INFO] Listening at: http://127.0.0.1:8000 (4552)
    2017-05-20 07:50:00 [4552] [INFO] Using worker: sync
    2017-05-20 07:50:00 [4556] [INFO] Booting worker with pid: 4556
    2017-05-20 07:50:00 [4556] [ERROR] Exception in worker process:
    Traceback (most recent call last):
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker
        worker.init_process()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process
        self.wsgi = self.app.wsgi()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi
        self.callable = self.load()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 62, in load
        return self.load_wsgiapp()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load_wsgiapp
        return util.import_app(self.app_uri)
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app
        __import__(module)
    ImportError: No module named website.wsgi
    Traceback (most recent call last):
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker
        worker.init_process()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process
        self.wsgi = self.app.wsgi()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi
        self.callable = self.load()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 62, in load
        return self.load_wsgiapp()
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load_wsgiapp
        return util.import_app(self.app_uri)
      File "/var/www/html/foo/.env/local/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app
        __import__(module)
    ImportError: No module named website.wsgi
    2017-05-20 07:50:00 [4556] [INFO] Worker exiting (pid: 4556)
    2017-05-20 07:50:00 [4552] [INFO] Shutting down: Master
    2017-05-20 07:50:00 [4552] [INFO] Reason: Worker failed to boot.

Why? What have I missed?

Guest May 20, 2017, 8:10 a.m. 0 Answer 

Please help

This is a copy of my question in stackoverflow, please help. http://stackoverflow.com/questions/44001085/how-to-get-request-metahttp-host-in-settings-py

 

I am making a django application where it will have 2 apps. When you open www.webName.co.id it will use urls.py from app A, but when you open webName.co.uk it will use urls.py from app B

This is the urls.py from the main project:
    
    urlpatterns = [
    url(r'^tinymce/', include('tinymce.urls')),
    url(r'^filer/', include('filer.urls')),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
    url(r'^admin/', admin.site.urls),
    ]

I was planning to add something like this to that file:

    if settings.CURRENT_HOST_IP == 'www.webname.co.id':
        urlpatterns += url(r'^', include('webname_id.urls')),
    else:
        urlpatterns += url(r'^', include('webname_uk.urls')),

That way, it will simply use the urls from the app that is being used, depending on the current www you are entering the site with.

So my project have 1 backend admin, but multiple front-end templates and urls. The problem is i can't figure out how to set CURRENT_HOST_IP in the settings.py,

Usually i use this to get the current IP / host the user is using:
    
     request.META['HTTP_HOST']

But i can't access the request object in settings.py

Guest May 16, 2017, 8:35 a.m. 1 Answer 

pop up window in django

Hey, this for loop can only display one course when i press the pop up button, I don't unserstand why it cannot loop through all the courses. Without the pop up i can display all the courses. Please help!!!Thanks in advance!!
<td>
    <div data-role="main" class="ui-content">
        <a href="#myPopup" data-rel="popup">Courses</a>
        <div data-role="popup" id="myPopup" class="ui-content" style="min-width:250px;">
            {% for n in college.junction_set.all %}
                    {{ n.course_name }}
                    {{ n.course_name.examiner_body }}
                    {{ n.course_name.course_capacity }}<br>
            {% endfor %}
        </div>
    </div>
</td>

 

Guest Oct. 10, 2016, 8:26 a.m. 0 Answer 

DB design

Hi.I am into django for hardly 6 months.And hence I am not that great in designing Databases.So can any one provide a sample models for creating an e commerce website?(including basic features like user cart etc.)

Guest Aug. 28, 2016, 1:33 p.m. 1 Answer 

Language

Hi, i wanted to ask about djangocms. How can I add new language for translation this site

tolqinbek_isoqov@mail.ru July 20, 2016, 11:59 p.m. 1 Answer 

How do I create a folder for a model when I submit the form in the admin page?

Hello. I'm new to Django and I'm having trouble figuring out how to do it.

 

My model is like this:

class Clinica(models.Model):
    def __str__(self):
        return self.nome

    nome        = models.CharField(max_length=20)
    site        = models.URLField(blank=True,null=True)
    folder      = models.FilePathField(blank=True,null=True)
    data_inc    = models.DateTimeField('Data Publicada')
    data_lim    = models.DateField('Vencimento')

 

How can I create that folder?

Guest July 19, 2016, 4:20 p.m. 0 Answer 

logging-in into a webpage using our LDAP credentials in django using django_auth_ldap module

I am using django_auth_ldap module to authenticate LDAP users who are logging into my web page.

Edited my settings.py file as per the document https://pythonhosted.org/django-auth-ldap/example.html

import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType


# Baseline configuration.
AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"

AUTH_LDAP_BIND_DN = "cn=django-agent,dc=example,dc=com"
AUTH_LDAP_BIND_PASSWORD = "phlebotinum"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
    ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
# or perhaps:
# AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"

# Set up the basic group parameters.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=django,ou=groups,dc=example,dc=com",
    ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn")

# Simple group restrictions
AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=django,ou=groups,dc=example,dc=com"
AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=django,ou=groups,dc=example,dc=com"

# Populate the Django user from the LDAP directory.
AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail"
}

AUTH_LDAP_PROFILE_ATTR_MAP = {
    "employee_number": "employeeNumber"
}

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_active": "cn=active,ou=django,ou=groups,dc=example,dc=com",
    "is_staff": "cn=staff,ou=django,ou=groups,dc=example,dc=com",
    "is_superuser": "cn=superuser,ou=django,ou=groups,dc=example,dc=com"
}

AUTH_LDAP_PROFILE_FLAGS_BY_GROUP = {
    "is_awesome": "cn=awesome,ou=django,ou=groups,dc=example,dc=com",
}

# This is the default, but I like to be explicit.
AUTH_LDAP_ALWAYS_UPDATE_USER = True

# Use LDAP group membership to calculate group permissions.
AUTH_LDAP_FIND_GROUP_PERMS = True

# Cache group memberships for an hour to minimize LDAP traffic
AUTH_LDAP_CACHE_GROUPS = True
AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600


# Keep ModelBackend around for per-user permissions and maybe a local
# superuser.
AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

I want clarification on few things. i,e to get a login page and to authenticate the logged in LDAP user:

  1. login url, login view, html template for login page should be created explicitly" ??
  2. If they are autogenerated, how can we get the username and password entered by user and search for the same using AUTH_LDAP_USER_SEARCH.

Guest May 18, 2016, 5:39 a.m. 0 Answer 

Problem with running Django admin panel

I am new in Django. After running server when I enter the server address then it works fine. But when I put(/admin) after the url then Django ask me to enter username and password. The funny thing is when I enter anything in username and password box and press login then it redirect me to the desired page. How can I get rid of it?

 

Guest May 3, 2016, 2:04 p.m. 1 Answer 

Django for Plotting

Hello 

Is it possible to Plot data (.csv) into a hosted website designed using Django ?

data will be sent from a computer ( or mini computer like Raspberry ) to server where it will be plotted into STREAMING GRAPHS, Users can have access to the live streaming or archive

Is that possible with only Django/python?

 

Thank you.

mehdikun1@gmail.com April 1, 2016, 5:42 p.m. 2 Answer 

Showing most visited article in my blog

 

Hi,

In the blog there will be many article. So i have a question How to show  most visited article in a window in my blog font page? please feedback with details so that i can add this solution in my blog.

 

thanks a lot.

Rana

ranafge@gamil.com Feb. 16, 2016, 12:14 p.m. 1 Answer 

Showing most visited article

Hi,

In the blog there will be many article. So i have a question How to show  most visited article in a window in my blog font page? please feedback with details so that i can add this solution in my blog.

 

thanks a lot.

Rana

Guest Feb. 16, 2016, 12:11 p.m. 0 Answer 
Load More Questions

Codility : Nesting

Determine whether given string of parentheses is properly nested.

email@djangotutsme.com April 21, 2016, 9:03 a.m.

Codility : Brackets

Determine whether a given string of parentheses is properly nested.

email@djangotutsme.com April 18, 2016, 2:31 a.m.

Bubble sort in Python

In this article you can see how to use Bubble sort in python

email@djangotutsme.com April 16, 2016, 9:36 a.m.

Codility : Triangle

Determine whether a triangle can be built from a given set of edges.

email@djangotutsme.com April 6, 2016, 8:23 a.m.

Codility : Distinct

Compute number of distinct values in an array.

email@djangotutsme.com April 6, 2016, 7:53 a.m.

Codility : MinAvgTwoSlice

Find the minimal average of any slice containing at least two elements.

email@djangotutsme.com April 5, 2016, 2:12 p.m.

Codility : PassingCars

Count the number of passing cars on the road.

email@djangotutsme.com March 29, 2016, 3:49 a.m.

How to add custom django manager

In this article I'll show you how to create custom django manager. A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application.

email@djangotutsme.com Jan. 5, 2015, 8:42 a.m.