Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nested serializers for not direct related names
I have below models in my project class TicketCounter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ticket_counter_name = models.CharField(max_length=100, default="") class TicketCategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ticket_category_name = models.CharField(max_length=100, default="") ticket_category_rate = models.CharField(max_length=100, default="") class WorkerToTicketCounter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ticket_counter = models.ForeignKey(TicketCounter, related_name="workers") worker = models.ForeignKey(User, related_name='ticket_counter') worker_to_ticket_counter_is_deleted = models.BooleanField(default=False) class TicketCounterToCategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ticket_counter = models.ForeignKey(TicketCounter, related_name="categories") ticket_category = models.ForeignKey(TicketCategory) Each TicketCounter will have a worker(User) and TicketCategorys. When the worker login into an Android app. He will have to get his details like email first_name and 'last_name'. I did it with below serializer. class MeSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'pk', 'first_name', 'last_name', 'email', ) In my application, there is a need, where not only details but also his associated TicketCounter is needed. So I have added ticket_counter like below class MeSerializer(serializers.ModelSerializer): ticket_counter = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ( 'pk', 'first_name', 'last_name', 'email', 'ticket_counter', ) def get_ticket_counter(self, user): qs = user.ticket_counter.filter(worker_to_ticket_counter_is_deleted=False) if qs.exists() and hasattr(qs.first().ticket_counter, 'ticket_counter_name'): return qs.first().ticket_counter.ticket_counter_name return "--" But now I need to get the associated categories of that ticket_counter in list of objects in MeSerializer. Is it possible? -
Django add multiple database NAME for different user
In my django project i have to differenziate database name by user. i would to create a table, or a field in user table with database name and in settings.py insert related values checking user connected, but i have two doubt: How can i insert into DATABASES dict new variable? DATABASES = { 'default': { 'ENGINE': 'django.db.test.postgresql', 'NAME': myvar, 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', } } Settings.py is read before table and db instantiation, how is possible passing values after login? There is another pythonic way to achieve this result? Thanks in advance -
Gunicorn only starting worker when some request is sent
I have configured gunicorn for 5 workers. However only 1 is started, rest are like in sleeping state. Only when I would try to login i.e. a request is sent to them they would fork/start for the first time. Below is config. $VIRT_ENV/gunicorn -c config.py utrade.wsgi:application \ --preload \ --log-level=debug \ --timeout=30 \ --access-logfile=- \ --access-logformat="%(r)s %(s)s" \ --log-file=- Inside the django there is tornado worker so there is some sort of dependency where I want all the tornado processes to be up before user logins. How can I make gunicorn start all the workers and not wait for request? I tried preload flag but it didn't help. -
How do I construct a Django model to return a row-based dictionary?
I am planning a data structure with a list of arbitrary key-value pairs, in other words a dictionary. (The key is distinct from the object ID provided by Django.) Ultimately I want to perform a query with the following logic: Return all key-value pairs associated with object X. They should be accessible by key, e.g. x.dict["key"] One option is to store a dictionary as a string in a single field, but this limits my ability to make other queries ("all entries with the key Y", "all entries with the value Z"). Another option is to encode the dictionary as fields in the model, but the dictionary "schema" is too fluid to be enforced in the database itself. Thus, I want to encode each key-value pair as an entry in a table. How can I query this table in a way that allows me to access the entries like a dictionary? -
Django ModelChoiceField is not initially selected according to related models
I'm having some difficulties with Django's ModelChoiceField. I wrote the following code: class BookForm(ModelForm): publisher = forms.ModelChoiceField(queryset=Publisher.objects.all()) ... Now Book and Publisher are related this way: Book --> Library --> SubPublisher --> Publisher. All relations were made using ForeignKey. My form is like that: Publisher (ModelChoiceField) SubPublisher (ModelChoiceField with autocomplete widget that filters according to Publisher selection) Library (same as SubPublisher, filters according to SubPublisher) My problem is that I can't get ModelChoiceField to select the relevant Publisher out of the publishers list. Note: Publisher & SubPublisher are only there to filter on Libraries - and it works, the issue is only about setting initial values according to selected Library's ForeignKeys What am I missing? Thanks in advanced! -
How to load static JavaScript file and css in Django with Pycharm
I am new to django , I am unable to set path to load js and css file from directory. When I run server my page is showing without css and js. I setting file of project I have set static path as: STATIC_URL = '/templates/' and in template directory I have 3 dir named html, js, css. I am able to load html file from html dir but not js and css. -
Updating nested model using model.objects.filter(xx).update with dictionary is it possible?
Say I have the following two models class modelEmployer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) employer_zip = models.IntegerField(default=0) I know if I had a dictionary like this my_dict = {"employer_zip": 1210} and then I did this modelEmployer.objects.filter(id=someId).update(**my_dict) it would pass. Now in my case my dictionary basically has a nested object user in it as well and it looks like this {'user': {'username': 'adam', 'last_name': 'Griffin', 'password': 'adminabc', 'email': 'adam@gmail.com', 'first_name': 'Adam'}, 'employer_zip': 98033} Now if I do this - it will fail modelEmployer.objects.filter(id=someId).update(**my_dict) Is there any way I can accomplish this ? -
Compute Django Model Field Value on First Access (Lazy Field)
Description: I want to add a new field to an existing Django model. The value of this field for each instance can be computed using an external API. Since there are already a large number of instances saved in the database and the external API has a quota, it is not a good idea to compute this field for every instance on database migration. It worths mentioning that this field will be rarely accessed. Question: Is it possible to compute the value, only on the first access to that specific field and save it in the database for future uses? Is there an standard way of handling this situation? -
Django filter returning blank queryset
I'm using Django 2.0 In my app's models.py file, I have a model Abc and model manager as AbcManager and queryset as AbcQueryset class AbcQueryset(models.query.QuerySet): def search(self, query): q = Q(show_to_all=True) if query: q.add(Q(walmart_record__name__icontains=query) | Q(amazon_record__category__icontains=query), q.connector) if q: return self.filter(q).distinct() else: return self.all() class AbcManager(models.Manager): def get_queryset(self): return AbcQueryset(self.model, self._db) def update_or_create(self, walmart_record, amazon_record, **save_data): record = Abc.objects.filter( walmart_record_id=walmart_record.pk, amazon_record_id=amazon_record.pk ) print(record.query) print(record) print('walmart_record: ' + str(walmart_record.pk)) print('amazon_reocrd: ' + str(amazon_record.pk)) if record.exists(): print('~~~~~~~~~~~~~~~~~~ record alreay exists') record.update(**save_data) print(record.first().pk) return record.first(), True record, created = self.get_queryset().get_or_create( walmart_record=walmart_record, amazon_record=amazon_record, **save_data ) print('~~~~~~~~~~~~~~~~~~ record created') print(record.pk) return record, created def search(self, query): return_data = self.get_queryset().search(query).order_by('-created') class Abc(models.Model): walmart_record = models.ForeignKey(WalmartRecord, on_delete=models.CASCADE) amazon_record = models.ForeignKey(AmazonRecord, on_delete=models.CASCADE, null=True) modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) objects = AbcManager() def __str__(self): return self.arbitrase def get_absolute_url(self): return reverse('detail', kwargs={'pk': self.pk}) But on calling **update_or_create() it is always creating a new record.** Running sql script generated from record.query is working fine in phpmyadmin and results are coming but print(record) gives blank list as <ArbitraseRecordQueryset []> -
None-root user commands not found
When I logged in as root , all commands will be executed . But when I logged in as another user, cant use any of these commands : mkvirtualenv, activate , deactivate , workon , .... The error is -bash: COMMAND : command not found But accidentally i found virtualenv command will work instead of mkvirtualenv But dont know why ? anyone can help ? -
Django objects uniqueness hell with M2M fields
class Badge(SafeDeleteModel): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.PROTECT) restaurants = models.ManyToManyField(Restaurant) identifier = models.CharField(max_length=2048) # not unique at a DB level! I want to ensure that for any badge, for a given restaurant, it must have a unique identifier. Here are the 4 ideas I have had: idea #1: using unique_together -> Does not work with M2M fields as explained [in documentation] (https://docs.djangoproject.com/en/2.1/ref/models/options/#unique-together) idea #2: overriding save() method. Does not fully work with M2M, because when calling add or remove method, save() is not called. idea #3: using an explicite through model, but since I'm live in production, I'd like to avoid taking risks on migrating important structures like theses. idea #4: Using a m2m_changedsignal to check the uniqueness anytime the add() method is called. I ended up with the idea 4 and thought everything was OK, with this signal... @receiver(m2m_changed, sender=Badge.restaurants.through) def check_uniqueness(sender, **kwargs): badge = kwargs.get('instance', None) action = kwargs.get('action', None) restaurant_pks = kwargs.get('pk_set', None) if action == 'pre_add': for restaurant_pk in restaurant_pks: if Badge.objects.filter(identifier=badge.identifier).filter(restaurants=restaurant_pk): raise BadgeNotUnique(MSG_BADGE_NOT_UNIQUE.format( identifier=badge.identifier, restaurant=Restaurant.objects.get(pk=restaurant_pk) )) ...until today when I found in my database lots of badges with the same identifier but no restaurant (should not happend at the business level) I understood there … -
How to write python script to run automatically at 11:30 pm everyday? [duplicate]
This question already has an answer here: Django - Set Up A Scheduled Job? 21 answers I am working on an analysis project. I have to fetch the news daily from some news channel. I have written a python script in my Django views which are used to fetch the news every day. What can I do in my script so that it runs automatically at 11:30 pm. Here is my script: def ndtv(request): url = 'https://www.ndtv.com' resp = requests.get(url) soup = BeautifulSoup(resp.text, 'html.parser') i = 1 data = "" da = [] d1 = [] href = [] date = [] d = datetime.now() - timedelta(1) for x in soup.find_all('a'): try: n = x.text.strip() n2 = x.get('href').strip() if (len(n) > 60): d1.append(n) href.append(n2) resp = requests.get(n2) soup2 = BeautifulSoup(resp.text, 'html.parser') for x in soup2.find_all('span'): if x.get('itemprop') == "dateModified": y = x.text[9:22] date.append(y) # print(n,x.text[9:]) y = y.lstrip(':') y = y.rstrip('I') if (dateparser.parse(y) > d): qs = NDTVdb(title=n, href=n2) qs.save() print(n, y) break except: p = 1 return HttpResponse("<h1>Success NDTV</h1>") When I run this script fetches all the title of today news and save it to my database. The URL is following http://127.0.0.1:8000/news/ndtv Please help me to run it automatically … -
How can I restrict user from accessing some specific urls?
I have created a view which allow user to delete a specific Booking provided with id but I dont want other user except the user associated with the Booking object to delete it. How I can restrict user to access urls which delete booking they not own. The urls: path('manage/', views.ManageView, name='manage'), path('manage/delete_booking/(?P<pk>\d+)', views.delete_booking, name='delete_booking'), The views: @login_required def delete_booking(request, pk): booking = Booking.objects.get(pk=pk) booking.delete() return redirect('manage') @login_required def ManageView(request): bookings = Booking.objects.filter(user=request.user) context = { 'user': request.user, 'bookings': bookings } return render(request, 'timetable/manage.html', context) Template: <div class="w3-content"> <div class="w3-third w3-padding w3-center"> <h4 class="bg-color">Infomation</h4> <p>Student ID: {{ user.profile.student_id }}</p> <p>Full name: {{ user.last_name }} {{ user.first_name }}</p> </div> <div class="w3-two w3-padding w3-center"> <h4 class="bg-color">Booking</h4> {% if not bookings.exists %} <p>You don't have any booking</p> {% else %} {% for booking in bookings %} <p>{{ booking.room }} {{ booking.date }} {{ booking.lesson.number }} <a href="{% url 'delete_booking' booking.pk %}">Delete</a></p> {% endfor %} {% endif %} </div> -
Django - Store user location data with GeoDjango
I want to use GeoDjango to get retrieve from the user location point information like city, country, etc. In order to use GeoDjango I have to install PostGIS which adds geographic object support to PostgreSQL. Questions: Do I have to install PostGIS on the default database or is a best practice to store location data in different database? Can I mix django.db.models and django.contrib.gis.db.models to make clear difference between GeoDjango fields and the default ones? Example: from django.db import models from django.contrib.gis.db import models as geo_models class Profile(models.Model): """ This model extends the `User` model as an One-To-One link. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) company_name = models.CharField(max_length=100, blank=True) location = geo_models.PointField() -
Django rest-auth facebook authentication does not return JWT
I'm trying to get JWT by using django-rest-auth + Social Authentication(Facebook). I've followed all the examples from rest-auth-doc When I used httpie to request for JWT, I got "500 Internal Server Error" and my facebook user data saved to my User model. http POST :8000/rest-auth/facebook/ access_token="MY FACEBOOK ACCESS TOKEN" I could successfully obtain JWT at the second time. I found that JWT returned successfully if my user data is in the User model. I have no idea why this is happening. Is there something else I need to do Please let me know if any further info is needed for figuring out the problem. -
Django; How to test models or forms if there's no custom method
I'm just beginner and it's just general question. I started learning how to do test in Django. I'm wondering how and what I should run the test if there's not custom method in models or forms. Seems like tutorials run the tests using custom methods but I didn't create custom method. A tutorial says we should test creating, changing and deleting but I'm wondering how I can test. Anyone who can give me tips? -
When to use which serializer representation?
I'm getting started in Django rest framework and its fun, however, serializers are quite overwhelming for me. I am still not able to understand when do we use nested serializers and when we use built in representation fields like PrimaryKeyRelatedField, HyperlinkedIdentityField etc. Can anyone add a little description on when do we use one and when do we use the other ? -
How to login using LDAP in Django
I am trying to enable LDAP server for login and authenticate in my Django application. I read django-auth-ldap tutorial and done all the changes in settings.py. But I not able to login from LDAP server users, Django always try to login only form local database. What i have to do and change any thing while login user? any changes is required in view.py authenticate() function for login. My code snippets are below : settings.py AUTH_LDAP_SERVER_URI = 'ldap://my_domain.com' AUTH_LDAP_BIND_DN = 'cn=admin,dc=my_domain,dc=com' AUTH_LDAP_BIND_PASSWORD = 'My_password' AUTH_LDAP_USER_SEARCH = LDAPSearch( 'ou=users,dc=my_domain,dc=com', ldap.SCOPE_SUBTREE, '(uid=%(user)s)', ) AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } # Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=django,dc=my_domain,dc=com', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)', ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') # Simple group restrictions AUTH_LDAP_REQUIRE_GROUP = 'cn=enabled,ou=django,ou=groups,dc=my_domain,dc=com' AUTH_LDAP_DENY_GROUP = 'cn=disabled,ou=django,ou=groups,dc=my_domain,dc=com' # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "username": "uid", "passsword": "userPassword" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': 'cn=active,ou=django,ou=groups,dc=my_domain,dc=com', 'is_staff': 'cn=staff,ou=django,ou=groups,dc=my_domain,dc=com', 'is_superuser': 'cn=superuser,ou=django,ou=groups,dc=my_domain,dc=com', } # This is the default, but I like to be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache distinguised names and group memberships for an hour to minimize # LDAP traffic. AUTH_LDAP_CACHE_TIMEOUT = 3600 # Keep ModelBackend around for per-user … -
How do to add a single subdomain to Django app
I am trying to add a subdomain such as "shop.example.com" to an existing Django app that is hosted on "example.com" I keep finding https://django-subdomains.readthedocs.io/en/latest/ as the only option but this causes errors on the main app when I run the server. It also seems more than I need. I am trying to connect this shop.example.com to a shopify site. Thanks -
how to fill foreign key column in one of the Django model/table with the value of parent table?
I have a Django model/SQL table, which is static and will always have 4 rows with one column (ID) as primary key, like below Status_ID Status 1 active 2 inactive 3 pending 4 deprecated I have another Django model in which records will be inserted on daily basis and have foreign key (Status_ID) of above table and has to be inserted with status_ID as 2, always. ID My_code status_ID Location 1 some code 2 India 2 other code 2 USA I have below code which populates the second table T1= Table2(My_code='some code', Location='India') T1.save() what should be the piece of line to populate second table's status_ID column with 2, always ? -
Understanding django ModelForm submission
I'm trying to create comment system in a blog. This is the view section. def post_content(request,post_slug): post= Post.objects.get(slug=post_slug) new_comment=None #get all comments that are currently active to show in the post comments= post.comments.filter(active=True) if request.method=='POST': comment_form= CommentForm(request.POST) if comment_form.is_valid(): # saving a ModelForm creates an object of the corresponding model. new_comment= comment_form.save(commit=False) new_comment.post=post new_comment.save() else: comment_form=CommentForm() return render(request,'blog/post_content.html',{'post':post,'comments':comments,'comment_form':comment_form}) There's no comment yet. Now, what I don't understand is when I post a comment and then page reloads, I immediately see the comment (which I shouldn't be). By my understanding, this should be the flow- When the page reloads(after submitting comment), it goes to views and retrieves active comments first (which should be empty because none has been saved yet, has it?) It is saved only when the if condition is satisfied and form is valid , which are all below. And I haven't retrieved comments after saving. But still, the 'comments' variable contains the recent comment I made. How is this happening ? What sorcery is this ? Please somebody make it clear for me !! -
Django OTP Example unable to use looking for example or Templet
I'm looking for Django OTP https://django-otp-official.readthedocs.io/en/latest/index.html example or templet where i can understand it. -
Creating a unique dictionary key
The problem I am making an e-commerce in Django and the user can pick multiple items before adding them to the cart, I'm using the timestamp as an object id in the user's cart when add to cart button clicked. When add to cart button clicked I have a dict of {"item_id":"qty"} creating the cart object goes like {"timestamp":"item_id;qty"} the timestamp serves as an unique id so i can give id to the rows of the cart if they need to be deleted, if so sends the id of the element of the cart in the back-end and deletes the same element from the user's cart object The timestamp is not unique... The process is too fast that the timestamp stays the same and it does not make different keys any advice to have a different timestamp would be appreciated . -
How could I create a postgresql extension in django test setup
I'm using django 1.11 and PostgreSQL 9.6. When I want to test an app, I find that the django test will create and use a test database.This test database doesn't have an extension that need to be created first. So how to create an extension after create the test database and before create the test data? -
Django Models Storing Multiple sensor floating points into one field
Currently going through Django training this is a beginner question. The extent of what I know about designing models below name=models.CharField(max_length=255) status_text=CharField(max_length=255) name:'bob' status:'status' My Question How do I update the fields for this model name: 'bob' omg:'['3.5', '10.2', '15.4', '13.2'] name=models.Charfield(max_length=255) status:models.Charfield(max_length=255) Is it still the same same type of model. Correct Json Outcome { name:"kehlin", status:[3.76, 8.8, 9.9, 10.3, 14.5, 18.0] }