Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework Serialize model with foreign key
Simple question: I have next models: class Artist(models.Model): name = models.CharField(...) surname = models.CharField(...) age = models.IntegerField(...) clas Album(models.Model): artist = models.ForeignKey(Artist, ...) title = models.CharField(...) I wish to create an Album serializer that: Shows Artist information on GET Can link Artist using pk on POST I can make the POST using pk using the following serializer, but I don't know how to GET artist information in the same serializer: class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = '__all__' Thanks. -
Django ORM really slow iterating over QuerySet
I am working on a new project and had to build an outline of a few pages really quick. I imported a catalogue of 280k products that I want to search through. I opted for Whoosh and Haystack to provide search, as I am using them on a previous project. I added definitions for the indexing and kicked off that process. However, it seems that Django is really, really really slow to iterate over the QuerySet. Initially, I thought the indexing was taking more than 24 hours - which seemed ridiculous, so I tested a few other things. I can now confirm that it would take many hours to iterate over the QuerySet. Maybe there's something I'm not used to in Django 2.2? I previously used 1.11 but thought I use a newer version now. The model I'm trying to iterate over: class SupplierSkus(models.Model): sku = models.CharField(max_length=20) link = models.CharField(max_length=4096) price = models.FloatField() last_updated = models.DateTimeField("Date Updated", null=True, auto_now=True) status = models.ForeignKey(Status, on_delete=models.PROTECT, default=1) category = models.CharField(max_length=1024) family = models.CharField(max_length=20) family_desc = models.TextField(null=True) family_name = models.CharField(max_length=250) product_name = models.CharField(max_length=250) was_price = models.FloatField(null=True) vat_rate = models.FloatField(null=True) lead_from = models.IntegerField(null=True) lead_to = models.IntegerField(null=True) deliv_cost = models.FloatField(null=True) prod_desc = models.TextField(null=True) attributes = models.TextField(null=True) … -
how can i take the comma separated ip addresses in django form?
i have to create a form which can take mutiple IP addresses (comma separated) from user and run the desired command (input from user) and display it on the web page. i could not figure out how can i do it. Currently the code is able to take single IP address, run command and display the result on web page, successfully.! forms .py from django import forms class CmdForm(forms.Form): ip_address = forms.CharField(label='Enter IP address:') command = forms.CharField(label='Command to execute:') Views.py click here for views.py note:- the issue on the link has been resolved -
get instances of child models of abstract base model class
I have a BaseModel class and three children of it. I want to get a queryset, that combines all instances of all subclasses to my BaseNotification class. Is there a way to do that in one query? class BaseNotification(BaseModel): seen = models.BooleanField(default=False) text = models.TextField() class Meta: abstract = True class ApprovalNotification(BaseNotification): object = models.ForeignKey("Object", on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey("User", on_delete=models.CASCADE) class ComplaintNotification(BaseNotification): complaint = models.ForeignKey("Complaint", on_delete=models.CASCADE) class ProposalNotification(BaseNotification): proposal = models.ForeignKey("Proposal", on_delete=models.CASCADE) When I try python BaseNotification.objects.all() it obviously gives an error that BaseNotification has no attribute 'objects'. -
status code in custom exception in python [on hold]
I want to create custom exception with custom status code in my django project my code must be something like this class CustomJsonError(Exception): def __init__(self, encoder=DjangoJSONEncoder, message=None, **kwargs): final_json = { "success": False, "code": kwargs.get('status'), "message": message, "data": {} } content = json.dumps(final_json, cls=encoder) super(CustomJsonError, self).__init__(content, kwargs.get('status')) and I want using that like this raise CustomJsonError(message=validate.errors, status=status.HTTP_400_BAD_REQUEST) and I expect to getting result like this in response with STATUS CODE 400, not 500 { "success": true, "code": 400, "message": { "adviser": [ "required field" ], "job": [ "required field" ] }, "data": {} } -
How to connect daphne and nginx using linux socket
I am trying to deploy Django application that needs both http and websocket connection using daphne and nginx. The connection between nginx and daphne is established using Linux socket. when nginx receives a request, daphne would exit with error "address already in use" I made sure that both users who run nginx and daphne have read and write access to the sock file nginx conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events {worker_connections 1024;} http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; map $http_upgrade $connection_upgrade { default upgrade; '' close;} access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; upstream websocket{server unix:/run/daphne/bot.sock;} include /etc/nginx/conf.d/*.conf; server { listen 80; server_name 10.xx.xx.65; location /static/js { alias /var/botstatic/js;} location /static/img { alias /var/botstatic/img;} location /static/css { alias /var/botstatic/css;} location /static/webfonts {alias /var/botstatic/webfonts;} location / { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade;} } daphne service file [Unit] Description=daphne server script After=network.target [Service] User=sattam Group=sattam WorkingDirectory=/home/sattam/sattambot #Environment=DJANGO_SETTINGS_MODULE=myproject.settings ExecStartPre=/home/sattam/ExecStartPre.sh ExecStart=/usr/bin/daphne -u /run/daphne/bot.sock --access-log /var/log/daphne/log SattamBot.asgi:application Restart=always [Install] WantedBy=multi-user.target ExecStartPre #!/bin/bash if [ ! -f /run/daphne/bot.sock ]; then mkdir -p /run/daphne; touch /run/daphne/bot.sock; … -
Django annotate not giving values for a many to many field
I wrote a views function: def get_lists(request,user_email): """Get all the lists made by user""" try: user_instance = MyUser.objects.get(email=user_email) except MyUser.DoesNotExist: return HttpResponse(json.dumps({'message':'User not found'}),status=404) if request.method == 'GET': influencers_list = UserInfluencerGroupList.objects.filter(user=user_instance).annotate(total_reach=Sum('influencers__followers'),total_engagement=Sum('influencers__avg_picture_engagement')).order_by('id') influencers_list = serializers.serialize('json',influencers_list, fields =['id','influencers','list_name','total_reach'], indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True) return HttpResponse(influencers_list,content_type='application/json',status=200) else: return HttpResponse(json.dumps({'message':'No lists found'}), status=400) I want to return the total number of followers of all the influencers in each list and also their total_engagement. However after using the annotate field, the json object returned doesn't have the total number of followers or the total_engagement in each list. How should I use annotate to display the total number of followers of all the influencers in each list and also their total_engagement. My django model is as follows: class UserInfluencerGroupList(models.Model): list_name = models.CharField(max_length=255) influencers = models.ManyToManyField(Influencer, blank=True) user = models.ForeignKey(MyUser, on_delete = models.CASCADE) -
How to range the items in loop in query set?
I am working on QuerySet and I have connected this views.py with MongoDB and instead of writing every item, I just want to loop it with database. But whenever I run the code it gives me AttributeError saying that 'int' object has no attribute 'img'. How to give range to it? Because I made three variables target1, target2 and target3 just to divide the title and images in three columns in index.html. Without for loop range it is giving me all the results def index(request): query = request.GET.get('srh') if query: target1 = Destination.objects.filter(title__icontains=query) target1 = Destination.objects.all() for field in target1: field.img field.title *Without using database with it.* target2 = c = [Destination() for __ in range(2)] c.img = 'Data Entry.jpg' c.title = 'Data Entry' target3 = f = [Destination() for __ in range(2)] f.img = 'Website Testing.jpg' f.title = 'Website Testing' context = { 'target1': target1, 'target2': target2, 'target3': target3 } return render(request, 'index.html', context) -
How to inherit file from parent to fill form field?
I did some inheritance from filled data to one of my form. That fields are strings and files. When inheritance string fields worked fine, but the files was empty and not showed in my template. I though main problem on my views. I really stuck here. Any solution for my code? Or any ideas for what i have to do? views.py @login_required def forward(request, message_id, form_class=ComposeForm, template_name='mails/compose.html', success_url=None, recipient_filter=None, quote_helper=format_quote, subject_template=_(u"Re: %(subject)s"),): """ Prepares the ``form_class`` form for writing a reply to a given message (specified via ``message_id``). Uses the ``format_quote`` helper from ``messages.utils`` to pre-format the quote. To change the quote format assign a different ``quote_helper`` kwarg in your url-conf. """ parent = get_object_or_404(Message, id=message_id) if parent.sender != request.user and parent.recipient != request.user: raise Http404 if request.method == "POST": sender = request.user form = form_class(request.POST, request.FILES, recipient_filter=recipient_filter) if form.is_valid(): form.save(sender=request.user, parent_msg=parent) messages.info(request, _(u"Message successfully sent.")) if success_url is None: success_url = reverse('mails:messages_inbox') return HttpResponseRedirect(success_url) else: form = form_class(initial={ 'body': quote_helper(parent.sender, parent.body), 'subject': parent.subject, #HERE #this two are filefield, but strings other worked fine and showed on template 'file_surat': [parent.file_surat.url], 'lampiran': [parent.lampiran.url], 'nomor_surat': parent.nomor_surat, 'jenis_surat' : parent.jenis_surat, 'sifat_surat' : parent.sifat_surat, }) return render(request, template_name, { 'form': form, }) forms.py class … -
Django rest framework custom filter backend data duplication
I am trying to make my custom filter and ordering backend working with default search backend in django rest framework. The filtering and ordering working perfectly with each other, but when search is included in the query and i am trying to order query by object name, then data duplication is happening. I tried to print queries and queries size, but it seems ok when i logging it in the filters, but in a response i have different object counts(ex. 79 objects in filter query, 170 duplicated objects in the final result) Here is my filterset class class PhonesFilterSet(rest_filters.FilterSet): brands = InListFilter(field_name='brand__id') os_ids = InListFilter(field_name='versions__os') version_ids = InListFilter(field_name='versions') launched_year_gte = rest_filters.NumberFilter(field_name='phone_launched_date__year', lookup_expr='gte') ram_gte = rest_filters.NumberFilter(field_name='internal_memories__value', method='get_rams') ram_memory_unit = rest_filters.NumberFilter(field_name='internal_memories__units', method='get_ram_units') def get_rams(self, queryset, name, value): #here is the problem filter #that not works with ordering by name q=queryset.filter(Q(internal_memories__memory_type=1) & Q(internal_memories__value__gte=value)) print('filter_set', len(q)) print('filter_set_query', q.query) return q def get_ram_units(self, queryset, name, value): return queryset.filter(Q(internal_memories__memory_type=1) & Q(internal_memories__units=value)) class Meta: model = Phone fields = ['brands', 'os_ids', 'version_ids', 'status', 'ram_gte'] My ordering class: class CustomFilterBackend(filters.OrderingFilter): allowed_custom_filters = ['ram', 'camera', 'year'] def get_ordering(self, request, queryset, view): params = request.query_params.get(self.ordering_param) if params: fields = [param.strip() for param in params.split(',')] ordering = [f for f in … -
save multiplechoicefield in django
I try to save data from multiplechoiceField but only one item is save. when only one item we don't have a problem , when is multiple only the last item is save models.py class Reservation( models.Model): date_de_reservation = models.DateTimeField('Date de reservation', auto_now = True) type_enseignement = models.CharField('Type enseignement', max_length = 10, choices = (("cm", "CM"), ("td", "TD"), ("tp", "TP"), ("tc","TC")), ) date_du_jour_reserve = models.DateField("Date du jour reservé") plage_horaire = models.ForeignKey("Plage_Horaire", on_delete = models.CASCADE ) cours = models.ForeignKey(Cours, on_delete = models.CASCADE) enseignant = models.ForeignKey(Enseignant, on_delete = models.CASCADE) sallecours = models.ForeignKey(SalleCours, on_delete = models.CASCADE, blank = True, null = True) option = models.ForeignKey(Option,on_delete = models.CASCADE ) valide = models.BooleanField(blank = True, default = False) analyse = models.BooleanField(blank = True , default =False ) forms.py class Reservation_Form(forms.ModelForm): faculte=forms.ModelChoiceField(label="Faculte", queryset=Faculte.objects.all()) departement=forms.ModelChoiceField(label="Département", queryset=Departement.objects.all()) filiere=forms.ModelChoiceField(label="Filière", queryset=Filiere.objects.all()) niveau = forms.ModelChoiceField(label = 'Niveau', queryset = Niveau.objects.all() ) option=forms.ModelChoiceField(label="Option", queryset=Option.objects.all()) semestre=forms.ModelChoiceField(label='Semestre', queryset=Semestre.objects.all()) plage_horaire = forms.ModelMultipleChoiceField(label="", queryset = Plage_Horaire.objects.all()) class Meta: model=Reservation exclude=('date_de_reservation', 'sallecours', 'valide', 'enseignant','plage_horaire' ) widgets={ 'date_du_jour_reserve': DateInput(), } views.py def reservation(request): f=Reservation_Form() if request.method=='POST': f=Reservation_Form(request.POST) print (f.is_valid()) print(request.POST.getlist('plage_horaire') ) if f.is_valid() : res = f.save(commit=False) plage_horaire = f.cleaned_data['plage_horaire'] for i in plage_horaire: res.plage_horaire=i res.save() return redirect('configuration:ma_reservation') -
What are types of project recommended for django to do as a student?
Doing a Django project, what should be its structure and add-ons ? I've tried doing a game project on windows but all the codes were in a mess. Using the latest version of pycharm and django. -
Python test coverage for class' __str__
I have a very basic questing regarding Python coverage tests. In my Django models, all the __str__ representations are not covered in my tests. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name What would be the appropriate way to test these? This doesn't work: class TestCategory(TestCase): def test_category(self): category = Category.objects.create(name='Test Category') self.assertEqual(category.__str__(), 'Test Category') Thank you in advance for your help! -
if a task call with delay() when will execute exactly?
I'm new in celery and i want use it but i don't know when i call a task with delay() when exactly will execute? and after adding a new task what i must to do to this task work correctly? i use a present project and i extending it, but old task work correctly and my task doesn't . present app1/task.py: from __future__ import absolute_import, unicode_literals import logging logger = logging.getLogger('notification') @shared_task def send_message_to_users(users, client_type=None, **kwargs): . . #doing something here . . logger.info( 'notification_log', exc_info=False, ) ) and this is my code in app2/task.py: @shared_task def update_students_done_count(homework_id): homework_students = HomeworkStudent.objects.filter(homework_id=homework_id) students_done_count = 0 for homework_student in homework_students: if homework_student.student_homework_status: students_done_count += 1 homework = get_object_or_404(HomeWork, homework_id=homework_id) homework.students_done_count = students_done_count homework.save() logger.info( 'update_students_done_count_log : with id {id}'.format(id=task_id), exc_info=False, ) sample of how both task calling: send_message_to_users.delay(users = SomeUserList) update_students_done_count.delay(homework_id=SomeHomeWorkId) project/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hamclassy.settings') app = Celery('hamclassy') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. … -
Is using view decorators to handle user permissions bad practice?
I'm using django view decorators to check permissions in quite a complex way, and am starting to realise that this might be bad practice. Given a user's profile is in a certain state, say 'application pending' and so certain views should not be shown to this user, but should be shown to users who have 'application complete'. I'm currently using decorators to redirect pending users to the homepage, with a popup telling them their application is still pending. However, I read on google's python best practice, that decorators should be simple, and not rely on database connections, files etc. Does this mean that something such as checking the state of a borrowers application before showing a view is bad practice, and if it is, what is an alternative? -
Django rest framework - Serialize all fields of native object
I'm trying to serialize an object that's a mix of normal fields, model objects and querysets. I want to include all normal fields and then I'll create serializers for each model type. The problem is I can't automatically add all the non-model fields from my class: class ObjectSerializer(serializers.Serializer): class Meta: fields = '__all__' It Gives me an empty object. Is there any way to include all fields using non-model serializer? Or is there better way to achieve what I'm trying to do? -
How to Migrate django models to an MySQL read-only database?
I'm completely new to the Django development. In my work, My manager has given me a task of migrating the existing Models of my Django projects to a Read-only Database of MySQL server. additional details - 1) I have created a User in MySQL with read only privileges. Kindly help me in solving this problem. Thanks in advance. -
Django admin-site redirect if ValidationError during saving
my question is about saving new object in admin-site in Django. i dont want to raise error if user with email already exist, but i want to directly redirect to admin/edit page.. and edit that user i tried to rewrite clean method in form, but that was not right i think. i have a model like: class Users(models.Model): first_name = models.CharField(max_length=30) email = models.EmailField(unique=True) ... My form: class UserForm(forms.ModelForm): class Meta: model = Users admin: class UserAdmin(admin.ModelAdmin): form = UserForm Is there a way to do that? -
Django & timezone, beginning of the day : should I make_aware() in my function one or two times?
I have a simple function that returns the beginning of the day in Django (by default, today's day) : import datetime from django.utils.timezone import make_aware def DayBeginning(DateTime="Now"): if DateTime == "Now": DateTime = make_aware(datetime.datetime.today()) year = DateTime.year month = DateTime.month day = DateTime.day return make_aware(datetime(year, month, day, 0, 0, 0, 0)) I am afraid that if I call "make_aware" two times, I might offset the result. Did I do it right or not ? (my timezone is 'Europe/Paris') PS : Feel free to criticize my code, I am a newbie developer -
Why use media url for image uploads by user?
I am new to django, while learning about Handling Media Files in Django, I have read that we use media files configuration concept. Now while making a model I have designed my class with variable img=models.ImageField(upload_to='pics' ) When I have already mentioned that I have to upload images in pics folder, so why we are using media files configuration -
How to load multiple different page templates using a single view
I have a standard view and url in my Django project: views.py def app(request): template = loader.get_template('index.html') return HttpResponse(template.render(context, request)) urls.py: urlpatterns = [ path('', views.app, name='app'), ] I have c.50 additional page templates that I would like to serve from the /app/ directory. E.g. 'app/page1.html', 'app/page2.html', etc. Each of these templates is a basic .html file with no special functions, ie. they don't need individual context or other processing in views.py I know I can create 49 more entries in views.py and urls.py to define the reference to each of these templates, but is there a quicker way to load the them without going through this? For example, in pseudocode is there a wrapper I can put in the view so that '/app?page=page2.html' loads page2.html and avoids a new view.py and urls.py entry? -
pyodbc is not working with django 1.2.4 in Ubuntu machine
I am working on django project which is running with MySQL smoothly but I want to use MSSQL instead of MySQL.I have installed some packages such as pymssql,pyodbc and django-mssql etc. but failed. I got the following error: sqlalchemy.exc.DBAPIError: (Error) ('01000', u"[01000] [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found (0) (SQLDriverConnect)") None None Django==1.2.4 sqlalchemy==0.6.6 x -
Multiple Search Fields not working as expected
I have 3 search field(event_name, event_loc, event_date), while one of them filled it return all table data, while it has to be return one. views.py def searchEvent(request): if request.is_ajax(): q_event_name = request.POST.get('event_name') q_event_loc = request.POST.get('event_loc') q_event_date = request.POST.get('event_date') # return JsonResponse(dict(events=list(Event.objects.values('name', 'info')))) return JsonResponse( serializers.serialize('json', Event.objects.filter( Q(name__icontains=q_event_name) | Q(info__icontains=q_event_loc) | Q(start_event_dt__icontains=q_event_date))), safe=False) custom.js $.ajax({ url: '/searchevent/', data: { 'event_name': event_name, 'event_loc': event_loc, 'event_date': event_date }, dataType: 'json', type: 'POST', success: function (data) { data = JSON.parse(data); event_html = ''; for(var i in data){ event_name = data[0]['fields']['name']; event_html = event_html + '<div class="col-md-4">' + ' <h5 class="card-title text-center pt-3">' + event_name + '</h5>' + '</div>'; } document.getElementById("event-container").innerHTML = event_html; } }); for example, I have two event in my DB name=aaa, loc=bbb, date=2019-01-01 name=ccc, loc=ddd, date=2018-01-01 in the search bar when I searched for only name field with aaa, it returns all of the two event, which i expected to return me only first event. -
how to save selectMultiple in django
i Try to save a multiplechoicefield in my database. but when I save it's only one item who are saved models.py class Reservation( models.Model): date_de_reservation = models.DateTimeField('Date de reservation', auto_now = True) type_enseignement = models.CharField('Type enseignement', max_length = 10, choices = (("cm", "CM"), ("td", "TD"), ("tp", "TP"), ("tc","TC")), ) date_du_jour_reserve = models.DateField("Date du jour reservé") plage_horaire = models.ForeignKey("Plage_Horaire", on_delete = models.CASCADE ) cours = models.ForeignKey(Cours, on_delete = models.CASCADE) enseignant = models.ForeignKey(Enseignant, on_delete = models.CASCADE) sallecours = models.ForeignKey(SalleCours, on_delete = models.CASCADE, blank = True, null = True) option = models.ForeignKey(Option,on_delete = models.CASCADE ) valide = models.BooleanField(blank = True, default = False) analyse = models.BooleanField(blank = True , default =False ) class Plage_Horaire(models.Model): debut = models.TimeField("Heure de début", unique = True) fin = models.TimeField("Heure de fin", unique = True) def __str__(self): return "{0}--{1}".format(self.debut, self.fin) forms.py class Reservation_Form(forms.ModelForm): faculte=forms.ModelChoiceField(label="Faculte", queryset=Faculte.objects.all()) departement=forms.ModelChoiceField(label="Département", queryset=Departement.objects.all()) filiere=forms.ModelChoiceField(label="Filière", queryset=Filiere.objects.all()) niveau = forms.ModelChoiceField(label = 'Niveau', queryset = Niveau.objects.all() ) option=forms.ModelChoiceField(label="Option", queryset=Option.objects.all()) semestre=forms.ModelChoiceField(label='Semestre', queryset=Semestre.objects.all()) plage_horaire = forms.ModelMultipleChoiceField(label="", queryset = Plage_Horaire.objects.all()) views.py -
How to get the full file path of the browsed file in Django
I have a browse control in Django application, which is reading only the file of the browsed file.What I required is full file path of the browsed file. I have tried the different attributes for the browse control and its not working. To read the text of file control: request.POST["BrowseControlName"] It was returning the only file name not the absolute file path