Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django validation - avoiding multiple full_cleans()
I am new to Django, and after reading a bunch of docs/guides and googling stuff, I am still a little confused about the best practice way to do validation. It seems like the best place to do validation is on the Model level, to ensure that it is always applied, regardless of where the data comes from (e.g. Django front-end, some JS server, API, etc). If I override the Model save() method in my base model to call full_clean(), that seems like the best way to guarantee that the saved data is always good. However, I am running into various issues with this in my project. The obvious one is that Django's ModelForms call Model full_clean() already, so I end up calling it twice in this case. On top of that, there are other complications, for example: if there is a Model level method that saves a compound Model that has another Model inside it (e.g. Address inside some Account), I can't just save Address, because Account might fail validation afterwards. So I really need to validate both Models first, and only then save them (keep it transactional). But then, I need to call full_clean() to validate, and it's called … -
How can i fix this Django admin issue? Django admin Site matching query does not exist
My admin does not work. I alredy try it a couple of hours. The miration works: C:\Users\sebas\AI_MachineLearning\Django_Projekt\pythonprojects\cookbook>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, recipes, sessions, sites Running migrations: No migrations to apply. C:\Users\sebas\AI_MachineLearning\Django_Projekt\pythonprojects\cookbook> The Superuser is created. Runserver works: C:\Users\sebas\AI_MachineLearning\Django_Projekt\pythonprojects\cookbook>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 18, 2019 - 22:06:57 Django version 2.2.5, using settings 'cookbook.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. If I try the urls ../admin: http://dpaste.com/069QF7H DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 2.2.5 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: C:\Users\sebas.conda\envs\pythonDjango\lib\site-packages\django\db\models\query.py in get, line 408 Python Executable: C:\Users\sebas.conda\envs\pythonDjango\python.exe Python Version: 3.6.7 Python Path: ['C:\Users\sebas\AI_MachineLearning\Django_Projekt\pythonprojects\cookbook', 'C:\Users\sebas\.conda\envs\pythonDjango\python36.zip', 'C:\Users\sebas\.conda\envs\pythonDjango\DLLs', 'C:\Users\sebas\.conda\envs\pythonDjango\lib', 'C:\Users\sebas\.conda\envs\pythonDjango', 'C:\Users\sebas\.conda\envs\pythonDjango\lib\site-packages'] Server time: Mi, 18 Sep 2019 21:55:32 +0200 Envoi -
urls files started to look like scratch files with no colored fonts in Pycharm
My problems started by changing the shape of th all urls files when I use pycharm only, then I modified some models but the site does not work properly, and unable to read the models members. I tried to start a new project all the new rls.py converted to scratch files I do not the meaning of this error:- django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Can I load a fixture with the DateField set to null?
I'm have some Datefields I would like to keep null or blank when I load a fixture. Is there a way to keep them null or blank without putting some default value? In the model, I have already set null=True, blank=True. -
npm can't resolve babel_loader when running React with Django
I am following this tutorial for integration React with Django. I have gone through all the steps, but when I run npm run dev, I get this error: > AttractoraProject@1.0.0 dev /Users/hugovillalobos/Documents/Code/AttractoraProject > webpack --mode development ./Attractora/frontend/src/index.js --output ./Attractora/frontend/static/frontend/main.js Insufficient number of arguments or no entry found. Alternatively, run 'webpack(-cli) --help' for usage info. Hash: cf46d3c1f598793a6a6e Version: webpack 4.40.2 Time: 111ms Built at: 09/18/2019 2:05:08 PM ERROR in Entry module not found: Error: Can't resolve 'babel_loader' in '/Users/hugovillalobos/Documents/Code/AttractoraPro ject' npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! AttractoraProject@1.0.0 dev: `webpack --mode development ./Attractora/frontend/src/index.js --output ./Attractora/ frontend/static/frontend/main.js` npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the AttractoraProject@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/hugovillalobos/.npm/_logs/2019-09-18T19_05_08_809Z-debug.log I ran this command to install babel, so I don't know what I am missing: npm i @babel/core babel-loader @babel/preset-env @babel/preset-react babel-plugin-transform-class-properties --save-dev -
How do I model Django timestamps if I must import old data initially?
I have some basic timestamp fields that should end up as auto_now_add: class Example(models.Model): created = models.DateTimeField(auto_now_add=True) However, I need to seed the initial Django project database from an external database where these creation timestamps are already populated for existing data. I imagine I may need to do the following: Start with created = models.DateTimeField(default=timezone.now) Import old database data Migrate to created = models.DateTimeField(auto_now_add=True) Is this necessary to preserve the old timestamps, or can I start with the desired auto_now_add and import somehow while ignoring this? -
Django: 'weblearn' is not a registered namespace
I am a beginner with Django, and I have been following this tutorial so far - with the small exception of naming the app weblearn instead of polls as done in the tutorial. So far it worked fine, all worked as expected. I am in about the half on the fourth page, and just created the file weblearn/templates/weblearn/results.html, and I double checked that the name polls is not used in any of the code/html. But still, when I navigate to the page http://127.0.0.1:8000/weblearn/1/ as suggested, I get an error In template /Users/alex/Coding/Django/learnit/weblearn/templates/weblearn/detail.html, error at line 5 'weblearn' is not a registered namespace What can I do to debug this error? I have not the slightest idea what the error could mean... detail.html: <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'weblearn:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form> -
How to fix this error when running celery task
When I try to run this code it throws an error, I want to run task_number_one and print_test as a periodic task but it throws the same error for both. from celery.task import periodic_task from celery.schedules import crontab from celery import task @task() def task_number_one(): print("Celery Task Working...") @periodic_task(run_every=crontab(minute='10', hour='6,8,9,10,11,12')) def print_test(): print(1) task_number_one.delay() I get this below error [2019-09-18 17:21:17,093: ERROR/MainProcess] Received unregistered task of type 'page.tasks.task_number_one'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) Traceback (most recent call last): File "/home/naanal/venv/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 559, in on_task_received strategy = strategies[type_] KeyError: 'page.tasks.task_number_one' -
issue in printing dictionary value in django
I have two list li_title and a_href as below. i have combine it in to dictionary but it not print any thing in template file. This is the code in view(value are appended in list with same length) param = {li_title[i] : a_href[i] for i in range(len(li_title))} return render(request, 'index.html', param) This is the code in index.html. {%for i,j in param.items% {{j}} {% endfor %} -
403 Client Error: Forbidden for url: https://api.twitter.com/oauth/request_token - can't sign in with Twitter
I'm trying to add twitter sign in option to my python application and I'm getting following error from web server: GET /social-auth/login/twitter/ HTTP/1.1" 500 103190 403 Client Error: Forbidden for url: https://api.twitter.com/oauth/request_token I work on dev environment django + unicorn with SSL on localhost. I've checked following instruction on Twitter callback url's guide: Don’t use localhost as a callback URL Instead of using localhost, please use a custom host locally or http(s)://127.0.0.1. My callback URL: https://127.0.0.1:8000/social-auth/complete/twitter/ Is it possible to make it work without hosting real domain? -
how to get absolute object url when using through
i'm trying to get the absolute url when a new post will create , this is a common way to do that : df get_absolute_url(self) return reverse('url_name' , kwargs={'id':self.id}) but this doesnt work i use through (subquery) in django class Order(models.Model): ... id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') pass def get_absolute_url(self): return ('print' , {'id':self.id}) class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE , null=True) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) pass urls.py path('print/<int:id>/' , PrintDetailView.as_view() , name='print'), i used function based view -
Django- Username is getting written as User_admin.User.None, How to fix it?
I have made a website where users can post and other users can give like or if they want they can remove their like. I want to write down in the website who has given like in that post. So I have tried in the following way but it is printing out user_admin.User.Nonein the html file. In the product models.py class Item_Product(models.Model): title = models.CharField(max_length=100) pub_date = models.DateTimeField() body = models.CharField(max_length=1000) image = models.ImageField(upload_to = user_directory_path_for_item_product) likes = models.PositiveIntegerField(default=1) product_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def pub_date_pretty(self): return self.pub_date.strftime("%b %e %Y") class Vote(models.Model): voter = models.ManyToManyField(User, blank=True) item_product = models.OneToOneField(Item_Product, on_delete=models.CASCADE) def __str__(self): return "Item ID: "+str(self.item_product.id) + " Item Name:"+str(self.item_product) This is my views.py def item(request, item_id): obj = get_object_or_404(Item_Product, pk=item_id) voter_obj = get_object_or_404(Vote, item_product_id=item_id) return render(request, 'item.html', {'item':obj, 'voter':voter_obj}) This is my html {% extends 'navbar-footer.html'%} {% block content %} <h1>{{button}}</h1> <h4>This is item number {{item.id}}</h4> <h4>{{ item.title }}</h4> <h4>{{ item.body }}</h4> <button type="button" class="btn {{button}}" onclick="javascript:{document.getElementById('increase_like').submit()}">Like {{item.likes}}</button> <form action="{%url 'increase_like' item.id%}" method="POST" id='increase_like' > {% csrf_token %} <input type="hidden" name="" id=""> </form> <img src="{{item.image.url}}" alt=""> <h1>{{voter.voter}}</h1> {% endblock %} When I give like as different users it is showing like this rather than showing the … -
Searching a model's records base on an attribute of another model which has related to this one?
I have two model classes class A and class B. The second class is related to the first using a foreign key. I want to be able to search class A objects by an attribute of class B (inside django admin): class A(models.Model): a1 = models.CharField() a2 = models.CharField() class B(models.Model): fk = models.ForeignKey(A, on_delete=models.CASCADE,) b1 = models.CharField() class AAdmin(admin.ModelAdmin): search_fields = ['a1', 'b1'] admin.site.register(A, AAdmin) -
Allow both authenticated and unauthenticated users access a django rest view with token authentication decorator
I am working with django rest, I however have an issue in one of my views because, i want to allow both authenticated users and unauthenticated users access the view then check if the user is authenticated then there are some special events to be done by the celery tasks, however, whenever i add the decorator for the authentication_classes, unauthenticated users can no longer visit the page even after setting the permission_classes to allow all simply my code is here, hope someone can know what i need to add or remove @api_view(['GET']) @permission_classes([AllowAny]) @authentication_classes([TokenAuthentication]) def item_details(request, pk): if request.user.is_authenticated: #here some tasks the main issue is that it seams that TokenAuthentication just nullify AllowAny and takes over the checking of the permisssion class or is there something am doing wrong? -
django.db.utils.OperationalError: (2059, <NULL>)
So, i trying to swap standart SQLite DB on MySql. When i changed DATABASE settings in project's settings.py, it gives me an error: django.db.utils.OperationalError: (2059, <NULL>) My DATABASE settings looks like this: DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql', 'NAME': 'django_app', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '3306', } } I spend whole day to search some information about this error, but found nothing. -
Extract values from Django <QuerySet> in Python 3
I have some python code: UnitTestCollection.objects.filter(unit__type=unit_type) which outputs data in format: <QuerySet [<UnitTestCollection: VALUE1>, <UnitTestCollection: VALUE2>... How can I extract a list of the values only i.e. [VALUE1, VALUE2....] -
django logging, loggers key values
I try to get logs from Django and celery but I want to know the syntax can I have a different name for 'django.request','django','celery'? How to get all level of logs from logger? what is propagate? 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'ERROR', 'propagate': True, }, 'django': { 'handlers': ['console'], 'level': 'ERROR', 'propagate': True, }, 'celery': { 'handlers': ['celery_logstash'], 'level': 'ERROR', 'propagate': True, }, } -
Django: How to save a ID in a ManyToMany Relation in a form?
i am testing nesting different models and how to populate them via a form in django. (using Django 2.2 and PostgreSQL) These are my models... models.py class Guest(models.Model): name = models.CharField(max_length=40) meal = models.ManyToManyField('Meal') def __str__(self): return self.name class Meal(models.Model): dish = models.ForeignKey('Dish', null=True, blank=False, on_delete=models.SET_NULL) table = models.PositiveIntegerField(null=False, blank=False) def __str__(self): return "Dish:" "{}" "/ Table:" "{}".format(self.dish, self.table) class Dish(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name views.py class GuestCreateView(CreateView): model = Guest template_name ="testa/create_guest.html" form_class = GuestForm success_url = reverse_lazy('testa:testa_home') def form_valid(self, form): return super().form_valid(form) forms.py class GuestForm(forms.ModelForm): dish = forms.ModelChoiceField(queryset=None) # --- Input for meal.table table_input = forms.IntegerField(widget=forms.NumberInput) class Meta: model = Guest fields = [ 'name', 'dish', 'table_input' ] # --- Dish names from dish.model def __init__(self, *args, **kwargs): super(GuestForm, self).__init__(*args, **kwargs) self.fields['dish'].queryset = Dish.objects.all() def save(self): # --- save first Meal.model data = self.cleaned_data mealData = Meal(table=data['table_input'], dish=data['dish']) mealData.save() # --- take the meal.pk for guest.meal_id meal_id = mealData.id # --- save Guest.model guestData = Guest(name=data['name'], meal_id=data['meal_id']) guestData.save() PROBLEM Dish.model is a list of dishes (Pizza, Hot Dog, Cake...) Meal.model saves the related dish and also adds a Table Number Guest.model relates to a dish and the table number and also adds a guest name. … -
How do you write all user emails from a Django user database to a text file?
Using shell commands, what is the quickest way to export all user email addresses from a Django database into a text document? -
Django superuser doesn't have permission to delete models
I am working on upgrading a Django website from Django 1.8 to Django 2.2 and have come across a problem when trying to delete an object from the Django admin changelist view. When I try to delete an object, I am shown a screen with the words "Deleting the selected Records would result in deleting related objects, but your account doesn't have permission to delete the following types of objects". The problem is, I am a superuser and should have permission to delete any object I want, or so I thought. I have read a decent amount of documentation on Django upgrades and permissions of superusers, however I haven't stumbled across anything that helps me (I could be missing something though). I have tried creating a new superuser just in case, still the same message occurs though. Anyway, Does anyone have any idea why this could be happening? Note: I can't show any code because I am working for a company and I signed an NDA. Just some help pointing me in the right direction would be appreciated. -
Django admin site does not pick current image url
I am trying to edit the fields of one of my objects in the django admin site, I also have a cloudinary image field in my model. The issue is, anytime I try to make an edit to one of the CharFields of my object,I get the error: value too long for type character varying(100) which I later found out that everytime I finish my edits and I am trying to save, it looks for a new image to replace the current image of my imagefile eventhough I did not touch my imagefile, thus it returns an empty image url string like this: But the current image url works fine and displays when clicked like this: I just want to know if I am doing something wrong, why does it look for a new image url everytime I click save. This is my models.py file: from django.db import models from cloudinary.models import CloudinaryField class profiles(models.Model): firstname = models.CharField(max_length=120, default = 'null') #max_length=120 lastname = models.CharField(max_length=120, default = 'null') gender = models.CharField(max_length=120, default = 'null') dob = models.CharField(max_length=120, default = 'null') callNumber = models.CharField(max_length=120, default = 'null') whatsappNumber = models.CharField(max_length=120, default = 'null') ministry = models.CharField(max_length=120, default = 'null') centre = … -
How can I upload svg file to a django app?
I tried to upload an .svg by the admin site to SQLite (django's default db) and I got the following error: Upload a valid image. The file you uploaded was either not an image or a corrupted image. I can uplad .jpg files and it works properly. class News(models.Model): news_id = models.AutoField(primary_key=True, editable=False) news_title = models.CharField(max_length=150) news_date = models.DateTimeField(auto_now_add=True, editable=False) news_body = models.TextField(max_length=1500) news_img = models.ImageField(upload_to="pictures/%Y/%m/") news_author = models.ManyToManyField(Author) class Meta: ordering: ['news_id'] def __str__(self): return '%s %s %s'%(self.news_id, self.news_title, self.news_date) -
How to get a single object`s with Django ORM
Can I extract all the listing data from the Save model where the Save object has two fields and I want to extract the data of the listing only one field def ViewSaveListing(request): context = {} listings = Save.objects.filter(user=request.user).only('listing') context['listings'] = listings return render(request, 'Main.html',context) This error appears to me when I execute the query: django.core.exceptions.FieldError: Cannot resolve keyword 'price' into field. Choices are: id, listing, listing_id, user, user_id The model: class Listing(models.Model): price = models.BigIntegerField() roomsTotal = models.PositiveSmallIntegerField(null=True) Bathrooms = models.PositiveSmallIntegerField(default=None) class Save(models.Model): listing = models.ForeignKey(Listing, related_name='Save',on_delete=models.CASCADE) -
Server hangs when rtmclient starts
I need to receive messages from slack and save them to the database. I read that this can be done through rtmclient. But when I try to implement this, the server just hangs on this line - Performing system checks. -
How to remove a scheduled settings task from Django Celery Beat?
I am using django celery beat to orchestrate recurring scheduled tasks. The beat scheduler i am using is the django database scheduler. The beat schedule is in my settings file as such: CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'core.tasks.task_number_one', 'schedule': crontab(), }, } This successfully schedules and runs this task every minute, however, when I delete this task from this setting and re-deploy (via elastic beanstalk), the task continues to run. I had to manually delete it via the django admin interface. Why does the beat not reload the schedule? Should i be calling some command to trigger this when i deploy?