Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save everything for new object except ManyToMany field in Django
I want to save object with ManyToMany relation. When I submit the form, all things save except field that have ManyToMany relation. These are my files: #Forms.py class ExamForm(ModelForm): class Meta: model = Exam fields = '__all__' #Models.py class Exam(models.Model): questions = models.ManyToManyField(Question) title = models.CharField(max_length=250) class Question(models.Model): title = models.CharField(max_length=250) answer = models.TextField(null=True, blank=True) #Views.py def add_exam(request): if request.method == "POST": form = ExamForm(request.POST) if form.is_valid(): new_exam = form.save(commit=False) new_exam.save() return redirect('view_exam') else: form = ExamForm() template = 'add_exam.html' context = {'form': form} return render(request, template, context) What is wrong with these codes? -
Django DateTime serializing
im getting a strange serialized representation of my DateTimeField, at the ending of the representation I get a "-05:00" on the JSON. Inside my model the field is defined as: ultima_actualizacion = models.DateTimeField(auto_now=True) And in the serializer I got it inside the Meta Class: class Meta: fields = ( ... 'ultima_actualizacion', ... ) But when I make a request in the response JSON I get something like: { ... "ultima_actualizacion": "2019-08-07T15:34:22.692530-05:00" } Which seems odd because I haven't changed the format and still get that "-05:00" in every ultima_actualizacion I have looked and tried changing the format and input formats as specified in: Django Rest Framework Fields and in this other answer but still get the "-05:00" -
Monitoring django connections
I'm trying to investigate how well my application is utilising pooled django connections to a mysql database. From mysql, I am able to see the connections and their state, but it appears that the vast majority (often over 99%) of the connections are generally in an idle state. I have been able to monitor the queries made from the django application by following the advice in this post: https://stackoverflow.com/a/24876751/8196202. I am now looking to monitor the connections in a similar way -- i.e. detect when a new connection is created, how long the connection is kept open, and how much of the connection's life is spent in an idle vs active state. I'm wondering if anyone has some tips or suggestions on how to go about gathering this information? My goal is to use the information gathered to try and decide on reasonable values to use for CONN_MAX_AGE, etc. -
Django, When to use multiple template loaders
This is a standard practice question So I have a Django app that contains the standard loader that loads all my web templates from the assets/template folder along with most expected context processors. My app also sends out e-mails in txt and html formats for which I use a different loader. The loaders are set up as follows: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'assets/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, { 'NAME': 'EmailTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'assets/mails')], 'APP_DIRS': True, }, ] When rendering the mails I use get_template(..., using='EmailTemplates') and it works fine. However, my partner argues that the differences between the loaders are minimal and that it's better to make it just one loader and placeassets/mailstoassets/templates/mails`. As Django was build to support multiple template loaders (as evident by the parameters using in the many key template methods, I was wondering: When is it useful to implement multiple template loaders on a site and when should it be avoided? -
Django how to extend generic View class
I noticed that I am setting site-wide context variables and request variables for many views on my site. Naturally, this situation calls for inheritance. If all of my view class-based views are inheriting from SiteView instead of the generic View, I can factor out all the commonalities into the SiteView child class. I can then inherit from SiteView on all my views. But, I cannot get this to work. Here is my code: from django.contrib.auth.decorators import login_required from django.views.generic import View from django.utils.decorators import method_decorator class SiteView(View): ''' Extends the generic django-supplied View class ''' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(SiteView, self).dispatch(*args, **kwargs) def get(self, *args, **kwargs): ''' Adds the variables required in the get request ''' context = super(SiteView, self).get(*args, **kwargs) context['common_var'] = 'some common value' context['user'] = request.user return self.render_to_response(context) This throws the following TypeError: dispatch() missing 1 required positional argument: 'request' Any help would be appreciated -
Defining views and urls in Django. Why aren't parenthesis used to call the function?
I have been going through "Python Crash Course", and I'm working on the "Django Web Application project (Learning Log)" stage. There is something that contradicts what I have already learned... """views.py file""" from django.shortcuts import render def index(request): """The home page for Learning Log.""" return render(request, "learning_logs/index.html") """urls.py file""" from django.urls import path from . import views app_name = "learning_logs" urlpatterns = [ # Home page path("", views.index, name="index") ] In the code above, in "urls.py" file, views.index is called but without parentheses. Why is that? Also, the index function has "(request)" parameter, but the argument is never provided. Am I missing something? Note that this code works fine. -
How can a Ajax/jQuery script show three dependent form dropdown box entries all within one form url?
I am developing a simple form prototype that contains 4 entries in PythonAnywhere (Python 3.7 + Django): PinID (Independent, simple manual number entry) Region (Independent Dropdown Box) Name (Region-Dependent Dropdown Box) Source (Name-Dependent Dropdown Box) What shows up in the Name box is dependent on the Region box, and what shows up in the Source box is dependent on the Name box. So ultimately, the Source Box is dependent on the Region box (If A, then B. If B, then C. So C is dependent on A). To note, if the Region or Name box is blank, their respective dependents are blank. As my current code is written (which is likely wrong), I can only get my Name box to autopopulate correctly. The Source box remains blank, but it does indeed autopopulate correctly after I refresh the page. However, I intend to keep the form all in one url. I refer to two other .html files to "insert" themselves into the form's .html file without refreshing the page. In the jQuery script, I put the identical segment of code for the second dependent dropdown box under the success function of the first dependent dropdown box, which might be my issue. … -
Images as static files in Django (development)
I'm having trouble displaying an image in my home.html template in development. In settings.py, I have this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # for production STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static-assets'), # for development ) The relevant part of the file structure is this: pred_market_pg [base directory] staticfiles [empty] static-assets mp_logo_dark.jpg templates home.html [further templates] markets [all the usual app files] static css markets.css users [all the usual app files, no static folder] In home.html, I then have {% load static %} on top, and further down <img src="{% static 'mp_logo_dark.jpg' %}"/>. I have DEBUG = True and have included django.core.staticfiles in my INSTALLED_APPS in settings.py. Where am I going wrong? -
Django query_params array type instead of string
I have an ApiView that supports get requests: class BookApiView(APIView): def get(self, request): search_criteria = request.query_params When I send a GET request to this end point: http://0.0.0.0:3000/api/book/?q=the+lord+of+the+rings The request.query_params is: <QueryDict: {'q': ['the lord of the rings'], 'page': ['2']}> Instead of being: <QueryDict: {'q': 'the lord of the rings', 'page': '2'}> How can I stop the value from becoming a list or my only option is to parse the value and convert it back to a string? -
Django in production not showing custom 404 page
My django site is in production on digital ocean with ubuntu 18.04 and Django 2.2. It is working with nginx and gunicorn following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 I cannot get it to display my custom 404 page. I have tried setting up the 404 by adding handler404 ='forum.views.error_404' in urls. I added a view function def error_404(request): data = {} return render(request,'forum/error_404.html', data) The rest of my nginx setup is as shown in the tutorial. I think i have to change something in my config for nginx for this to work, something about proxies, but i have no idea how to do it i am completely lost with those config files and which lines to add where. -
How can I add a nullable or boolean field to ManyToManyField Django?
I am trying to add a boolean field which is 'is_featured' column in a pivot table of Portfolio. I want to add images gallery with multiple images but among them there will be a featured image or first one will be featured if there is more than one images is featured. I have found that by 'through' is possible but that do not solve my problem. http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships from django.db import models from tinymce.models import HTMLField from category.models import Category from imageGallery.models import ImageGallery from tag.models import Tag class Portfolio(models.Model): title = models.CharField(max_length=191) description = HTMLField() category = models.ForeignKey(Category, on_delete=models.CASCADE) tag = models.ManyToManyField(Tag, blank=True) # > Here I want to add another column 'is_feature' !!!! gallery = models.ManyToManyField(ImageGallery, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Generally tag will create a pivot table portfolio_portfolio_imageGallery where i want add another column 'is_feature' that could be nullable, or a boolean id portfolio_id imageGallery_id is_feature <- is extra column I want to add. Any help will be greatly appreciated. -
How to store time intervals created dynamically with Javascript in Django
I am working on a Django project with exams, where a unit that makes exams should define prices for the exams made on each interval of the day. So, we need to store intervals of time with start, end and the correspondent price, but the problem is that there is not a fixed number of intervals, then it should be dynamic. I managed to create dynamic fields with Javascript (code bellow), but how can I store this data in a smart way with Django? I will need this later to calculate exam prices. I thought of something like that, but I don't know how to make queries that way: start_time = ArrayField( models.TimeField(null=True, blank=True), null=True, blank=True ) end_time = ArrayField( models.TimeField(null=True, blank=True), null=True, blank=True ) //$('#start-time').mask('00:00'); var max_fields = 10; var wrapper = $(".container1"); var add_button = $(".add_form_field"); var x = 1; $(add_button).click(function(e){ e.preventDefault(); if(x < max_fields){ x++; $(wrapper).append('<input class="two wide field" type="text" name="start[]" placeholder="00:00"/>'); //add input box $(wrapper).append('<input class="two wide field" type="text" name="end[]" placeholder="00:00" />'); $(wrapper).append('<input class="two wide field" type="text" name="price[]" placeholder="0,00"/>'); $(wrapper).append('<br>'); //$(wrapper).append('<a href="#" class="delete">Delete</a>'); } else { alert('Limite de 10 intervalos'); } }); $(wrapper).on("click",".delete", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--; }) });  -
Django model does not update in celery task
I am trying to make a celery task that updates django model and sends email. The emails are sent properly but the model is not saved to the database. Any ideas why does it happen? Here is my sample task: @app.task() def send_invitation(company_id): users = User.objects.filter(company_id=company_id, user_email__invitation_sent=False) for user in users: user.user_email.invitation_sent = True user.save() send_email(user) I have tried several saving options for example user.user_email.save() but when the task finishes, mails are sent but invitation_sent stays False and I can't figure out why this happens -
DRF using another model field in a serializer
I'm moving my first steps with DRf and I'm having problems with this issue. Suppose that I have a model made like this class Snps(models.Model): snpid = models.AutoField(db_column='SNPID', primary_key=True) rsid = models.CharField(unique=True, max_length=20) chrom = models.CharField(max_length=5) pos = models.PositiveIntegerField() class Meta: managed = False db_table = 'SNPs' def __str__(self): return str(self.snpid) class SnpsFunctionalelement(models.Model): snpid = models.ForeignKey(Snps, models.DO_NOTHING, db_column='SNPID', primary_key=True) elementid = models.ForeignKey(Functionalelement, models.DO_NOTHING, db_column='ElementID') celllineid = models.ForeignKey(Celllines, models.DO_NOTHING, db_column='CELLLINEID') filetype = models.CharField(db_column='fileType', max_length=10) class Meta: managed = False db_table = 'SNPs_FunctionalElement' unique_together = (('snpid', 'elementid', 'celllineid', 'filetype'),) def __str__(self): return str(str(self.snpid) + str(self.elementid) + str(self.celllineid) + str(self.filetype)) Now in the serializers.py I want to get the field rsid from Snps and serializing it with the other fields replacing snpid of SnpsFunctionalElement and looking around i found this solution class SnpsFunctionalelementSerializer(serializers.ModelSerializer): rsid = serializers.SerializerMethodField() def get_rsid(self, obj): return obj.Snps.rsid .... but it doesn't work saying that 'SnpsFunctionalelement' object has no attribute 'Snps' and I can't understand what to do -
Is it possible to prefix django models, to run multiple apps on same database
I would like to run multiple different django apps which share the same database. While model specific tables are prefixed with the app, such as appname_tablename, the issue is the Django default tables below are also created. Therefore if I have multiple apps running on the same database these tables are not differentiated. For example, these tables are created automatically. But I would prefer if they were also created with the app prefix, E.G. appname_AUTH_GROUP. Is that possible? • AUTH_GROUP • AUTH_GROUP_PERMISSIONS • AUTH_PERMISSION • AUTH_USER • AUTH_USER_GROUPS • AUTH_USER_USER_PERMISSIONS • CONFIG_FACT • DJANGO_ADMIN_LOG • DJANGO_CONTENT_TYPE • DJANGO_MIGRATIONS • DJANGO_SESSION -
Using IS NULL in PyMongo
I am trying to do an 'd': None in my pymongo query. But when I do None. I am not getting any results. My SQL: SELECT date, a, vt, b, c, d ,SUM(theSum) AS theSum FROM table where date between '2019-07-08' and '2019-08-08' AND a in ( 'abc', 'xyz') AND c IN ('qwe') AND b IS NOT NULL AND (d IN ('yo') OR d IS NULL) group by 1,2,3,4,5,6 order by theSum DESC LIMIT 25 PyMongo: {'$match': { '$and': [{ 'date': { '$gte': sd, '$lte': ed }, 'a': { '$in': a }, 'b': {'$ne': None}, 'c': { '$in': c }, }, { '$or': [{ 'd': {'$in': d} }, {'d': None }] }] } } { '$group': { '_id': { 'a': '$a', 'vt': '$vt', 'b': '$b', 'c': '$c', 'd': '$d' }, 'theSum':{ '$sum': '$theSum' } } }, { '$project': { '_id': 0, 'a':'$_id.a', 'vt': '$_id.vt', 'b': '$_id.b', 'c': '$_id.c', 'd': '$_id.d', 'theSum': '$theSum' } }, { '$sort': { 'theSum': -1 } }, { '$limit': 25 } ]) I get 43 records when I query in SQL but 0 when I query the pymongo code. What am I doing wrong in pymongo. -
How to use django's ORM as a stand alone package in AWS lambda?
For starters, I have tried the following posts & they did not help. Using Django ORM Inside AWL Lambda Using Only The Db Part Of Django Django Stand Alone Docs Following the django docs and using pieces of the above links I created the following standalone script to use django's ORM. import django from django.conf import settings def configure(): settings.configure(DEBUG=False, DATABASES={ # TODO: Change this to environment variables 'default': { "ENGINE": "django.db.backends.mysql", "NAME": "db_name", "HOST": "db_host", "USER": "admin", "PASSWORD": "db_pass" } }, INSTALLED_APPS=['my_models'] ) django.setup() In my handler.py file with my registerUser lambda functions from .django_orm.main import configure configure() from .django_orm.my_models import AppUser def registerUser(event, context): #Application Logic newUser = AppUser() newUser.save() return True When I run this I get the following error ... File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'my_models' My directory structure is the following: ./myServerlessProject ./djangoORM ./main.py ./manage.py ./my_models ./__init__.py ./models.py ./handler.py ./serverless.yml What am I doing wrong and how do I get the django ORM to be stand-alone? -
Error : type object 'Inventory' has no attribute 'objects'
I created a model and used random generator for it. Thus, I had to use UserManager for that model. Wen I am using this model in views, I am getting the above error. I have done this multiple times and never got an error. I don't know what is wrong. Please help. Thanks in advance! models def unique_rand(): while True: code = Inventory.objects.make_random_password(length=6, allowed_chars="1234567890") if not Inventory.objects.filter(code=code).exists(): return code class Inventory(models.Model): premises = models.ForeignKey(Premises, on_delete = None) item = models.CharField(max_length=255,blank=False,unique=True) code = models.CharField(max_length=255, null=True, blank=True,default = unique_rand) quantity = models.IntegerField(null = True, blank=True) is_defected = models.BooleanField(default = False) objects = UserManager() def __str__(self): return self.item views class Inventory(ListView): model = Inventory template_name = 'inventory.html' def get_queryset(self): pre = Premises.objects.get(userprofile__user = self.request.user) queryset = Inventory.objects.filter(premises = pre) return queryset I have already imported models and Usermanager. -
Whats the different between override the update method inside view and inside serializers?
I am new in django i know this is a naive question but im so confused about when exactly do we have to override update method located in view and when do we have to override update method located in serializer? -
How can i filter data retrieved from a Django Rest Framework endpoint
I have some data on a MongoDB database, it looks like this, where i have more records all looking like the following document: {"data":[{"one":"[[1756.53, 2.419583], [13755.95, 0.056274], [1755.62, 0.027065], [11755.59, 0.085065], [1175.28, 906], [11752.33, 0.333531], [11752.31, 0.5], [11752.03, 0.6], [11752.02, 0.107656], [1751.99, 1.288268], .... }], {"item: "one"} Those records are fetched from a DRF api endpoint: http://127.0.0.1:8000/market/myapi/ And then they are rendered into my template on a DataTable using an AJAX call: $(document).ready(function() { var table = $('#mytable').DataTable({ "ajax": { "type" : "GET", "url" : "/myapi/?format=datatables", "dataSrc": function(json) { return JSON.parse(json.data[0].one); } }, "columns": [ {"data":0, "title":"DATA"}, ] }); }); The problem with my actual code is that there are a lot of documents into the DB, and i don't want to display on my table all of them, just a certain one. For example, if the slug of my Django page is one, and i'm on http://127.0.0.1:8000/pages/one/, i need to retrieve the data of the record one. Here is how i figured it out, but i don't really know how to do it in terms of code. Should i do edit my AJAX call or is there a way to do it straight in Django? Any advice is appreciated -
nginx is trying to host my media files from the wrong location? How can I fix this?
I have created a django app and I am using digitalocean to host the site. I have a media directory. I have installed nginx. I have configured nginx to get my media files from match my server file list. -For some strange reason, nginx is changing the media file directory and trying to get files from the wrong location. I can not figure out how to change the nginx configuration to get media files from the correct location. -File serving works perfectly fine on my development box using localhost. As soon as I push the code to digitalocean with gunicorn and nginx, the media hosting directory magically changes. I am trying to find out if nginx has a secret configuration file? I have gone through all of the configurations on the Django settings.py and urls.py files to make sure they are pointing to the right directions. I have gone through my server files and my nginx configuration to make sure they are pointing to the right places. On the Django development side: -I have edited the settings.py to set the MEDIA_ROOT and MEDIA_URL: (My reputation isn't high enough for photos) -Django Settings.py -I have edited the URLS.py: -urls.py -On my … -
Cannot assign SimpleLazyObject in my code
I want to insert 'FineModel' data on 'ODE_Marks_Model' inserting time. model.py class ODE_Registation_Model(models.Model): student = models.ForeignKey(User,on_delete=models.CASCADE) subject = models.ForeignKey(SubjectMaster,on_delete=models.CASCADE) ode = models.ForeignKey(ODE_List_Model,on_delete = models.CASCADE,verbose_name="which ode") exam_date = models.DateField() registration_date = models.DateField() class ODE_Marks_Model(models.Model): ode_registered = models.OneToOneField(ODE_Registation_Model,on_delete=models.CASCADE) marks = models.SmallIntegerField() verified_by = models.ForeignKey(User,on_delete=models.CASCADE) class FineModel(models.Model): fine = models.IntegerField() user = models.ForeignKey(ODE_Registation_Model,on_delete=models.CASCADE) admin.py @admin.register(ODE_Marks_Model) class ODE_Marks_Admin(admin.ModelAdmin): list_display = ('ode_registered','marks','verified_by') exclude = ['verified_by',] def save_model(self, request, obj, form, change): instance = form.save(commit=False) if instance.marks == -1: fine = FineModel.objects.create(user=request.user,fine=50) fine.save() instance.verified_by = request.user instance.save() return instance I expect the output to save FineModel object in save_model but, I got the error : ValueError at /admin/core/ode_marks_model/add/ Cannot assign ">": "FineModel.user" must be a "ODE_Registation_Model" instance. -
Django 'int' object has no attribute 'resolve_expression'
I tried to get profit here, but it gives me this error: 'int' object has no attribute 'resolve_expression' This is what I tried: def get_trades_queryset(self): trades = self.get_trades() print(trades) trades_sell = self.get_trades_sell() trades_buy = self.get_trades_buy() if trades_sell: traded_price_sell = trades_sell[0] print(traded_price_sell) traded_share_sell = trades_sell[1] else: traded_price_sell = 0 traded_share_sell = 0 print(traded_share_sell) if trades_buy: traded_price_buy = trades_buy[0] traded_share_buy = trades_buy[1] else: traded_price_buy = 0 traded_share_buy = 0 formula = traded_price_sell * traded_share_sell - traded_price_buy * traded_share_buy r = trades.annotate(traded_price_sell=traded_price_sell, traded_price_buy=traded_price_buy, traded_share_buy=traded_share_buy, traded_share_sell=traded_share_sell, profit=ExpressionWrapper(formula, output_field=models.CurrencyField()), ) return r I am very new to python. Should I use ExpressionWrapper only when I have F() expression? Because the QuerySet (trades, trades_sell and trades_buy are QuerySet here) initially is empty, so it gives 0 to formula here. I also tried profit = c(formula) which gives similar results. How can I fix it? Any help is appreciated. -
Django ListView: filter history based on chosen user
I've got a History ListView in which I'd like to let my Users filter the Historyitems based on which User they picked in the ModelChoiceFields I'm providing them My History View looks like this: class HistoryItems(ListView): model = HistoryItem template_name = 'history/history_table.html' context_object_name = 'history_items' def get_context_data(self, **kwargs): user_id = kwargs.get('user_id') query = {} if user_id: user = get_object_or_404(User, pk=user_id) query['changed_by'] = user else: user = None history_items = HistoryItem.objects.filter(**query).select_related('changed_by', 'content_type') return { 'filter_history_form': HistoryFilterForm(user_id=user_id), 'history_items': history_items, } It returns me the correct History items in a big table (see html below). And then I've got this form: class HistoryFilterForm(forms.Form): normal_user = forms.ModelChoiceField(User.objects.filter(special=None), label="Normal Users", empty_label="All normal users") special_user = forms.ModelChoiceField(User.objects.exclude(special=None), label="Special User", empty_label="All special users") def __init__(self, *args, **kwargs): user_id = kwargs.pop('user_id') super(HistoryFilterForm, self).__init__(*args, **kwargs) self.fields['normal_user'].initial = user_id self.fields['special_user'].initial = user_id self.helper = FormHelper() self.helper.label_class = 'sr-only' self.helper.add_layout(Layout( Row( Div('normal_user', css_class='col-sm-3'), Div('special_user', css_class='col-sm-3'), ) )) This form simply creates two ModelChoiceFields of the same User object, just that one field shows all "normal" users and the other all "special users" My Urls looks lime this: urls = [ path('', views.HistoryItems.as_view(), name='history_index'), path('u=<int:pk>', views.HistoryItems.as_view(), name='history_index'), ] I figured that I would need to refresh my page all the time when … -
How to use django and mysql?
I want to use django with mysql but it alwyase give me error: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. so I tried to download with pip install mysqlclient but it gived me error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ And when I tried to download visual studio it dosen't work,I'm using windows 7 32 bits,I tried it give the windows that it's downloading but it always suddenly stop and it doesn't download So I want to know if there is any visual studio for windows 7 or can I install the C++ package directly without installing visual studio