Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unhandle exceptions - Handler for that?
As per django's documentation - if there are any unhandled exceptions django sends an email to ADMINS email list : https://docs.djangoproject.com/en/2.1/howto/error-reporting/ For any unhandled exceptions - is there any way one can add a wrapper around it ? The goal is : instead of sending an email - i want to handle the exception, do some parsing, and add it into the DB and/or log the info. If folks can nudge me in the right direction, would really appreciate it. -
building database with django
i'm building database but i have problem, when i click on on of record hyperlink on database it run this on html: {% for metadata in genome.metadata_set.all %} <li>{{metadata.location}} - {{metadata.composition}}</li> {% endfor %} and display the data from all records at once ! what should i do to display the data specific for each record separet? -
Django get user permissions from queryset
In my application each user is given access to one of the four groups (I have 4 groups created). I have to check if user has ceritan permissions to access a form. I am obtaining the user from self.request.user and getting the queryset of the corresponding user model. group = self.request.user.groups.all() But if I try to do self.request.user.groups.all().values('permissions') It is printing the permissions in such a way that each of them has a number associated to it. I want to check if there is any way to check if the user has the access to ceritan model based on the queryset I got. I mean is there any method alike has_perm('') to perform the above task. I have searched about it on google and stackoverflow. but could not find the satisfying results. So, is there any way to perform the above operations ?? -
django session timeout on ajax request
We have built Angular frontend dashboard that gets the backend data from Django application using API calls. It works well for the super admin user. However, for staff user, if I go back and forth between admin interface and frontend dashboard user is logged out. I am guessing this might be happening due to a session timeout. When I checked "django_session" table it was empty. Any help in solving this is appreciated. -
What are the best django mptt videos?
I have been pretty new to django and have learned the basics of it and have created a blog using it. Due to the project requirement by the client I need to learn django mptt. Can anyone please provide me with online tutorial for django mptt ? -
Django ModelForm fails to save "many to many" records using ModelForm and save_m2m
I am new to Django and using this project to learn it. I am able to save the Journal record but the many to many relationship does not work. This 'create' view displays the correct form including the multi-select box with all of the cryptos listed (from Crypto model). When submitting the form the many-to-many records do not save but the Journal saves fine. I have found a bunch of different answers to this, some are for python 2.7, but this is the simplest method based on the Django documentation. Any help is greatly appreciated. Also, the relationship works fine in the Admin section, so I am thinking it has something to do with the Forms and/or the View & saving. models.py from django.db import models from crypto.models import Crypto as CryptoModel class Journal(models.Model): title = models.CharField(max_length=200, help_text='Journal Title', blank=False, null=False) content = models.TextField(max_length=2000, help_text='Journal Content (HTML OK)', blank=False, null=False) crypto_id = models.ManyToManyField(CryptoModel, blank=True) created = models.DateTimeField(help_text='Created', auto_now_add=True, null=True) def __str__(self): return self.title ## String for representing the Model object, usually name field or title forms.py from django.forms import ModelForm, ModelMultipleChoiceField, widgets from journal.models import Journal as JournalModel from crypto.models import Crypto as CryptoModel class JournalForm(ModelForm): # select multiple items … -
How to update a model record in Django-Rest
I want to make a Survey Api for a school with the name of the teachers with Dango-Rest-Framework. I want to create a way so users can post the name of the teacher (or the id of the teacher in Teacher model) and automatically add one point to that teacher's point field. Here is my Teacher Model class: class Teacher(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True,null=True) voting = models.IntegerField(default=0) and views.py: class TeachersViewSet(viewsets.ModelViewSet): queryset = models.Teachers.objects.all() serializer_class = serializers.TeachersSerializer authentication_classes = (TokenAuthentication,) so what i want is that on the frontend users can call the api and tell that add 1 point the this teacher's voting field(they don't need to metion the number 1. because the api always has to add 1 point for each request).Do I have to create a new Viewset? Honestly I don't know where to start; so any help would be appreciated. -
Get current page number in ListView
How does one get the Paginator info in a class based view? I'm want to call a function from within get_context_data and I need to pass the current page and the last page. views.py: from django.views.generic import ListView from django.core.paginator import Paginator from .utils import pageList class PeopleView(ListView): model = People paginate_by = 5 context_object_name = 'people' def get_context_date(self, *args, **kwargs): context = super(People, self).get_context_data(*args, **kwargs) context['page-list'] = pageList(<current_page>, <last_page>) return context -
Getting data from select tag
<select class="tag" name="Tag" > <option value="1">Option-1</option> <option value="2">Option-2</option> <option value="3">Option-3</option> </select> Here is the code i'm using in a form, I'm a beginner and i have no idea how to get the value of selected option.I'm using flask as backend. Would you please help me with it? Please explain for both cases: 1. Getting the value after form submit 2. Getting the value just after selection (In order to add content to the page based on the selection) -
How to find where query is triggered [Django]
How can I profile a query and find where it is triggered to optimize it? I'm trying to use django toolbar but it doesn't show which function is triggering the query so I don't know where to fix. -
How to show product options on the cart page
Question took from the django-oscar mail list. I want to show product option on the cart page how can i do that. -
Why is LOGGING in my Django settings.py ignored?
I'm trying to set up logging in my Django 2.1 app, but I can't get INFO logs to display. ERROR and WARNING show, but never INFO. I added a custom LOGGING set in my settings.py, but it doesn't seem to affect the actual logging. I've tried changing the levels, changing the formatters, turning on disable_existing_loggers. I'm pretty certain that Django just ignores LOGGING, but https://docs.djangoproject.com/en/2.1/topics/logging/#configuring-logging and everywhere I look seems to indicate otherwise. What do do?! DETAILS: I'm running this in Heroku with gunicorn, but also run via python manage.py runserver and it acts the same. In my ./api/v1/serializers.py and ./users/models.py I've added logging like this: import logging logger = logging.getLogger(__name__) ... ... ... logger.info('Test log INFO') logger.warning('Test log WARNING') logger.error('Test log ERROR') My settings are at ./amp/settings.py and have this: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d: %(message)s', }, 'simple': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'verbose', 'filters': [], }, 'file': { 'class': 'logging.FileHandler', 'level': 'DEBUG', 'filename': '/tmp/amp-server/debug.log', 'formatter': 'verbose', }, }, 'loggers': { '': { 'level': 'INFO', 'propagate': True, 'handlers': ['console', 'file'], 'filters': [], }, 'django.request': { … -
Issue while doing migrations to Oracle Database using Django
I am building a Django app and it has several apps. It is working fine with SQLite database as a backend. When I am trying to migrate the backend to Oracle using "manage.py migrate", I am getting below error django.db.utils.DatabaseError: ORA-01950: no privileges on tablespace 'XXXXXX' When I checked my User privileges in the database, it has privileges to create tables, views etc. I tried to execute "manage.py sqlmigrate" and go through the queries that Django is going to execute on the database and found out that they are "create table" and "add constraints queries". Is there a way in Django to find out which query is getting failed or raising that ORA-01950 error? -
Image is not showing in django template but other tag is working
I am trying to show up my image in django template. But the image is not showing. There is a headline tag which is working fine. I don't know where I am stuck. I searched it here and got a lot of solution, but none of this are not solving my issue. Here is my views.py: enter image description here Here is my urls.py and my images are in the media directory enter image description here And this is home.html: enter image description here Please help me to fix my problem. -
Custom faker provider for usage with factory boy and pytest
I am attempting to add some custom faker provider to use with factory boy and pytest. Right now, I put the provider in faker_providers/foo.py/Provider In my factories.py file, I have to import foo.py and then register by running: factory.Faker.add_provider(foo.Provider) I am thinking of using pytest_sessionstart(session) to auto register all the custom provider under faker_providers. Is there a way to do that? Any suggestions for other ways to organize and register custom providers would also be appreciated -
Serving robots.txt with cache in Django,
So currently I'm serving my robots file with a view and I was wondering how could I server the file with cache. My url looks like this. url(r'^robots.txt/?$', 'robots_txt', name='robots_txt') And my view is: def robots_txt(request): store_url = request.subdomain store = something.get_store(request.context, store_url) if store.robots_txt: robots = store.robots_txt else: robots = dsetting('ROBOTS_DEFAULT_TEXT').replace('<br />', '\n') return HttpResponse(robots, content_type="text/plain") What is does is that when the robots.txt is requested is checks if theres a file in the database and if there is it returns it but if there's not it send a default file. How could check first if there's a file in cache if not do what I'm already doing? -
Django auto_now_add=True giving incorrect time
I would like the current time to be recorded automatically when a record is created in my Django database. In my model I am using: dateTime = models.DateTimeField(auto_now_add=True) From my understanding this automatically stamps the time considering the correct time zone. Instead however, this is outputting a time that is 5 hours ahead of my local time. So to try and debug this, I ran this function in my view and printed the output: from django.utils import timezone timeNow = timezone.localtime(timezone.now()) timeNow will output the correct time. So I changed my model to: def get_time(): return timezone.localtime(timezone.now()) dateTime = models.DateTimeField(default = get_time) This still results in the same incorrect time stamp. I also changed the timezone in my settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Canada/Central' USE_I18N = True USE_L10N = True USE_TZ = True Any ideas what I am missing? -
Return all objects relationships recursive
How i can return all relationships on recursive table on django Structure(model): class Category(models.Model): name = models.CharField(max_length=100) details = models.CharField(max_length=100) state = models.IntegerField(default=1,choices=estado_choices,) parent = models.ForeignKey('self', blank=True, null=True, related_name='category', db_index=False) I would like return like this on template: _______________________________________________ # |Category |name |description| ________________________________________________ 1 | Principal |Example |example 3 | 2 | Subprincipal |subprincipal |example 3 | 3 | Subprincipal 2 |subprincipal 2| example3 i dont know how return this relationship.. please someone idea..!! -
Client-side javascript file not updating in some browser tabs on refreshing, but fine in new ones
I am making a full stack application using Django. I have some client side Javascript written in a file called logic.js. I noticed that sometime when I make changes in the logic.js file and then hit refresh in the browser, the browser's logic.js file doesn't change. However if I open the site in another window, it get the updated logic.js file. I am perplexed by this behaviour of my browser (if it a browser problem). Why is this happening? -
Django: The requested URL /index.html was not found on this server
I have deployed my Django project on UWSGI on Apache. I can go to any non-root URL, but cannot go to mydomain.com. I get this error: My URL patterns include the root: url(r'^$', views.TasksView.as_view(), name='index'), Do you know what's going on? Thanks. -
DRF User Update
I know this has been discussed and it's basic but I can't find what is wrong with it. I've pulled up my old projects (which works!) and corresponded to what I did. It never reaches to update in serializer, and I'm at lost why. I dont know what else I'm missing. Error: "{"last_name":["This field may not be null."],"pass… null."],"email":["This field may not be null."]}", status: 400 frontend patch('api/getprofile') django/DRF serializer: class UserSerializer(serializers.ModelSerializer): first_name = serializers.CharField() last_name = serializers.CharField() email = serializers.EmailField() password = serializers.CharField(style={'input_type': 'password'}) class Meta: model = User fields = '__all__' def create(self, validated_data): user = User.objects.create( username=validated_data.get('username'), email=validated_data.get('email'), password=validated_data.get('password') ) user.set_password(validated_data.get('password')) user.save() return user def update(self, instance, validated_data): #print instance <-- if never gets here... is update not update for key, value in validated_data.items(): if value: print value setattr(instance, key, value) instance.save() return instance views.py class UserRetrieveUpdateAPIView(generics.RetrieveUpdateAPIView): serializer_class = UserSerializer permission_classes = (IsAuthenticated, ) queryset = User.objects.all() def get_object(self): return self.request.user def update(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) instance = serializer.instance return Response(UserSerializer(instance=instance).data, status=status.HTTP_200_OK) -
how to get a field name knowing id number in django
I have the following query set to get the subcategory name knowing the id number: query_sc = Post_Sub_Category.objects.filter(id='1').values('sub_category_name') it gave me the following output: {'sub_category_name': 'car'} how can I get only the car. i mean I need the output to be car only 'the value not the dictionary. -
How can I get GUNICORN to use Python3?
I'm trying to configure Gunicorn with Supervisord on Ubuntu. When /etc/supervisor/conf.d/myproject.conf gets run, I receive this error message Traceback (most recent call last): File "/home/chris/django-apps/env/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/chris/django-apps/env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_proc$ self.load_wsgi() File "/home/chris/django-apps/env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/chris/django-apps/env/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/chris/django-apps/env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/chris/django-apps/env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/chris/django-apps/env/local/lib/python2.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/chris/django-apps/nibbleblog/nibbleblog/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi I'm pretty sure I receive this error because its trying to run Python 2.7 and my codebase is in Python 3. How can I get gunicorn to run python3 through supervisor? I can run the server fine in my venv with python3 but when I run it through supervisor outside my venv, this is where I am having trouble. Any ideas how to fix this? Any help is much appreciated! Thank you! -
Django ORM Tree model structure
I currently have 4 models AbstractComponent, Component1, Component2 and Component3. The Component models inherit from AbstractComponent and have their own specific fields as shown below: class AbstractComponent(BaseModel): part_number = models.CharField(max_length=512) manufacturer = models.CharField(max_length=512) class Component1(AbstractComponent): type = models.CharField(max_length=512) class Component2(AbstractComponent): lifecycle_hours = models.FloatField(default=0) class Component3(AbstractComponent): hardware_version = SemverField(blank=True, null=True) I want to be able to create a hierarchal structure wherein any of the components can be the parent of another component. Basically any component can be composed of multiple components and in order to model this, I want to have a field on the components which lets me know its parent component if it has one. What's the best way to implement this? I know Django has GenericForeignKey and GenericRelation for relating multiple models but I couldn't figure out how to use them for my specific use case. I would like to be able to use the django DRF to add/remove a parent for a component as well. -
Creating ManyToMany instances at the same time in Django
I've got data for all of the countries on a json that looks like this: { "name":"Afghanistan", "topLevelDomain":[ ".af" ], "alpha2Code":"AF", "alpha3Code":"AFG", "callingCodes":[ "93" ], "capital":"Kabul", "altSpellings":[ "AF", "Afġānistān" ], "region":"Asia", "subregion":"Southern Asia", "population":27657145, "latlng":[ 33.0, 65.0 ], "demonym":"Afghan", "area":652230.0, "gini":27.8, "timezones":[ "UTC+04:30" ], "borders":[ "IRN", "PAK", "TKM", "UZB", "TJK", "CHN" ], "nativeName":"افغانستان", "numericCode":"004", "currencies":[ { "code":"AFN", "name":"Afghan afghani", "symbol":"؋" } ], "languages":[ { "iso639_1":"ps", "iso639_2":"pus", "name":"Pashto", "nativeName":"پښتو" }, { "iso639_1":"uz", "iso639_2":"uzb", "name":"Uzbek", "nativeName":"Oʻzbek" }, { "iso639_1":"tk", "iso639_2":"tuk", "name":"Turkmen", "nativeName":"Türkmen" } ], "translations":{ "de":"Afghanistan", "es":"Afganistán", "fr":"Afghanistan", "ja":"アフガニスタン", "it":"Afghanistan", "br":"Afeganistão", "pt":"Afeganistão", "nl":"Afghanistan", "hr":"Afganistan", "fa":"افغانستان" }, "regionalBlocs":[ { "acronym":"SAARC", "name":"South Asian Association for Regional Cooperation", "otherAcronyms":[ ], "otherNames":[ ] } ], "cioc":"AFG" } I'm trying to make models to represent all of this information. I have one Country model, and then a model for language, translation, regional blocks, and currency that are linked to Country through a ManyToManyField(). I'm trying to add all of the countries at once to my database using the Django shell. Inside I'm running this command: import json from api.models import Country from api.models import currencies, languages, translations, regionalBlocs with open('data.json') as f: data_json = json.load(f) for data in data_json: data = Country(name=data['name'], topLevelDomain=data['topLevelDomain'], callingCodes=data['callingCodes'], capital=data['capital'], altSpellings=data['altSpellings'], region=data['region'], …