Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgres & Django - DataError: time zone not recognized
We are getting the following error from some of our users: DataError: time zone "Asia/Qostanay" not recognized We've found out that the problem was coming from the following SQL query: SELECT * FROM "app_foobar" WHERE ( EXTRACT('hour' FROM "app_foobar"."date" AT TIME ZONE 'Asia/Qostanay') = 0 ); -
query prints objects instead of some names in django
Is there a simple way to remove query set objects in my template just to print product name without the objects what it prints class SellerAccountMixin(object): products = [] def get_products(self): account = self.get_account() products = Product.objects.filter(seller=account) self.products = products return products class SellerDashboard(SellerAccountMixin,FormMixin, View): def get(self, request, *args, **kwargs): context["products"] = self.get_products() return render(request, "sellers/dashboard.html", context) template {% if products %} <div class='pull-left col-sidebar '> {{ products }} </div> -
Authenticate VueJS app to Django DRF back end using sessions
Good afternoon, I am writing an app structured with two docker containers. Docker1 is the front end VueJS app, Docker2 is the backend Django DRF API. I would like to manage access using Sessions (NOT JWT's). I am having trouble finding resources to help me get started on this approach. Does anyone have any good resources on how to interact with authenticating and managing Django sessions over DRF? Most of the examples use a DJango template form to do initial authentication which is not an option in this case. Thanks for your help. BCBB -
Regular expression not matching the given pattern
regular expression not matching. The current path, attendance/B-2019-07-05, didn't match any of these. ^attendance/(?P<date>\[AB]-\d{4}-\d{2}-\d{2})/$ [name='update_data'] -
Django model with dynamic fields based on foreign key
I am trying to implement a model where only a subset of the fields should be presented in forms, based on a foreign key in the model. The total number of fields is relatively low (~20), but may change frequently with different values of the foreign key. I would like to use something like single table inheritance, but with a single model (no inheritance). I looked at existing packages eav, dynamic models... but they did not seem to fit my needs. I part of the requirement is that I would like to query the models by sql without too many joins. Here is a use case representing applications to grants based on a request for application (rfa). The rfa is entered in the admin by staff and the applications are made by end users. application class rfa (request for application): foreign key field_1 ... field_20 rfa class: app_fields (coma separated list of field names) In the forms, only the fields in app_fields should be visible for a particular rfa. I have the rfa part covered with django-separatedvaluesfield and I was wondering how to implement the application pages so that they work with generic views in the frontend and admin, and … -
Django 2.0 + Sublime Text 3 + Windows, how can I start
I'm beginner in the python (sure not so novice, but it's not important) So, I'm gonna create web-app with using Django 2.0 in Sublime Text 3. In the internet not so many tutorials, special for Windows. To all other, they are all using PyCharm and hit "auto create project with venv". Due to it, I can't start! I want to know if Sublime Text 3 has a plugin for work with Django more easy, special if that plugin can create auto project with venv. Sorry for question not about code problem, but that problem so bad for me now! -
UWSGI default log not showing REMOTE_USER
In my UWSGI default log REMOTE_USER is empty. Could anybody please help me how to send this from Django Application. Or is there any way to have both default uwsgi log and custom log -
Static file does not work: Not Found: /{static 'logo.png'}
In my Django app I created a navbar. I want to diplay a small png image on the top-left of it. So I used the static file. In my mysite folder I created a folder called static_files. In this folder, I added my png image with the name logo.png The I changed my settings.py of mysiteas follows: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static_files/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' My base.html contains: {% load staticfiles %} <nav class="navbar navbar-light bg-light"> <a href=""> <img src="{static 'logo.png'}" alt="" class="d-inline-block alight-top"/> </a> <a class="" href="fdklsmflds">Login</a> <a class="" href="fdklsmflds">Sign up</a> </nav> I finally run python3.6 manage.py collectstatic BUT I GET THE ERROR: [04/Jul/2019 18:13:53] "GET / HTTP/1.1" 200 1379 Not Found: /{static 'logo.png'} [04/Jul/2019 18:13:54] "GET /%7Bstatic%20'logo.png'%7D HTTP/1.1" 404 2139 -
Listview display immediately after loading page in Django
I'm trying to write a small online store on django and I have a small problem: I want to display the listveiw immediately after the page loads, but django does not allow it I tried to make a display by pressing a button, and it worked, but I would like to make a display as soon as the page loads urlpatterns = [ path('', views.index, name = 'INDEX'), path ('prod/', ListView.as_view(queryset=Product.objects.all(), template_name="mainPage/homePage.html")) ] Can you help me? -
Django REST framework. APITestCase. How to fix ' bad_value, referenced_table_name, referenced_column_name'
I have the following models: class Student(models.Model): first_name = models.CharField(verbose_name='student first name', max_length=64) last_name = models.CharField(verbose_name='student last name', max_length=64) email = models.EmailField() class Meta: db_table = 'student' def __str__(self): return self.first_name + ' ' + self.last_name class Course(models.Model): name = models.CharField(max_length=255) description = models.TextField() start_date = models.DateField(null=True, blank=True, default=None) end_date = models.DateField(null=True, blank=True, default=None) class Meta: db_table = 'course' def __str__(self): return self.name class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='courses', on_delete=models.CASCADE) student = models.ForeignKey(Student, related_name='student_name', on_delete=models.CASCADE) completed = models.BooleanField(null=False, default=False) class Meta: db_table = 'course_participant' def __str__(self): return self.course, self.student Urls: app_name = 'student' urlpatterns = [ path( 'student', StudentAPIView.as_view(), name='list' ), path( 'student/detail/<int:pk>/', StudentAPIDetailView.as_view(), name='detail' ), path( 'student/assign_student_to_course', StudentAPIAssignToCourse.as_view(), name='assign_student_to_course' ), path( 'student/assigned_to_course', StudentAPIAssignedToTheCourseView.as_view(), name='assigned_to_course_list' ), path( 'student/assigned_to_course/detail/<int:pk>/', StudentAPIUnassignedFromTheCourseView.as_view(), name='unassigned_to_course_list' ), path( 'student/report/<int:pk>/', StudentAPIPerformanceReport.as_view(), name='student_performance' ) ] Views: import csv from django.http import HttpResponse from rest_framework import mixins, generics from course.models import ( CourseParticipant ) from student.models import ( Student ) from student.serializers import ( StudentSerializer, AssignStudentToCourseSerializer, StudentAssignedToTheCourseSerializer ) class StudentAPIView( mixins.CreateModelMixin, generics.ListAPIView ): serializer_class = StudentSerializer def get_queryset(self): queryset = Student.objects.all() return queryset def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class StudentAPIDetailView( mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.RetrieveAPIView, ): serializer_class = StudentSerializer def get_queryset(self): query_set = Student.objects.all() return query_set def … -
cannot import name 'RemovedInDjango110Warning'
I cloned a django project from github and then I created a virtual env and installed requirements from requirements.txt file and when I load server I get following error: -
Pass object id from nested serializer to parent serializer in Django Rest Framework
I've created two serializers - ASerializer and BSerializer. A model has b many-to-many field with relation to B. My goal is to be able to update multiple nested B objects while updating A object. My serializers: class ASerializer(WritableNestedModelSerializer): b = BSerializer(many=True) class Meta: model = A fields = '__all__' read_only_fields = ['id'] def update(self, instance, validated_data): info = model_meta.get_field_info(instance) bs_data = validated_data.pop('b', None) for attr, value in validated_data.items(): if attr in info.relations and info.relations[attr].to_many: field = getattr(instance, attr) field.set(value) else: setattr(instance, attr, value) if bs_data: for b_data in bs_data: b_serializer = BSerializer(data=b_data) if b_serializer.is_valid(): b = B.objects.update(**b_data) instance.b.add(b) else: raise exceptions.ValidationError(todo_serializer.errors) return instance class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = '__all__' read_only_fields = ['id'] And models: class A(models.Model): name = models.CharField('Name', max_length=250) content = models.TextField('Content') b = models.ManyToManyField('bs.B', blank=True, null=True, verbose_name='todo', related_name='as') class B(models.Model): name = models.CharField('Name', max_length=250) description = models.TextField('Description') The problem I encountered is, that during update (PATCH), printing bs_data, all I get is [OrderedDict([('name', 'test'), ('description', 'none')]), OrderedDict([('name', 'another'), ('description', 'one')])] And I cannot update all nested B objects - every nested object gets the content of last provided one (so in this example above, every nested object would be filled with 'another' name and … -
How to copy m2m fields when copying one model to another
I am able to copy all of the properties of a model except the m2m fields using a post_save signal. The QuerySet returns empty when using the same steps that work in the shell so I am unable to add the fields to the new object/model. signals.py @receiver(post_save, sender=RecurringEventItem) def create_calendar_event(sender, instance, created, **kwargs): if created: min_date = datetime.now() - timedelta(days=365) max_date = datetime.now() + timedelta(days=365) recurring_event = RecurringEventItem.objects.get(pk=instance.id) print(recurring_event.attendee) print(recurring_event.attendee.all()) if recurring_event.attendee is not None: attendees = recurring_event.attendee.all() if instance.recurrences is not None: calendar_item_list = [] recurrence_dates = list(instance.recurrences.between(min_date, max_date)) for date in recurrence_dates: new_calendar_item = CalendarItem(name=instance.name, start_date=instance.start_date, completion_date=instance.completion_date, description=instance.description, end_date=datetime.date(date)) if attendees: new_calendar_item.calendar_attendees.add(attendees) calendar_item_list.append(new_calendar_item) CalendarItem.objects.bulk_create(calendar_item_list) Works in the shell: test = RecurringEventItem.objects.get(pk='42f59a0ba1ac40858256a607fd8c57a3') test_2 = test.delegated_to.all() test_2 <QuerySet [<Contact: Test Person>]> Result of the QuerySet when the app is running. <QuerySet []> -
How to iterate a value based on an object value in django template
I have a model which is 'Saloon' class. I want to iterate saloon name based on the value of capacity. I tried many answers (forloop.counter, Custom template tags and filters) but could not manage to do it. I only want to repeat the saloon's building and name based on the capacity value models.py class Saloon(models.Model): building= models.CharField(max_length=55) name= models.CharField(max_length=125) capacity= models.IntegerField() views.py from django.shortcuts import render from .models import Saloon def salonogrenci(request): saloons = Saloon.objects.all() return render(request, 'salonogrenci/home.html', {'saloons':saloons }) home.html <table class="table table-hover"> <tbody> {% for saloon in saloons %} {% for i in range(saloon.kapasite) %} <tr> <th scope="row">{{ saloon.building }}</th> <td>{{ saloon.name }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> -
What is usecase of Django Management script?
I heard of about Django Custom Management script in lots of community and i am not getting why should i write custom management script as django manage.py a lot of useful command? I am very new in django... Can anyone tell me some usecase of custom management script? Thanks -
Realtions and render multiple inlineformset_factory in the same page
I'm writing a Django application and I'm stuck at the point where I can't figure out how to structure the model and use the inlineformset_factory to get on a single page the ability to dynamically add for each customer a variable set of activities for each week day (0-6). For Example: Monday Tennis Yoga Tuesday Tennis Running Judo [ ... ] Sunday Walking Swimming Suppose that I have this model: DOW = ( (1, "Lunedì"), (2, "Martedì"), (3, "Mercoledì"), (4, "Giovedì"), (5, "Venerdì"), (6, "Sabato"), (7, "Domenica"), ) class Customer(models.Model): firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) def __str__(self): return self.firstname + " " + self.lastname class Week(models.Model): cliente = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True, blank=True, default=None ) week_number = models.IntegerField() week_day = models.IntegerField( choices=DOW, null=False ) def __str__(self): return "Week number: " + self.week_number class Activity(models.Model): name = models.CharField(max_length=20) week_day = models.ForeignKey(?) def __str__(self): return "Activity: " + self.name What is the relation to put in place between Activity <-> Week to obtain the ability to have into a single page multiple forms that belong to a specific 'week_number' for each 'week_day' ? I have to create a specific "Activity" model one for each day and then use them into inlineformset_factory(Week,Activity_Monday), … -
changing function to class python
I am using django version 1.8.6. I have created student edit profile function so I want to change that function to class here is my views.py def student_edit_profile(request): if request.method == 'POST': info_form = StudentEditProfileInfoForm(request.POST, request.FILES, instance=request.user) edit_form = StudentEditProfielForm(request.POST, instance=request.user) if edit_form.is_valid() or info_form.is_valid(): edit_form.save() info_form.save() return redirect('student_course_list') else: info_form = StudentEditProfileInfoForm(instance=request.user) edit_form = StudentEditProfielForm(instance=request.user) return render(request, 'students/student/edit_profile.html', {'edit_form':edit_form, 'info_form': info_form}) else: info_form = StudentEditProfileInfoForm(instance=request.user) edit_form = StudentEditProfielForm(instance=request.user) return render(request, 'students/student/edit_profile.html', {'edit_form':edit_form, 'info_form': info_form}) and also here is my forms.py class StudentEditProfielForm(UserCreationForm): class Meta: model = User fields = { 'first_name', 'last_name', 'username', 'email', 'password', } class StudentEditProfileInfoForm(forms.ModelForm): class Meta: model = StudentProfile fields = { 'date_of_birth', 'bio', 'gender', 'country', 'address', 'city', 'image' } Anyone can I need that student_edit_profile() function change to class, and also if I visit the link without login it will show error showing like this 'AnonymousUser' object has no attribute '_meta' Anyone I need help. -
How to get the last item Message from every user in Django?
I am making a Django Chat app and I try to create an all message window, where I need all of the last messages that I got from the users I already tried distinct() and with .values() but nothing worked(I know I miss spelled recenpen_id, that is not the problem) class MessageView(APIView): def get(self, request): message = Message.objects.order_by().filter(recepien_id=request.user.id) serializer = MessagesSerializer(message, many=True) return Response({"message_info":serializer.data}) -
When are ContentTypes and Permissions created?
I created a new model and wanted to give permissions to a certain group group in the migration file after the migrations.CreateModel cando_ct = ContentType.objects.get(app_label='main', model='cando') cc_group = Group.objects.get(name='content creators') add_p = Permission.objects.get(content_type=cando_ct, codename='add_cando') cc_group.permissions.add(change_p, delete_p, view_p) but when i run migrate, i get an error saying: ContentType matching query does not exist. but if i run this script in a separately (in a different python manage.py migrate instance), i don't get the error. So my question is when are the contenttypes and permissions created? -
range() issue in Django unittest
I have a Django testcase, and I'm creating some objects in setUp: OBJ_COUNT = 4 class ObjTest(TestCase): def setUp(self): for i in range(OBJ_COUNT): print(i) Obj.objects.create() Running this test results in 5, not 4 objects! And the print() gets this output: 0 1 2 3 5 wtf? But the same code works as expected outside of setUp(). Am I missing something? Maybe this is somehow related to recent upgrade to Django 2.2.3 (from 2.1.7)? -
Is there a new device login alert system in django?
I am looking for a package or a way to implement a system into Django project that would send alerts to the users whenever a new login to their account is detected from a new device or basically different from the device they signed up from in the first place. Please suggest something that would work in production. I expect it to work in Django2 and python3. -
How to save queryset by user in new models from our created models?
I have some models and every models have many queryset. models: class Match(models.Model): match_name = models.CharField(max_length=20) first_team = models.ForeignKey('FirstTeam', on_delete=models.SET_NULL, null=True) second_team = models.ForeignKey('SecondTeam', on_delete=models.SET_NULL, null=True) tournament_name = models.ForeignKey('TournamentName', on_delete=models.SET_NULL, null=True) match_created = models.DateTimeField(auto_now_add=True) match_stated = models.DateTimeField(default=timezone.now()) mega_league = models.ManyToManyField('MegaLeague', blank=True) I have also many models class like this. In admin section I created data for every models and then I show all queryset on different templates correctly. Now I want to make same duplicate models class(same fields also) where data is stored by user. When user select our own queryset in templates then that queryset will store in new duplicate models(same class and same fields) and every queryset will different different for different users. That means every user can store their queryset by selecting our own queryset from templates. How can i do this?? -
How to save a string variable from views in Django
I'm trying to use pytesseract for my Django application. In views.py I called pytesseract and stored all the text it found in the 'text_content' variable. I want to save this variable as the 'text' parameter for my model, but I'm not sure how to go about this. I tried to use .save(), but got this error: 'str' object has no attribute 'save' <!-- language: lang-py --> #views.py def image_view(request): if request.method == 'POST': form = partForm(request.POST, request.FILES) if form.is_valid(): form.save() data = request.POST.copy() image_file = request.FILES.get('image') text_content= pytesseract.image_to_string(Image.open(image_file)) text_content.save() return redirect('success') else: form = partForm() return render(request, 'add_image.html', {'form' : form}) # models class Component(models.Model): snum = models.CharField(max_length=20, default = '') image = models.ImageField(blank=True) text = models.TextField(default = 'no text found') #forms.py class partForm(forms.ModelForm): snum = forms.CharField(max_length=128, help_text="please enter the number.") class Meta: model = Component fields = ['snum', 'image'] -
How to check the lines that executed while processing a http request in a Django Project
I am developing a Django application, it is successfully working right now. I want to track how many lines of code is being executed while serving an HTTP request. I've gone through the coverage.py but it has to be included in the view, due to this I am not able to get the code coverage of the entire scenario i.e. from import statements to return Response. Below is the code that I've Implemented. This is models file from django.db import models class Puppy(models.Model): """ Puppy Model Defines the attributes of a puppy """ name = models.CharField(max_length=255) age = models.IntegerField() breed = models.CharField(max_length=255) color = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_breed(self): return self.name + ' belongs to ' + self.breed + ' breed.' def __repr__(self): return self.name + ' is added.' class PuppyStore(models.Model): """ Puppy store, this supply all puppy needs """ puppy = models.ForeignKey(Puppy,on_delete=models.CASCADE) food = models.CharField(max_length=25) Views file from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Puppy from .serializers import PuppySerializer from coverage import Coverage @api_view(['GET']) def list_puppies(request): try: cov = Coverage() cov.erase() cov.start() qset = Puppy.objects.all() resp = PuppySerializer(qset, many=True) cov.stop() cov.save() cov.html_report() return Response(resp.data, status=status.HTTP_200_OK) except Exception … -
How to pass login view to header django
I have some problems about passing the login view to header, I want users to login from everypage via header but I couldn't do it yet. I tried to pass the view using render(request, "header.html") but it didn't work