Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tracking user web search history in Django
I am implementing a Django powered website in which I need to track the websites visited by a logged in user.I had googled it but didn't find anything specific to Django. I know there is a documentation available at link Can anyone please recommend some django specific document or some algorithm which is independent of the web browsers. Thanks . -
django.core.exceptions.FieldError: Unknown field(s) (academic_grade) specified for User
I am creating a form, inside forms.py I have: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'academic_grade',] But I get the following error: django.core.exceptions.FieldError: Unknown field(s) (academic_grade) specified for User I check in the database and user table have the 'academic_grade' grade column models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, blank=True, default='') academic_grade = models.CharField(choices=GRADE_CHOICES, default='') please guide me through this -
Delete an old form on radio button selection
I am beginner with django .. I couldn't find how to delete an old form when a radio button is selected and starting with a new form to be saved in models.py. I mean that on the selection of the first radio button i have a form with parameters, when i select the second radio button the old parameters must be deleted and i should define new parameters to be saved. tab_value test the value of radio button.. maybe here i should delete a form and define a new one ? I couldn't find a clear method to do this. Html : <div class="row"> <div class='col-md-9'> <div id="tabs"> <form action="{% url "backtest" %}" method='POST' role='form' id='form'> {% csrf_token %} <input type="radio" name="tabs" value="first" id="toggle-tab1" checked="checked" /> <label for="toggle-tab1">Long</label> <input type="radio" name="tabs" value="second" id="toggle-tab2" /> <label for="toggle-tab2">Short</label> <input type="radio" name="tabs" value="third" id="toggle-tab3" /> <label for="toggle-tab3">Long and Short</label> <div id="tab1" class="tab" > {% include 'tags/parameters_form.html' %} {% 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> … -
django - Connect an existing MySQL db to Django
I have a database that i would like to use for an app in my new Django project. I tried adding it to the setting.py by doing the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Colta_create'), 'USER': 'root', 'PASSWORD': 'toor123', 'HOST': '', 'PORT': '' } } I have installed mysqlclient, but i get this error: django.db.utils.OperationalError: (1049, "Unknown database 'colta_create'") -
(Django) forms.py: NameError: name 'Article' is not defined
Disclaimer: I am sorry if this is a stupid question, but I am looking at this code for the past hour and just can not find the mistake So, I am getting the following error message: "File "C:\Users\Daniel\Desktop\Programmieren\venv\src\blog\forms.py", line 10, in Meta model = Article NameError: name 'Article' is not defined" This is the relevent part in my forms.py: from django import forms from .models import * class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('article_title', 'article_text',) This is the relevent model in my models.py class Article(models.Model): article_title = models.CharField(max_length=200) article_text = models.TextField() article_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.article_title def get_absolute_url(self): return reverse('blog.views.article_detail', args=[str(self.id)]) I am grateful for any help! -
variable in login_url in django login_required decorator
I am building an app where multiple institutes will have their account. So I am trying to build urls in such a way that each institute can have urls like example.com/institute1_name , example.com/institute2_name etc. For this I have below code in my root url file. urlpatterns = [ url(r'^home/', include('homepage.urls', namespace='homepage')), url(r'^students/', include('students.urls', namespace='students')), ] # institute home page URLs urlpatterns += [ url(r'^zeal/', include('institute.urls', namespace='institute')), # zeal is an institute url(r'^demo_institute/', include('institute.urls', namespace='institute')), # demo_institute is another institute # more institutes will be added here. ] Question 1: Is this the best way to achieve this? code in institute urls.py file is as below: from django.conf.urls import url from institute import views app_name = "institute" urlpatterns = [ url(r'^$', views.institute_home, name='home'), url(r'^signin/$', views.signin, name='signin'), url(r'^logout/$', views.institute_logout, name='logout'), url(r'^home/$', views.institute_home, name='institute_home'), Now when I open example.com/zeal/signin it opens the signin page. But when I try example.com/zeal/ it requires login and It looks for login url. Code in my home view of institute is as below : @login_required(login_url='/institute/signin/') @user_passes_test(is_institute, login_url="/institute/signin/") def institute_home(request): data = {} # more code here Question 2 : How can I redirect user to institute specific login url. For example if user hit example.com/{insti-name} and user was … -
Filtering Django QuerySet based on ManyToMany relationship existence
The Models Here is the basic models setup we have. A List has many Items, and an Item can be in many Lists. For a given Item, if any of its Lists are good (i.e., list.bad == False) then the Item is good. If an Item doesn't appear in any good Lists, then it is bad. We have a custom QuerySet for Items, with a method for returning only good Items, and a method for returning only bad Items. class Item(models.Model): objects = ItemQuerySet.as_manager() name = models.CharField(max_length=255, unique=True) class List(models.Model): name = models.CharField(max_length=255, unique=True) bad = models.BooleanField(default=True) items = models.ManyToManyField(Item, related_name='lists') class ItemQuerySet(models.QuerySet): def bad(self): return self.exclude(lists__bad=False) def good(self): return self.filter(lists__bad=False) The Scenario Here's an example of a scenario we're having trouble with: one bad List, one good List, and two Items. BadList: GoodList: - Item1 - Item1 - Item2 Since Item1 appears in at least one good list, it should come up in Item.objects.good(), and not in Item.objects.bad(). Since Item2 does not appear in any good list, it should come up in Item.objects.bad(), and not in Item.objects.good(). We can set up the scenario like so: # Create the two lists. >>> goodlist = List.objects.create(name='goodlist', bad=False) >>> badlist = List.objects.create(name='badlist', … -
error value while trying to get floor after multiplying with 1000
I tried to multiply float value with 1000, but it gives wrong value a = 10.0057 floor(a * 10000) 100056.0 expected answer is 100057 and when i check a * 10000 100056.99999999999 actual answer should be 100057.0 is it a python error -
Why am I getting recursion error?
Why am I getting an error when trying to run my server to access the database to see if my code works? While in my projects folder in Terminal, I ran sudo python manage.py runserver to try to run the server but it doesn't work because of the aforementioned error. I've looked around SO but can't find one directly related to my problem. I'm getting my if() statement is the problem. The error I'm getting says: RuntimeError: maximum recursion depth exceeded while calling a Python object Here's my views.py file: from .models import Album from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.core.urlresolvers import reverse_lazy from django.views import generic from django.views.generic import View from django.views.generic.edit import CreateView, UpdateView, DeleteView from .forms import UserForm class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DeleteView): model = Album template_name = 'music/detail.html' class AlbumCreate(CreateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:index') class UserFormView(View): form_class = UserForm template_name = 'music/registration_form' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def … -
Django display and format group names in template
Having issues getting this information formatted correctly in my template. I've searched google and stack overflow extensively, but I haven't been able to solve this issue. I'm using django-role-permissions and I've created a bunch of roles, whcih get assigned to the group of each user. I want to display all the groups that they are in on my template with a comma in between. I also want to trade out the '_' between the names with a space. The closest I have come is to get the group names dispayed like the following: Driver Freight_manager System_admin Employee_manager I've tried a few custom templatetags but everything splits it into an individual character with a ',' between. Ultimately, I want it to look like the following, but I can't figure it out: Driver, Freight Manager, System Admin, Employee Manager Here is my template code: {% for g in profile_detail.user.groups.all %} {{ g.name|capfirst }} {% endfor %} I'm assuming that I can do this in a template and don't have to modify the view. Can someone help me with a templatetag or something to get this working? It's driving me nuts. -
Uploading file from a web from in django
I am trying to upload a file from my webfrom, I am not sure how to handle this in the backend. My model looks like this `from __future__ import unicode_literals from django.db import models` class RequesterInfo(models.Model): department = models.CharField(max_length=200) primary_contact = models.CharField(max_length=50) project_name = models.CharField(max_length=200) request_sponsor = models.CharField(max_length=200) email = models.EmailField(max_length=200) description = models.CharField(max_length=1000) date_submitted = models.CharField(max_length=100) time_constraints = models.CharField(max_length=200) priority = models.CharField(max_length=10) comments = models.CharField(max_length=250) attachments = models.FileField(upload_to='Files') Am I doing it the right way? Files is a folder in my current directory. Do I need to use MEDIA_ROOT now? I don't find any MEDIA_ROOT in my settings.py? Can someone help me in handling this -
Django form not saving password when creating user
I have made a custom form for my django app which allows users to register themselves for the website. This is the form for my django app: class TeacherRegistrationForm(UserCreationForm): email = forms.EmailField(required = True) school = forms.CharField(required = True) subject = forms.CharField(required = True) head_of_subject = forms.BooleanField(required = False) identification_code = forms.CharField(required = True) def __init__(self, *args, **kwargs): super(TeacherRegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].help_text = '' self.fields['password2'].help_text = '' class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'school', 'identification_code', 'subject', 'head_of_subject', 'password1', 'password2' ) def save(self, request): form = TeacherRegistrationForm(request.POST) user = User.objects.create(first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name'], email=self.cleaned_data['email'], username=self.cleaned_data['username'], password=self.cleaned_data['password1'] ) teacher_profile = TeacherProfile.objects.create(user=user, school=self.cleaned_data['school'], subject=self.cleaned_data['subject'], head_of_subject=self.cleaned_data['head_of_subject'], ) return user, teacher_profile This is the relevant part of the view: if request.method == 'POST': form = TeacherRegistrationForm(request.POST) entered_school_name = form['school'].value() entered_school_id = form['identification_code'].value() actual_school_id = SchoolProfile.objects.get(school_name__exact = entered_school_name).identification_code if form.is_valid()and (entered_school_id == actual_school_id): user, teacher_profile = form.save(request) return render(request, 'accounts/home.html') else: args = {'form': form} return render(request, 'accounts/reg_form.html', args) When I press submit, the user is created, however no password is set for the user -
Getting "ImportError: No module named models" error when running Celery worker
$ celery -A openduty worker -l info Traceback (most recent call last): File "/usr/local/bin/celery", line 11, in sys.exit(main()) File "/usr/local/lib/python2.7/site-packages/celery/main.py", line 30, in main main() File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/local/lib/python2.7/site-packages/celery/bin/base.py", line 311, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 785, in handle_argv return self.execute(command, argv) File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 717, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/usr/local/lib/python2.7/site-packages/celery/bin/worker.py", line 179, in run_from_argv return self(*args, **options) File "/usr/local/lib/python2.7/site-packages/celery/bin/base.py", line 274, in call ret = self.run(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/celery/bin/worker.py", line 212, in run state_db=self.node_format(state_db, hostname), **kwargs File "/usr/local/lib/python2.7/site-packages/celery/worker/init.py", line 95, in init self.app.loader.init_worker() File "/usr/local/lib/python2.7/site-packages/celery/loaders/base.py", line 128, in init_worker self.import_default_modules() File "/usr/local/lib/python2.7/site-packages/celery/loaders/base.py", line 116, in import_default_modules signals.import_modules.send(sender=self.app) File "/usr/local/lib/python2.7/site-packages/celery/utils/dispatch/signal.py", line 166, in send response = receiver(signal=self, sender=sender, **named) File "/usr/local/lib/python2.7/site-packages/celery/fixups/django.py", line 73, in on_import_modules self.worker_fixup.validate_models() File "/usr/local/lib/python2.7/site-packages/celery/fixups/django.py", line 158, in validate_models django_setup() File "/usr/local/lib/python2.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python2.7/importlib/init.py", line 38, in import_module import(name) File "/home/ec2-user/git/openduty/openduty/models.py", line 13, in from schedule.models import Calendar ImportError: No module named models -
Django silk middleware error
Im trying to add django silk to my project, and want to add the user ID for each of the logged requests on my app. This is how I have my middleware set: MIDDLEWARE_CLASSES = ( 'logger.middleware.LoggerMiddleware', 'silk.middleware.SilkyMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', 'middleware.loginrequired.LoginRequiredMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) As you can see, theres only one middleware above silk. This middleware just adds the user ID to an http header: class LoggerMiddleware: """. """ def process_request(self, request): session_key = request.COOKIES.get('sessionid') print session_key if session_key: try: session = Session.objects.get(session_key=session_key) uid = session.get_decoded().get('_auth_user_id') print uid request.META['HTTP_USER_ID'] = str(uid) except Exception as inst: print "the exception: " print inst The problem is that every time I try to do a post request I get the exception: Silk middleware has not been installed correctly. Ordering must ensure that Silk middleware can execute process_request and process_response. If an earlier middleware returns from either of these methods, Silk will not have the chance to inspect the request/response objects. Can anyone tell me what Im doing wrong and if there is an easier way to record the user that is making the requests on silk? -
dynamically appending ng-click is not working when there is switch between pages
I am new to angular js any help will be appreciated thanks in advance. The issue i am facing is I have one page called Page1 which has ng-click in dynamically created element and another page called page2. When i go from page1 to page2 and comes back to page1 ng-click is not working.I have tried lot of things but bad luck nothing is working. Please help with this.Below is the sample code: $scope.idh_str=header_str+'<tbody id="InventoryReportData">'; for(i=0;i<response.length;i++){ $scope.datastring=$scope.datastring+'<tr><td class="create_action" style="width:9.09%;"><a style="cursor:pointer;" ng-click="foo(response[i].a,response[i].b)" ><i class="fa fa-external-link" aria-hidden="true"></i></a></td></tr>'; } tbody_str = $scope.idh_str + $scope.datastring +'</tbody>'; angular.element($('#InventoryDataTable')).append($compile(tbody_str) ($scope)); /*----function call which is inside the controller only---*/ $scope.foo = funtion(a,b){ // do something } -
Django - default port 0 instead of 3306 - Can't connect to MySQL server on '127.0.0.1' (61)
I am trying to run my Django server but I get error (2003, "Can't connect to MySQL server on '127.0.0.1' (61)"). I have found information in this topic that the problem can by caused by MySQL port. I had checked it using SHOW GLOBAL VARIABLES LIKE 'PORT'; and I got value 0. It seems to me that it may be a reason. I have checked in my.cnf default port but everything seems to look good port = 3306. I wonder what should I do now? Thanks in advance. -
csrf_token missinig or incorect, even after including the token tag
I am getting a 'CSRF token missing or incorrect' error, but I have already added the {% csrf_token%} tag in the web form. Any idea why I still face this error? `def index(request): if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): form.save() return render(request, 'index.html') else: form = RequestForm() return render(request, 'index.html', {'form': form})` I cannot post the template, but I use the token as shown in line below <form id="reqForm" action="" method="POST" enctype="text/plain">{% csrf_token %} -
Should I put the gmap geocode to calculate the lat/lng from an address in the view.py or in the model.py?
My goal is to: take an address submitted by a user using generic python forms take the address data and calculate the lat/lng for the address store the address data and the lat/lng data in the same row of a database I've been told that the geocode should be calculated within the models.py. How does django take data submitted from a form make a calculation then input the entire data set into a database? I'm using django 1.11, Python 3.6 and gmaps api. I can calculate the lat/lng in the views.py but was told to put all business login in the models.py and I don't know how to move the lat/lng code into the models.py. Look forward to any suggestions. -
django javascript on form field to change dropdown to textfield on selecting a particular option from the dropdown
I have written some javascript code which converts a form field which is a choice field to textfield when the user selects the choice 'Other' from the options and lets the user enter data in the field which was initially a dropdown. That works fine but when i revisit the form to edit the field does'nt show the textfield data entered but shows the dropdown again with the default choice. This is the javascript- $(document).on('change', '#id_url', function(){ if($(this).val() === 'Other'){ var input = $('<input>', { id: this.getAttribute('id'), name: this.getAttribute('name'), type: 'text' }); $(this).replaceWith(input) } }); form- from django import forms from cms.models import Title from ohrp_cms_plugins.models import PluginModel class PluginForm(forms.ModelForm): class Meta: model = PortalServicesPluginModel fields = ['name', 'icon', 'url'] labels = { 'name': 'Name', } def __init__(self, *args, **kwargs): super(PluginForm, self).__init__(*args, **kwargs) choices = [(o.slug, o.title) for o in Title.objects.filter(published=True).order_by('title').distinct('title')] choices.append(('Other', 'Other')) self.fields['url'].widget = forms.Select(choices=choices) class Media: js = ('js/plugin.js',) -
django how to recover a single field from sqlite3
i have this register on my db: id nome email senha 2 teste teste@teste.com 1234 i'm trying to recover the 'senha' from the table, and i'm trying to use the rawqueryes usuario = request.GET.get('enderecoEmail') -- teste@teste.com senha2 = Usuario.objects.raw('select senha from projeto_usuario where email = %s',[usuario]) just for test i'm sending the argument to an html just to print return render(request, 'projeto/teste.html',{'senha':senha2,'usuario':usuario}) however what i'm getting as result is <RawQuerySet: select senha from projeto_usuario where email = teste@teste.com> i wanna know how can i retrieve that field from the sqlite3, i have been reading the whole documentation, but i really don't know what i'm missing -
django-tables2 updating attrs has no effect
This piece of code: def inject_data_names(table: tables.Table) -> tables.Table: for col_name, col in table.columns.items(): col.attrs['td']['data'] = str(col_name) print(col.attrs) return table seems to have no effect, when run on an instance of a child of tables.Table. The print statement shows this: {'class': 'paleblue table', 'th': {'class': 'id orderable'}, 'td': {'class': 'id'}} {'class': 'paleblue table', 'th': {'class': 'description orderable'}, 'td': {'class': 'description'}} {'class': 'paleblue table', 'th': {'class': 'orderable start'}, 'td': {'class': 'start'}} As you can see, the "data" value seems to be missing. Using Python 3.6.1, latest Django and django-tables2. Any clues? -
Generating WagtailCMS Document Previews
Is there a way to extend Wagtail's documents to show file previews? There's a service ( I have not tested ), which looks cool, but the free plan to Pro plan is a huge leap in cost. I am hoping someone has figured this out already and can point me to the solution. Thank you. -
Web Application Help, ASP.Net or Django or others?
This is a web application question. The source is a Access file for collecting users' info, updating complain status and liking to SQL server. The task is to deliver it to web. My question is what tool or software I should choose, ASP.net (web forms or MVC), Django or others? I'm totally new to this area. Any suggesting courses will be greatly appreciated. -
How do I remove "CY" from a year in loader.py?
I'm creating a website with Django that involves data from a CSV file. I got the loader script to work but I'm trying to tweak it to remove "CY" from the year (which shows up as "CY 2011" for example). Any suggestions or solutions would be greatly appreciated! -
Getting CSRF token missing or incorrect, even after adding the token in the web from
I am getting a 'CSRF token missing or incorrect' error, but I have already added the {% csrf_token%} tag in the web form. Any idea why I still face this error?