Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django request param from urls into views not working
I m trying to request table_id from table_base.html and is not returning anything. This my table_base.html <div class="container"> <div class="jumbotron"> <h1> {{ table_name }} List</h1> {% if list_tables %} <table class="table table-bordered sortable"> <thead> <th>Id</th> <th>Name</a></th> <th>Date</a></th> <th>Search Button</th> </thead> {% for list in list_tables %} <tr> <td><a href="#" >{{ list.id }}</a></td> <td> <a href="{% url 'tables:addview' table_id=list.id %}" name="table_name">{{ list.name }}</a> </td> <td>{{ list.date }}</td> <td><a href="#">Search</a></td> </tr> {% endfor %} </table> {% else %} <p> No Records Found</p> {% endif %} </div> </div> This is my tables/urls.py urlpatterns = [ url(r'^$', views.table_base, name='tables'), url(r'^(?P<table_id>\d+)$', views.AboutDetail.as_view(), name='details'), url(r'^(?P<table_id>\d+)/details$', views.addview, name='addview') ] This is my tables/views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self, **kwargs): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: return Crawledtables.objects.get(id=self.kwargs['table_id']) def addview(request, table_id): q = request.GET.get('table_id') print q table_name = Crawledtables.objects.get(id=q) print table_name AllTables._meta.db_table = table_name.name tbl_detail = AllTables.objects.order_by('id') return render(request, 'tables/table_list.html', {'details': tbl_detail}) It works 1 time. When I select the first table (table with id 1) it gives me all the info. When I try to select another … -
Django ModelAdmin's list_editable in the Wagtail ModelAdmin?
Django's ModelAdmin.list_editable class is super handy and I reeeeaally need it, but I'm not sure how to go about implementing in Wagtail's IndexView. Where do I begin? -
SQL database data into webpage using Django
Hi I have a very large dataset with 300,000 rows that I need to somehow insert into the webpage, unfortunately the webpage takes a long time to load with all of that information, is there a way using Django and python, that I can throw the data into some kind of list and then show it page by page? Thanks. -
Django: Querying Database
Here's my model, class Answer(models.Model): .... likes = models.ManyToManyField(User, related_name='answer_likes') timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) I wants to filter out the Answers which received maximum likes in last 24 hours. I got this solution, timing = datetime.now() - timedelta(hours=24) data = Answer.objects.filter(timestamp__gte=timing).annotate(final=Count('likes')).order_by('-final') But this is not what I want. I wants to filter out the answers which received the maximum likes in last 24 hour in the entire database not the ones asked in last 24 hours & received maximum likes. How can i do that? Thank You :) -
How to use a customized 404 page in Django CMS
Django allows to use customized error views, but I would like to take advantage of the CMS and use one of his pages for displaying the error. I have tried adding handler404 = 'hotels.views.page_not_found_view' to urls.py, and then rewrite the request in the view so it renders my error page: from cms.views import details def page_not_found_view(request): return details(request, 'page_not_found') But no luck so far, the app cannot find the path, Does somebody know an easy way to achieve this without using redirections? -
How to sort based on a choice field in django in template
Consider the following model: class Category(models.Model): name = models.CharField(max_length=100) description = models.TextField() POSITIONS = ( ('L', 'Left'), ('R', 'Right') ) position = models.CharField(max_length=1, choices=POSITIONS, default='R') class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name I want to sort the objects in a manner such that I can separate the left ones from the right ones and show them in separate parts of the html document. Something like: {% for category in categories|sort_by: "position" = "left" %} <ul class="collection with-header"> <li class="collection-header"> <h3>{{category.name}}</h3> <p><small>{{category.description}}</small></p> </li> {% for url in category.extra_link_set.all %} <li class="collection-item"><a href="{{url.url}}">{{url.url_text}}</a></li> {% endfor %} </ul> {% endfor %} I know this wont work. But I am just trying to give an idea as to what I want. Also would the process be similar for any other field type in django models? -
How should be done authentication using both Django Rest Framework and Django websockets in one project?
I use in project both Django channels with websockets and Django Rest Framework. I wonder whether there is any way to have one common Token for every user for authentication in Rest and websockets? Or maybe there should be two different tokens for every user, one in DRF and another for websockets? -
How to rename a field in a Django form?
I have a custom Django widget that renders some HTML that I cannot control, and by default the widget's HTML will has a fixed name attribute using a -, say name="field-name". My problem is that Django expects the name attribute in the HTML to be exactly the same as the variable name of the field in python. But of course in python I cannot name a variable using -. Is there any way to tell Django to decouple the variable name of the form field from the name in the HTML? In other words, when the user already introduced the data in the field and sends the POST request, can I tell Django that the field field_1 should be reading the value field-name from the requests.POST dictionary? -
Django apps not showing in admin when site is deployed to server
I have a test site which I am (trying) to get deployed to an Ubuntu 16.04 server. If I run the site using the Django server (python manage.py runserver 0.0.0.0:8000), I can see all of the apps when I visit the admin page as the superuser, and everything is fine. However, when I run the site normally, using wsgi, the only apps I can see (and interact with) in the admin are for the users and groups. None of the apps I have created are visible, and if I try and navigate to a change list page for one of them for example, I get a page not found. I believe my mod_wsgi set up is ok, in that I can view the admin and login, so I don't believe this is the problem. Perhaps it's a permissions issue? Any help much appreciated! -
Django Distinct and Foreign Key filtering Query
I found questions about this problem but no working answer, so any help is appreciated :) I want to display a list of the lastest Record made by each Client. Records is a model, which has Client as a field. Client is a ForeignKey for User. For example #Initially: Client3 --- Record6 Client2 --- Record5 Client2 --- Record4 Client1 --- Record3 Client1 --- Record2 Client1 --- Record1 #Wanted: we only keep one Record per Client, the lastest one. Client3 --- Record6 Client2 --- Record5 Client1 --- Record3 This is what I have tried: def LastRecordPerClient(request): id_list = Record.objects.order_by('-date').values_list('client__id').distinct() records = Record.objects.filter(id__in=id_list) return (request, 'records/record_list.html', {"records": records}) This is what I get in my shell: <QuerySet []> Any idea? -
Recursion Error - Maximum Recursion dept exceeded when ForeignKey('self') django
I am getting an error in admin console while trying to open a model (employees in my case). This is occurring after adding a field which is a ForeignKey('self'). I guess it is conflicting with str method. If I comment out the method, there is no error, but all the objects in the model are appearing as 'employee object'. Here is what my error looks like https://ibb.co/jHt84Q Here is my models.py: from django.db import models import calendar from datetime import datetime from datetime import timedelta class employees(models.Model): emp_id=models.PositiveIntegerField() emp_name = models.CharField(max_length = 100) emp_lname = models.CharField(max_length = 100) emp_loc = models.CharField(max_length = 100,null=True) manager_id=models.ForeignKey('self',null=True,blank=True) image=models.ImageField(upload_to='profile_image',default='/profile_image/profile-icon.png') email = models.EmailField(default='app-engine@gmail.com', blank=False) def __str__(self): return str(self.emp_id) + '-' + self.emp_name + '-' + self.emp_loc+'-'+str(self.manager_id) class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() status=models.CharField(max_length=1,default='P') ltype=models.CharField(max_length=2) message=models.CharField(max_length=500,blank=True) date_created = models.DateTimeField(auto_now_add=True) def leave_length(self): return self.end_date - self.start_date+timedelta(days=1); def __str__(self): return str(self.id) + '/' + str(self.employee.emp_name) +'/'+str(self.start_date) +'/'+str(self.end_date) +'/'+str(self.status)+'/'+str(self.date_created) -
Django - Get parent object with children's object
I'm new to Django so I might miss the answer for this one because of terminology. I am trying to get parent object with children objects, I've got: Product.objects.all().filter(sub_category__category_id=category_id).select_related() I am trying to get parent category object within the children objects I've already got. Thanks in advance :) -
Saving Post data to the database using django
I am trying to save post data for a custom user registration but I can't identify where I am going wrong. I am suspecting the problem is in mainapp/urls but I cannot figure out why. I have done some research on the subject read the following https://docs.djangoproject.com/en/1.11/topics/http/urls/ Django: Save Form Data to Database Django Forms: if not valid, show form with error message and many others but I cannot find the problem. Here are my models from django.db import models # Create your models here. class User(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 100) username = models.CharField(max_length=30) email = models.EmailField(unique = True) password1 = models.CharField(max_length=255) password2 = models.CharField(max_length=255) My custom form import re from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ObjectDoesNotExist class RegistrationForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) help_texts = { 'username': None, 'email': None, 'password': None, } def clean(self): cleaned_data = super(RegistrationForm, self).clean() password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if not password2: raise forms.ValidationError("You must confirm your password") if password1 != password2: self.add_error('password2', "Password does not match") return cleaned_data def save(self, commit=True): user = … -
django get value from html
I want to list all tables using my Crawledtables, and when i click table1 i need to pass in the table_id. With that table_id i need to get the table_name and list all the info inside that table. i m stuck at getting the table_id this is my views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self, **kwargs): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: id_table = Crawledtables.objects.get(id=self.kwargs['table_id']) return id_table def addview(self, request, **kwargs): id_table = request.POST.get("table_name") if id_table is not None: print id_table # with this table_id i need to get the table_name # need to use the table_name to get the content using # Ex: test = AllTables.objects.all() pass # i need to return the the content of the table id else: pass this is my table_base.html <br> <div class="container"> <div class="jumbotron"> <h1> {{ table_name }} List</h1> {% if list_tables %} <table class="table table-bordered sortable"> <thead> <th>Id</th> <th>Name</a></th> <th>Date</a></th> <th>Search Button</th> </thead> {% for list in list_tables %} <tr> <td><pre><a href="#" >{{ list.id }}</a></pre></td> {# this is where i get the id … -
django-admin startproject not working
I have created django file using django-admin startproject command and the file was saved in C drive, but I can't find that file in C drive. So I again created django file with same name and it gives error : CommandError: 'C:\WINDOWS\system32\website' already exists Can someone help me to solve this problem. Thanks in advance!!! -
Django ORM filter multiple values in multiple columns
I have SQL ... WHERE (id, case, date) IN (SELECT ...) My question is How can I do this in .filter() in Django ORM. -
KeyError: 'manager' in django get_initial
I working on FormView, and I need to set initial from another object, an example in my case we use Question model to set an initial for QuestionSuggestedEditsForm. But we got an error when updating the initial dict. 1. forms.py class QuestionSuggestedEditsForm(forms.ModelForm): class Meta: model = QuestionSuggestedEdits fields = ['title', 'description', 'tags'] 2. views.py class QuestionSuggestedEditsCreate(LoginRequiredMixin, RevisionMixin, FormView): template_name = 'app_faq/question_suggested_edits_create.html' form_class = QuestionSuggestedEditsForm model = QuestionSuggestedEdits def get_object(self): return get_object_or_404(Question, pk=self.kwargs['pk']) def form_valid(self, form): initial = form.save(commit=False) initial.question = self.get_object() initial.editor = self.request.user initial.save() form.save_m2m() messages.success(self.request, _('Suggeste edits Question successfully created!')) return redirect(reverse('question_redirect', kwargs={'pk': initial.pk})) def get_initial(self): initial = super(QuestionSuggestedEditsCreate, self).get_initial() for field, _cls in self.form_class.base_fields.items(): value = getattr(self.get_object(), field) # got a value #initial.update({field: 'no error'}) initial.update({field: value}) # traceback goes here.. return initial def get_context_data(self, **kwargs): context = super(QuestionSuggestedEditsCreate, self).get_context_data(**kwargs) context['question'] = self.get_object() return context And we got a traceback KeyError: 'manager'; File "/home/foobar/ENV/env-django-faq/lib/python3.5/site-packages/django/forms/boundfield.py", line 257, in build_widget_attrs if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute: File "/home/foobar/ENV/env-django-faq/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/foobar/ENV/env-django-faq/lib/python3.5/site-packages/django/forms/boundfield.py", line 245, in initial data = self.form.get_initial_for_field(self.field, self.name) File "/home/foobar/ENV/env-django-faq/lib/python3.5/site-packages/django/forms/forms.py", line 506, in get_initial_for_field value = value() File "/home/foobar/ENV/env-django-faq/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 842, in __call__ manager = getattr(self.model, kwargs.pop('manager')) KeyError: 'manager' -
Allow permission for get method for all users and allow post method for super user only in django rest api
class CategoryViewSet(viewsets.ModelViewSet): """ViewSet for the Category class""" queryset = models.Category.objects.all() serializer_class = serializers.CategorySerializer permission_classes = [permissions.IsAuthenticated] How do I allow get method for all user and post method for superusers only. -
How do I start the service automatically when Ubuntu starts?
I'm using Ubuntu 16 and I want to start the service. The service should start automatically when the system starts. The service starts the django server. [Unit] Description=service [Install] WantedBy=multi-user.target [Service] ExecStart=/usr/bin/python /home/ubuntu/wiki/Backend/manage.py python runserver 0.0.0.0:8000 Type=simple In the console error: ● wiki.service - service Loaded: loaded (/etc/systemd/system/wiki.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2017-09-22 11:10:44 UTC; 3min 36s ago Main PID: 1144 (code=exited, status=1/FAILURE) systemd[1]:Started service. python[1144]:Traceback (most recent call last): python[1144]:File "/home/ubuntu/wiki/Backend/manage.py", line 17, in <module> python[1144]: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? systemd[1]: wiki.service: Main process exited, code=exited, status=1/FAILURE systemd[1]: wiki.service: Unit entered failed state. systemd[1]: wiki.service: Failed with result 'exit-code'. -
Change the labels of choices dynamically - Django
I’m building a survey where each question has 5 choices which are displayed with radio buttons. The form is a model form, which shows all the questions on one page. The initial choices are set in the models. The label should be set according to question’s question_type. Eg. if the value for that is 1 then set the labels as a, b, c, d, e or if the value is 2 then set the labels as f, g, h, i, j. My questions: How do I change the label of a choice dynamically? The value of the choice stays the same but the label needs to be set according to a value of another field. The labels itself are pre-defined so I think that those should be stored in database? models.py class QuestionAnswer(models.Model): CHOICES = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ] questionnaire_key = models.ForeignKey(Questionnaire, null=False, blank=False) question = models.ForeignKey(Question, null=False, blank=False) answer_text = models.CharField(max_length=1, null=False, choices=CHOICES, default=None) class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire) question_type = models.CharField(max_length=1) forms.py class AnswerForm(forms.ModelForm): class Meta: model = QuestionAnswer exclude = ['question_type'] widgets = { 'answer_text': RadioSelect(attrs={'required': 'True'}), 'question': HiddenInput, 'questionnaire_key': HiddenInput, } -
Django models changing
I had a model class Subject(models.Model): subject_title = models.CharField(max_length=255) subject_lesson = models.ForeignKey(Lessons, on_delete=models.PROTECT) Before i had information in the database by this fields then i delete all information from database. Then i added some fields to the table. class Subject(models.Model): subject_title = models.CharField(max_length=255) subject_text = models.CharField(max_length=600) subject_image = models.ImageField(upload_to='uimages', blank=True, null=True, default='uimages/edu-logo-1.png') subject_lesson = models.ForeignKey(Lessons, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) After this django asking me: You are trying to add the field 'created_at' with 'auto_now_add=True' to subject without a default; the database needs something to populate existing rows . 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Select an option: What to enter? -
Dajngo template: group by key
I have list of objs: [{ key:test1 name: name1 }, { key:test1 name: name2 }, { key:test2 name: name3 }] Is it possible to combine values with similar keys without changing the structure? not to be displayed twice test1 in my case {% for item in list %} {{ item.key }} :{{item.name}} {% endfor %} now: test1 : name1 test1 : name2 test2 : name3 desired result: test1 : name1 _____ name2 test2 : name3 -
google oauth2 - Your credentials aren't allowed when using heroku
I am using a simple social login using google oauth2. I have deployed my app on heroku. I have successfull tested the google login on my local machine. However, when using heroku to login via google, It gives me this error, AuthForbidden at /oauth/complete/google-oauth2/ Your credentials aren't allowed I am using the same keys with the same name in heroku config vars. But still not sure why its not identifying login from heroku. -
Date time error in Python
I'm trying to learn the functions of Python but there is one thing I came across which I cannot figure out. calculated_time = '2014.03.08 11:43:12' >>> calculated_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") >>> print calculated_time 2017-09-22 15:59:34 Now when I run: cmpDate = datetime.strptime(calculated_time, '%Y.%m.%d %H:%M:%S') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime (data_string, format)) ValueError: time data '2017-09-22 16:35:12' does not match format'%Y.%m.%d %H:%M:%S' I can't understand why, if I directly pass this date then it is running but when I pass it after storing in a variable then I've got an error. -
Django, how to implement authorization in different ways
Tell me how to implement it so that some users (user) on login are authorized by phone, and the rest (owner, employee) by email, and all with different access rights? class UserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Please, enter the correct phone number') user = self.model(phone=phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user(phone=phone, password=password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], blank=True, max_length=15) phone = models.IntegerField(('contact number'), unique=True, db_index=True) # email = models.EmailField(_('email address'), unique=True) is_admin = models.BooleanField('superuser', default=False) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'phone' def get_full_name(self): return str(self.phone) def get_short_name(self): return str(self.phone) def __unicode__(self): return str(self.phone)