Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python OOP Design questions
I am currently building a Django application to track and analyse my stock porfolio. I currently have two [model] classes: Stock and Transaction. A stock holds information about a company and the transaction records all bought/sold shares from a stock. In my Stock class I have a 'stock' attribute. This is simply a holding attribute. All methods for updating this are done via the Transaction model (e.g. when I sell or buy shares). My reasoning is that everytime I view the object page, or call it, I don't have to perform a calculation to determin the amount of shares a stock own; this happens when we are selling or buying. The question I have is: is this a good way of writing software? Personally, I think this is a pros and cons case. But it would be nice to hear others thoughts and experiance. Perhaps I should just move the methods to the Stock model? Many things to consider here... Stock: class Stock(models.Model): """ Stock model refrences an organisation on the stock market. """ # DESC: Name of the company. name = models.CharField( unique=True, max_length=50, validators=[utils.alphabetical_chars_only] ) # DESC: Uniquely identifies a stock globally. isin = models.CharField( unique=True, verbose_name="ISIN", max_length=ISIN_LEN, … -
How to generate modelformset based on records in another model?
Suppose this is my model: class Question(models.Model): text = models.CharField(max_length=200) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) I want to create a modelformset from Answer model which automatically generates a form based on the number of records in Question model. model_formset = modelformset_factory(Answer, fields=('answer',), widgets = { 'answer': RadioSelect(choices=RATING_CHOICES),}) if request.method == "POST": form = model_formset(request.POST) if (form.is_valid()): # # # -
why can't I use my Django utilities, with django-admin
I installed Django with pip3 and got the up to date version but it says 'django-admin command not found'. I have python latest to, also when I tried to cd into the directory of Django admin but I failed. -
How to add manually on delete SQL constraints in Django?
In an existing Django project I experience critical performance issues when objects of a certain model are deleted. Actually the whole infrastructure breaks down. I'm pretty that this is caused by a foreign key field to another model with many and large entries. After several hours of googling I found a possible solution: Implementing on delete constraints on database level. I also found a long lasting discussion in a Django PR https://github.com/django/django/pull/8661 which would enable this feature. But I seems like it never reached 100% and will not be merged in the near future. Another way to solve my issue is mentioned in Django Docs https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.DO_NOTHING DO_NOTHING Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field. I'm using MariaDB. And I want to add a SET_NULL constraint to only one foreign key field of one model on database level. How can I do that in Django? I can perfectly live with hard coded ugly solutions, if they solve my problem and don't introduce new ones. -
SQL datetime2(7) field to Django [duplicate]
I need to rewrite this SQL column to a django model field DateCreated (datetime2(7), not null) what does the datetime2(7) exactly translate to? Many thanks in advance! -
Django Count lines in a Subquery
I need to count lines in a subquery and here is my solution for sqlite. class SQCount(Subquery): """Count lines in subquery""" template = "(SELECT count(*) FROM (%(subquery)s) _count)" output_field = models.IntegerField() sub = MyModel.objects.filter(user=OuterRef(OuterRef('id'))).values('id') qs = qs.annotate(count_total=SQCount(sub)) It works great for sqlite but not for MySQL (complains about Unknown column in 'where' clause). Any help appreciated. -
How can I get the ids of a queryset from a model and store them into a different model using a form?
I have a model called 'Competicion', with some objects and another model called 'Participante'. This second model has two fields: a foreignkey with the user and another foreingkey to 'Competicion'. In the view, I've made queryset from 'Competicion' and with a for loop in the template I've given each object the button of the form. With storing the user of the current session I have no problem but I want the form to know which object of the queryset it is to grab its id. #I have no problem with choices I just don't include them to save space Models.py class Competicion(models.Model): ciudad = models.CharField(max_length=50, null=True, choices=Ciudades_a_elegir, default="Ninguna") nombre = models.CharField(max_length=20, null=True, choices=Competiciones_a_elegir, default="Ninguna") titulo = models.CharField(max_length=40, null=True) fecha = models.DateField(null=True) participantes = models.IntegerField(null=True) flyer = models.ImageField(null=True, upload_to='imagenes', default='Ninguna') def __str__(self): return self.nombre + " " + self.titulo class Participante(models.Model): competicion = models.ForeignKey(Competicion, on_delete=models.CASCADE, null=True, blank=True) participantes = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.competicion.nombre + " " + self.competicion.titulo forms.py class ParticipanteForm(ModelForm): class Meta: model = Participante exclude = ['competicion', 'participantes'] views.py def competiciones(request): qs = Competicion.objects.all() form = ParticipanteForm(request.POST or None) if form.is_valid(): nombres = form.save() nombres.competicion = ???#Help me nombres.participantes = request.user nombres.save() return redirect('home') context = … -
Django: Refer to User objects in fixture for another model
To avoid the XY problem, I will describe my problem and my attempted solution separately. My problem I have an Appointment model which I want to write fixtures for. There is a one-to-many mapping from the Django User model to the Appointment model (every appointment has only one client, but a client can have multiple appointments). I know I can hard code the primary key for the Users in my appointment fixtures, but would be a brittle solution. Hard coding the foreign keys also compromises the readability of my fixtures. My attempted solution I looked at this question, which has an answer linking to Django documentation for natural keys. However, I ran into a problem attempting to use this approach. I believed I could create a proxy model for the User model, so I could create a custom Manager for natural keys. Here is my proxy model: class UserProxy(User): objects = UserManager # The UserManager class's code is omitted class Meta: proxy = True unique_together = [['username']] (If the UserManager class's code is relevant, please let me know in a comment, and I will add it.) However, when I run manage.py makemigrations, I get this error: ERRORS: accounts.UserProxy: (models.E016) 'unique_together' … -
Django Channels with Mongo DB - Python
I am trying to connect to mongo db using pymongo in my models.py and sending the connection object to UI using django channels. I wrote simple function to connect to mongo db using pymongo in my models.py like below models.py from django.db import models from pymongo import MongoClient def connectDB(): client = MongoClient('localhost', 27017) return client Now I have consumer.py to interact with my front end where in my websocket_connect method am calling connectDB() just to send the connection status to my UI. consumers.py from .models import connectDB async def websocket_connect(self, event): status = connectDB() await self.send({ "type": "websocket.accept", "text": status } ) here am just calling my connectDB() function which is there in my models to get the connection establishment status but throws error like below TypeError: 'Database' object is not callable. If you meant to call the 'encode' method on a 'MongoClient' object it is failing because no such method exists. how to solve this ? or is there any other way I can connect to db and send the status to UI using my consumers.py ? Thanks -
django - AbstractUser atributes gone ....?
so for some reason i get this error : $ python manage.py shell Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from auctions.models import * >>> u = User.objects.all() >>> u <QuerySet [<User: bob>]> >>> u.id Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'id' i did not set any primary key to overwrite djabgo's defaults (this is the code..) class User(AbstractUser): def __str__(self): return f"{self.username}" what is going on ??? -
How to initialize Django model fields whose loading was deferred?
I can overload the Model's __init__ to change the initialization behavior. But how to do the same when some of the model field loading are deferred? How do I run the initialization logic when that fields are loaded later? Is there something similar to def clean_field() that is called when the field is loaded later? -
How to create Route and View for HEAD http verb in Django Rest Framework
I would like to allow clients to send HTTP HEAD requests to my endpoint to allow them to check whether the resource exists without requiring the bandwidth to respond with the resource in the response body if it does. It should of course behave the same as GET but without sending the body of the response, just the header. I initially thought this would be handled by the DRF Router and ModelViewSet, but this question indicates that that isn't the case. Therefore I followed the advice in the answer posted there and wrote the following in urls.py and views.py: project/urls.py urlpatterns = [ path('api/resource/<str:value>', views.ResourceViewSet.as_view(actions={'head': 'retrieve', 'get': 'retrieve'})), app/views.py class ResourceViewSet(viewsets.ModelViewSet): serializer_class = serializers.ResourceSerializer queryset = Resource.objects.all() lookup_field = 'value' This setup isn't working for head requests. The get requests are all working as expected. Interestingly, the location and type of error I get depends on the client: From Postman client I get Parse Error: The server returned a malformed response in the Postman console. The DRF logs however show it giving the correct response code and there are no errors on the server. From CURL I get the correct response in the client, but the server throws a reset … -
Can anyone help me to implement hierarchical database in django or anyone has similar codes for the problem mentioned below?
I hope you will take this as a challenge. I want to make hierarchical database in django . This is a bit challenging to me and i am stuck here for many days and could not get solutions. Please help . Here i want to create is: Base class CellPhone N number of Brands for cellphones , N number of cellphone-models for each brands , N number of features for each models , N numbers of attributes for each feature and value associated with the attributes as shown in the picture above. This is the image how it should be implemented and appear on the admin: enter image description here enter image description here -
Certain Celery Tasks starts but hangs and never executes
I have an issue with Django and Celery where some registered tasks never get executed. I have three tasks in my tasks.py file, two of them; schedule_notification() and schedule_archive() work without issue. They are executed without issue at the predefined ETA. With the schedule_monitoring() function, I can see the job is started in Celery Flower but it never actually executes. It just sits there. I have confirmed I can run the command locally from the worker so I'm not sure where the issue could be. tasks.py (failing function) @task def schedule_monitoring(job_id: str, action: str) -> str: salt = OSApi() # This is a wrapper around a REST API. job = Job.objects.get(pk=job_id) target = ('compound', f"G@hostname:{ job.network.gateway.host_name } and G@serial:{ job.network.gateway.serial_number }") policies = [ 'foo', 'bar', 'foobar', 'barfoo' ] if action == 'start': salt.run(target, 'spectrum.add_to_collection', fun_args=['foo']) for policy in policies: salt.run(target, 'spectrum.refresh_policy', fun_args=[policy]) create_activity("Informational", "MONITORING", "Started proactive monitoring for job.", job) elif action == 'stop': salt.run(target, 'spectrum.remove_from_collection', fun_args=['bar']) for policy in policies: salt.run(target, 'spectrum.refresh_policy', fun_args=[policy]) create_activity("Informational", "MONITORING", "Stopped proactive monitoring for job.", job) else: raise NotImplementedError return f"Applying monitoring action: {action.upper()} to Job: {job.job_code}" Celery Configuration # Async CELERY_BROKER_URL = os.environ.get('BROKER_URL', 'redis://localhost:6379') CELERY_RESULT_BACKEND = os.environ.get('RESULT_BACKEND', 'redis://localhost:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER … -
Deploy Django App to Render as a static site
Anyone kind enough to tell me what should the build command be? Also what should there be in the publish directory (I named it dist and it has an empty index.html). My build script right now is: #!/usr/bin/env bash # exit on error set -o errexit python manage.py collectstatic --no-input python manage.py migrate -
How get another field than GROUP BY using MIN django ORM?
FIRST: This question is NOT THE SAME as this one: How to query as GROUP BY in django? please read carefully, I am asking to get the different field than the one group by. That questions for the same field. This is NOT THE SAME question. If we have table with columns: warehouse; product; price; How can we do this SQL query SELECT product, min(price) FROM table GROUP BY warehouse How to do that with django orm besides raw query? Can we do it with extra()? -
How to walletconnet with QR code in django?
Well I just wanted to ask that is there any package for django python to connect wallet by scanning QR code in django. I am using web3.py but i didn't see any package for wallet connect. If there is such package then please share with me and tell me how is possible. -
Name error when trying to filter date field from base table in django
I have two models class Rule(models.Model): pmdruleid = models.BigIntegerField(primary_key=True) effectivedate = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'rule' class Ruledefinitions(models.Model): ruleactivestatus = models.CharField(max_length=14) pmdclinicalruleid = models.OneToOneField(Rule, models.DO_NOTHING, db_column='pmdclinicalruleid', primary_key=True) class Meta: managed = False db_table = 'ruledefinitions' unique_together = (('pmdclinicalruleid', 'pmdclinicalvariableid'),) I am trying to filter records based on effectivedate field in viewset like below class ActiveclientViewSet(viewsets.ModelViewSet): queryset = Ruledefinitions.objects.select_related('pmdclinicalruleid').filter(pmdclinicalruleid__effectivedate < datetime.now()) I am getting NameError: name 'pmdclinicalruleid__effectivedate' is not defined. -
create() populates manytomany with every row in the related table, rather than leave it blank
Currently, I have three models in models.py: class User(AbstractUser): pass class Watchlist(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) listings = models.ManyToManyField('Listing', related_name = "watchlists", blank = True) class Listing(models.Model): title = models.CharField(max_length = 150) description = models.TextField() The problem occurs when a user creates their watchlist, which is handled by this piece of code in views.py: # Each listing has it's own page, # with a URL of the form /listing/<int:pk> def listing(request, pk): listing_instance = Listing.objects.get(pk = pk) if request.method == "GET": # return the page for the listing with primary key pk elif request.user.is_authenticated: watchlist_instance = Watchlist.objects.get_or_create(user = request.user)[0] watchlist_instance.listings.add(listing_instance) I would expect the row created by Watchlist.objects.get_or_create(user = request.user) to have no relations in its listings, but instead it has relations to every row in the Listing table (meaning the last line does nothing). For example, if the Listing table contained three rows: listing1 listing2 listing3 and a new user viewed the page for listing2 and tried to add it to their watchlist, their watchlist would include all three listings. To confirm it was create() that was causing the problem, I tried this: elif request.user.is_authenticated: watchlist_instance = listing_instance.watchlists.create(user = request.user) which looks (to me) to be basically … -
How to do `SELECT product, min(price) FROM table GROUP BY warehouse` in django ORM
If we have table with columns: warehouse; product; price; How can we do this SQL query SELECT product, min(price) FROM table GROUP BY warehouse How to do that with django orm besides raw query? Can we do it with extra()? -
how can i deliver two values to the django backend in jquery slider?
jquery <script> $(function () { $("#slider-range").slider({ range: true, min: 1910, max: 2019, values: [1950, 2010], slide: function (event, ui) { $("#amount").val(ui.values[0] + "won - " + ui.values[1] + "won"); } }); $("#amount").val($("#slider-range").slider("values", 0) + "won - " + $("#slider-range").slider("values", 1) + "won"); }); </script> html <FORM NAME="myForm" method="GET" action="{%url 'search_result'%}"> <p> <label for="amount">won:</label> <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;" aria-valuemin=""> </p> <input type="submit" value="search" id="search_button"> </FORM> I want to deliver two values to the django backend in GET form. two values are values[0] and values[1]. How to modify the input tag inhtml? -
Django NameError: name 'TypeError' is not defined
I recently started working for a company using and making changes to an existing Django platform. Right now im trying to cache static assets as well as ldap session since there is a bottleneck somewhere that is making my webpage load to slow. When trying to use memcached to cache ldap session I changed my django settings, after reloading the webpage it wouldn't load so I reverted the changes and reloaded apache again but now It's throwing the next exception: [Wed Jan 06 15:15:50.852034 2021] [mpm_event:notice] [pid 533599:tid 140576061348928] AH00493: SIGUSR1 received. Doing graceful restart Exception ignored in: <function Local.__del__ at 0x7fda60831790> Traceback (most recent call last): File "/var/www/deploys/dataforge/staging/current/venv/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fda60831790> Traceback (most recent call last): File "/var/www/deploys/dataforge/staging/current/venv/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message [Wed Jan 06 15:15:51.068359 2021] [mpm_event:notice] [pid 533599:tid 140576061348928] AH00489: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Wed Jan 06 15:15:51.068387 2021] [core:notice] [pid 533599:tid 140576061348928] AH00094: Command line: '/usr/sbin/apache2' My … -
Django: ERROR: Cannot install -r requirements.txt
I was following the advices stated here How to run cloned Django project? because I have to work on a cloned Django project. The steps I followed are: Clone Create and start a virtual environment Install the project dependencies And here is when I get the following error after running pip install -r requirements.txt : Collecting django-private-chat==0.3.0 Using cached django_private_chat-0.3.0-py2.py3-none-any.whl (23 kB) INFO: pip is looking at multiple versions of django-polymorphic to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-parler to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-mptt to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-model-utils to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-meta-mixin to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-meta to determine which version is compatible with other requirements. This could take a while. … -
Getting Syntax Error when trying to run manage.py
I am getting a Syntax Error when I am trying to run python manage.py runserver I have created my virtual environment and there is no error in the code which I added. The Error message is coming from manage.py and the Django files. I am using Python 3.0.9. I added a new app using python manage.py startapp, but now python manage.py runserver gives me lines of Tracebacks. -
Order a list coming from model's Meta option in a @property
I have this model: class Author(models.Model): class Meta: app_label = 'myapp' surname = models.CharField(max_length=255) firstname = models.CharField(max_length=255) extrainfo = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return u"{0} {1} {2}".format(self.firstname, self.surname, self.extrainfo) @property def alpha_name(self): return u"{0}, {1} {2}".format(self.surname, self.firstname, self.extrainfo) class Meta: ordering = [self.surname] class Source(models.Model): class Meta: app_label = "bassculture" short_title = models.CharField(max_length=255) author = models.ForeignKey("myapp.Author", blank=True, null=True, on_delete=models.CASCADE, related_name="sources") View: def SourceList(request): sources = Source.objects.all() return render(request, 'source/source_list.html', {'sources': sources}) Template: {% for source in sources %} <tr> <td>{{ source.author.alpha_name }}</td> <td>{{ source.short_title }}</a></td> <td>{{ source.date }}</td> </tr> In the template I'd like the alpha_name to be ordered by surname. As you can see I did put the class Meta: ordering = ... in my Author model. Nevertheless, the template renders the list of authors ordered by id (the default ordering, I suppose). How can I order it via the model/view? I know about the |dictsort tag, and I tried to have the same result with that (with no luck, it returns empty). I'd like to have the model or the view sort the ordering anyway, reducing the template's logic to a minimum.