Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Prevent form resubmission with user refresh and need to submit data to webpage using Django
I've seen this question a few times and can't find an option that works in my situation. I have a webpage that you can get to via a POST. It requires an '' be sent to the server. The webpage has a form for the user to fill out. When they submit the form, I need the user to return to same page. I need to prevent user 'refresh' from resubmitting the form. Most common solution I have found is: return HttpResponseRedirect('/<web_page/') I have tried this and adding kargs to the function parameters, but it doesn't seem to work. -
Angular django rest framework integration
How to serve angular using Django server? I don't want to host two different server for angular and Django. How to do it with a single django server? -
How can I show specific data un my Django form?
I'm a begginner at Django and I'm making an app for lending books and now I'm trying to make a Form using these models: In my app Books Class CopyB(models.Model): Copy= models.Autofield(primary key=True) Condition= models.Charfield(max_lenght=20) IdBook=models.ForeignKey(Book, blank= false, null= false ,on_delete= models.CASCADE) Also in my app Users Class User(models.Model): Myid= models.Charfield(primary_key=True, max_length=20) Name= models.Charfield(max_length=20) Lastname= models.Charfield(max_length=20) And in my app loans From apps.books.models import CopyB From apps.users.models import User Class loan(models.Model): IdLoan= models.Autofield(primary_key=True) IdB= models.ForeignKey(CopyB,blank=False, null=False) IdU= models.ForeignKey(User,blank=False, null=False) What I want to do is making a Form from the model loan and on that form on the field IdB I only want to show in the select input just Books in the model CopyB that in the field Condition is equal to available But I don't know how to make it! Thanks in advance -
SMTPAuthenticationError - 535, b'5.7.8 Username and Password not accepted. - sending email from docker
I'm trying to send an e-mail from django app in docker on Ubuntu and I'm receiving following message: Request Method: GET Request URL: https://localhost:8001/accounts/mail/ Django Version: 2.2.5 Exception Type: SMTPAuthenticationError Exception Value: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials x76sm1225174ljb.81 - gsmtp') Exception Location: /usr/local/lib/python3.7/smtplib.py in auth, line 642 Python Executable: /usr/local/bin/python Python Version: 3.7.4 There is no problem to send an e-mail outside docker. I tried every step from Google troubleshooting steps. Currently I have 2-Step verification which works for local app but still doesn't for docker one. I don't necessarily need Google SMTP (I have an account there), but what I what to achive is to send e-mail with activation link to user after registration for django application. -
ModuleNotFoundError: No module named 'rest-framework' with virtualenv and python3.7.4
I'm going though this tutorial: https://github.com/encode/django-rest-framework I make all of the changes, but when I get to the runserver part, I keep getting ModuleNotFoundError: No module named 'rest-framework' error.. | => ./manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "/Volumes/thunderb/attic/Projects/VS/maione/env/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
How to fix "DLL load failed" error while running Django + Celery with mod_wsgi?
I am trying to run a Django application on a Windows server using the Apache Web Server with mod_wsgi. I am using celery to run some asynchronous tasks and the application runs correctly in localhost, but I get the following error when running on the webserver: [Wed Sep 18 14:12:48.787255 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] mod_wsgi (pid=9608): Target WSGI script 'C:/Apache24/htdocs/webapp/djmaccherone/wsgi.py' cannot be loaded as Python module. [Wed Sep 18 14:12:48.787255 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] mod_wsgi (pid=9608): Exception occurred processing WSGI script 'C:/Apache24/htdocs/webapp/djmaccherone/wsgi.py'. [Wed Sep 18 14:12:48.792143 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] Traceback (most recent call last):\r [Wed Sep 18 14:12:48.792143 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] File "C:/Apache24/htdocs/webapp/djmaccherone/wsgi.py", line 35, in <module>\r [Wed Sep 18 14:12:48.792143 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] import djcelery\r [Wed Sep 18 14:12:48.792143 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] File "C:\\virtualenvs\\webapp\\Lib\\site-packages\\djcelery\\__init__.py", line 34, in <module>\r [Wed Sep 18 14:12:48.792143 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] from celery import current_app as celery # noqa\r [Wed Sep 18 14:12:48.792143 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] File "C:\\virtualenvs\\webapp\\Lib\\site-packages\\celery\\local.py", line 509, in __getattr__\r [Wed Sep 18 14:12:48.792143 2019] [wsgi:error] [pid 9608:tid 1352] [client 35.xxx.xxx.xx:58389] module = … -
Calling Class Based View (POST) method without going through url.py
we are developing an application backend API end points using Django Rest Framework with class based view approach. Now have an end point like BASE_URL/api/v1/users/posts/ , when called with post method all it does is saves (posts data, ex: {"post_id" : "1", "post_content" : "some_text" ,"posted_username": "user_name"}) into back end database. The above end point will be processed by application urls.py file and will redirect to corresponding view to save the data. Now I want co call the corresponding end point view class post method but not through regular end point [ requests.post(url,data,headers) ], need to invoke this class post method from another python file ( within the same application ), without going through urls.py. All I want to eliminate is network call. Please don't suggest saving directly to database by opening a connection to database, no I want to save data through REST API end point only (class view post method only) but not actually calling end point. Kindly suggest a way to do this. Many Thanks In advance. -
Configure Nginx and Django for Byte Range Request
I am building a web API using Django and Nginx that needs to support Byte-Range requests. Currently, when making a request such as: curl --header "Content-Type: application/json" --header "Authorization: Token 8f25cd3bb5b43a5277f4237b1d1db0273dbe8f6a" --request POST http://myurl/download/ --header "Range: bytes=0-50" -v my Django view (the MyFileAPI class) is called, the user is authenticated, and the correct file path (/code/web/myapp/user_id/user_info.pbf) is fetched. However, the first 50 bytes of the file are not returned. Instead I simply see the error: <html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.15.8</center> </body> </html> How do I configure Nginx to allow redirects to my file? default.conf server { listen 80; server_name localhost; charset utf-8; client_max_body_size 10M; location /static/ { alias /django_static/; } location / { include uwsgi_params; uwsgi_pass web:8000; add_header accept_ranges bytes; } location /myapp { root /code/web; add_header accept_ranges bytes; internal; } } nginx.conf user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } views.py class MyFileAPI(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: user = request.user my_file = … -
Branch is being created without add
Im wanting to create a fresh branch for my repository since I'm having previous problems. However nothing I'm trying is working. When I run (venv) C:\..\..\PycharmProjects\WebP1\DEMOPROJECT>git ls-tree --name-only hope on creation of a new branch, I get .gitignore DEMOAPP DEMOPROJECT __init__.py __pycache__ db.sqlite3 manage.py media static This isnt what i want as i want gitignore to ignore this *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 media I have tried --orphan branch but it seems to always take me back to a bad commit I don't want anymore. DEMOPROJECT folder is also being made a submodular for some reason which I don't want to happen. How can i fix this please? Is there a certain add I need to do? -
How to handle errors in Django
I want to make my django app as user friendly as possible and I want to handle appropriate errors and have it push out an error message sort of like an alert in javascript. I want to do this when there's no file uploaded. So when the upload button is pressed and nothing have been uploaded there would be an alert message sent out. def upload(request): if "GET" == request.method: return render(request, 'uploadpage/upload.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting a particular sheet by name out of many sheets worksheet = wb['Summary'] # iterating over the rows and # getting value from each cell in row seller_info = [] for cells in worksheet.iter_rows(min_col=2, max_col=2, min_row=1, max_row=5): for cell in cells: seller_info.append(str(cell.value)) return render(request, 'uploadpage/upload.html', {"excel_data": seller_info}) <!DOCTYPE html> <html> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'css/upload.css' %}"> <head> <div id='banner-container'> <div id='banner'> <h1 id='header'>MY APP</h1> <i class="glyphicon glyphicon-cloud" style="font-size:60px;color:lightblue;text-shadow:2px 2px 4px #000000;"></i> </div> <div> <body> <div id='upload-container' > <span><h1>Upload File !</h1></span> <span><h2>Upload Here</h2></span> <form method="post" enctype="multipart/form-data"> <div id='input'> {% csrf_token %} <input type="file" name="excel_file"> <div id='btn'><button type="submit">Upload File</button> </div> </form> <div> </div> </body> {{ …