Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving default fields in a ManyToMany relationship
User class User(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) username = models.CharField(max_length=60, unique=True) job = models.ManyToManyField(Job, blank=True, related_name="users", default = JobDefault) where JobDefault() returns a string. def JobDefault(): return "Artist" class Job(models.Model): job = models.CharField(max_length=60, null=True, default = JobDefault()) def __str__(self): return self.job So there's a m2m field involving User and Job but I want to set a default "Artist"(which is what JobDefault() returns) as the job if a user does not specify a job. Django seems to have a bug which prevents the setting of initial values of the model every time an instance is created. I tried implementing this by overriding the save method of User: def save(self, *args, **kwargs): if not self.job.all(): self.job.add(JobDefault()) super(User, self).save(*args, **kwargs) but returns an error when I try saving a User object: raise ValueError('"%r" needs to have a value for field "%s" before ' ValueError: "<User: hello@gmail.com>" needs to have a value for field "id" before this many-to-many relationship can be used I also tried using Postsave: @receiver(post_save, sender=User, dispatch_uid='SetDefaultName') def SetDefaultName(self, **kwargs): User = kwargs['instance'] if not User.job.all(): User.job.add(JobDefault) User.save() but returns this error when I try to run any manage.py command: @receiver(post_save, sender=User, dispatch_uid='SetDefaultName') NameError: name 'User' is not defined Is there … -
Django subdomains using django_hosts
I'm getting a NoReverseMatch at / 'ccc' is not a registered namespace when using django_hosts. I've followed tutorials from How to Use django-hosts Library, How to Create Infinite Domains Using Django Hosts, and I'm getting the NoReverseMatch error -
Password is never valid - Django
So I'm trying to build custom login functionality for an API, I'm trying to achieve this using tokens but I'm running into some problems. It always says password not valid so the password valid condition never turns to true for some reason even if the password is valid, Here is my code: class UserTokenHandler(APIView): def get(self, request, format=None): username = request.GET['username'] password = request.GET['password'] user = User.objects.filter(username=username) if user.exists(): if User.objects.get(username=username).password == password: chosen_token = '' for i in range(20): lower_case = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] upper_case = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] random_choice = random.randint(1,3) if random_choice == 1: chosen_token += lower_case[random.randint(0, len(list) -1)] elif random_choice == 2: chosen_token += numbers[random.randint(0, len(list) -1)] elif random_choice == 3: chosen_token += upper_case[random.randint(0, len(list) -1)] token = UserLogin.objects.create(token=chosen_token, user=user) token.save() print(password) print(username) return Response({'Token': chosen_token}) else: print(password) print(username) return Response({'Error':'Invalid Password'}) -
Get the Request Body in DRF API
I am passing a value in my API POST request like this { "reason": "string" } And my view is like this, class UpdateReason(GenericAPIView): permission_classes = [IsAuthenticated] serializer_class = serializers.ReasonSerializer queryset = Food.objects.all() def post(self, request, *args, **kwargs): self.get_serializer().instance = service.update(self.get_object()) return Response({"success": True}) serializer.py class ReasonSerializer(serializers.ModelSerializer): class Meta: model = Food fields = ("id", "reason") read_only_fields = ("id",) In the post, I have to get the value of the reason and pass it to the service. How can I execute this? -
How to ask for audio input directly in website without recording audio , then downloading it and then uploading it in django
I am trying to create a website , which converts speech to text (Python). I need to use that program in a website(html,css,js) but I am not able to figure out how to ask for audio input directly from microphone instead of first recording it , then uploading it -
Django file not found error when the file is there
I am working on a social media app. i have a signal that resizes the post image after upload. signals.py @receiver(post_save, sender=Post) def create_uuid(sender, instance, created, **kwargs): if created: img_dir = instance.media.url img_dir_list = img_dir.split("/") img_ext = img_dir_list[-1].split(".")[0] im = Image.open(img_dir) new_width = 0 for x in range(0, 3): new_width += 200 new_height = int(new_width/image.width * image.height) image = im.resize((new_width, new_height)) image.save(f"{settings.MEDIA_URL}posts/{img}{new_width}x{new_height}.{img_ext}") instance.save() models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) media = models.ImageField(null=False, blank=False, upload_to="posts")) caption = models.CharField(max_length=100, default="", null=True, blank=True) date = models.DateTimeField(default=timezone.now, null=True, blank=True) when i add a post and run the signal. it gives me FileNotFoundError but i can see the file in my media folder. how can i fix this? -
Django for loop in template
I have two datasets: ButikPages = ShopPages.objects.filter(UserID_id=User, Parent_id__isnull=True, IsActive=1, URL=shop_page_slug) SubPages = ShopPages.objects.filter(UserID_id=User, Parent_id__isnull=False, URL=shop_page_slug) In my Template I try to filter these two lists that if one ButikPages Query has SubPages it should a drop down menu if not a link menu. <ul class="navbar-nav"> {% for page in ButikPages %} {% for parentpage in SubPages %} {% if page.IsActive == 1 and parentpage.Parent_id != page.ID %} <li class="nav-item"><a class="nav-link" href="/{{ page.Slug }}/">{{ page.PageTitle }}</a></li> {% else %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">{{ page.PageTitle }}</a> {% if parentpage.Parent_id == page.ID and parentpage.IsActive == 1 %} <ul class="dropdown-menu"> <li><a class="dropdown-item" href="/{{ parentpage.Slug }}/">{{ parentpage.PageTitle }}</a></li> </ul> </li> {% endif %} {% endif %} {% endfor %} {% endfor %} </ul> That works if a Menu just has one entry, but if I have two SubPages it appears two time, which is what I understand because the two for loops. But how can I access the SubPages without the second loop? regards. -
Django bootstrap dropdown button in navbar not working
I've tried other questions with similar topic with many different links to bootstrap but it was not working for me, none of them. Any clues why my dropdown button does not roll down when clicked (also does not when hovered either as this was the case for some people). Thanks for any help. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Bootstrap core CSS --> <link href="https://getbootstrap.com/docs/4.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- Custom styles for this template --> <link href="https://getbootstrap.com/docs/4.2/examples/dashboard/dashboard.css" rel="stylesheet"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <link rel="stylesheet" type="text/css" href="{% static 'styles/stylesheet.css' %}"> <title> Milk - {% block title_block %}Milk Students{% endblock %} </title> </head> <body> <header> <!-- Navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark py-1"> <a class="navbar-brand p-2" href="{% url 'milk_app:home' %}">MilkStudents</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto" > <li class="nav-item"><a class="nav-link" href="{% url 'milk_app:home' %}">Home</a></li> <li class="nav-item "><a class="nav-link" href="{% url 'milk_app:about' %}">About</a></li> <!-- If the user is logged in, either as HOST or TENANT he gets these buttons available --> {% if user.is_authenticated %} … -
Can not save form with CreateView (Django, Python)
I am trying to save form to database but it doesn't work. These are my codes. Views.py class HotelAdCreate(AuthorsAccessMixin,CreateView): model = HotelBookingAd form_class = HotelBookingAdForm template_name = "account/article-create-update.html" def form_valid(self,form): form.save() return super(HotelAdCreate).form_valid(form) Forms.py class HotelBookingAdForm(forms.ModelForm): class Meta: model = HotelBookingAd fields = '__all__' def clean_sales_price(self): sales_price = self.cleaned_data["sales_price"] purchase_price = self.cleaned_data["purchase_price"] if sales_price > purchase_price: raise forms.ValidationError("error.") print("error") return sales_price I've tried different options, but I don't have enough skills to handle this problem. Can anyone help me? -
Is it possible to work with Django on Windows and Reactjs on WSL on the same computer at the same time?
I have set up an environment for Django on my windows machine and I have React and Nodejs on Windows-subsytem-for-Linux. I want to build a pet project using Django for backend and React for front end. Is it possible on develop with these settings or should I install both of them on the same environment before starting? -
How to display data from selected option in django
I have a Django project that display data for Baseball players. I added a Select option on each html page. I would like to display individual player information based on the selection from dropdown. Ex: If i select "John Doe" from drop down, i would like to see only "John Doe's" information. How can i code this. Thanks. -
'CustomEmailBackend' object has no attribute 'request'
I'm attempting to subclass the smtp backend for django and I'd like to get access to self.request or request, I'm getting the following error: 'CustomEmailBackend' object has no attribute 'request' Here is my subclass of EmailBackend from django.core.mail.backends.smtp import EmailBackend class CustomEmailBackend(EmailBackend): def send_messages(self, email_messages): if not email_messages: return 0 with self._lock: new_conn_created = self.open() if not self.connection or new_conn_created is None: return 0 num_sent = 0 for message in email_messages: #set default for this message deliverable = True #get list of recipients on message recipients = message.recipients() for recipient in recipients: emailvalidation = email_validation(recipient) if emailvalidation.result == "Safe to Send": pass else: deliverable = False if deliverable == True: sent = self._send(message) if sent: num_sent += 1 else: messages.error(self.request, 'Email address invalid. Email was not sent.') if new_conn_created: self.close() return num_sent -
MultiValueDictKeyError at /api/users/ - Django
So I'm trying to create a backend API using django and django rest framework, I'm trying to implement a login system using custom tokens, So I'm trying to make it so that when you put your login information in get request then it is supposed to take that information and return you a token but I'm running into some errors, When I first load up the page by typing http://localhost:8000/api/users/?username=admin?password=12345 I get MultiValueDictKeyError at /api/users/ error. Here is my code: class UserTokenHandler(APIView): def get(self, request, format=None): username = request.GET['username'] password = request.GET['password'] user = User.objects.filter(username=username) if user.exists(): if user.password == password: chosen_token = '' for i in range(20): lower_case = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] upper_case = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] random_choice = random.randint(1,3) if random_choice == 1: chosen_token += lower_case[random.randint(0, len(list) -1)] elif random_choice == 2: chosen_token += numbers[random.randint(0, len(list) -1)] elif random_choice == … -
mibian library version check in python
I am developing django project How can I check mibian version in run time of code import mibian print mibian.__version__ the bug result AttributeError: module 'mibian' has no attribute '__version__' -
include looged used in utils.py django
I have created an HTML calendar in the utils.py, where it created the events I would like to make it so that it uses the events of the user logged. There is a session created with the username. utils.py from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Event from myProject.helper import get_current_user class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal Does anyone have a solution on how I can achive that? -
Favicon not appearing
For some reason my favicon is not appearing on chrome. I am using django. And I have a file named favicon.ico in my static folder. {% load static %} <link rel="icon" href="{% static 'favicon.ico' %}"/> -
How do i get rid of value error, the view xxx didn't return an HttpResponse Object. It returned none instead
so im doing cs50x web development and the assignment is creating a wikipedia page. I created a views function where I can click on edit page to edit the content. However I keep running into this problem.enter image description here This is my code from views.py class EditForm(forms.Form): body = forms.CharField(label= "Body") def edit_page(request): title = request.POST.get("edit") body = util.get_entry(title) form = EditForm(initial={'body': body}) if request.method == "POST": form = EditForm(request.POST) if form.is_valid(): content = form.cleaned_data["body"] util.save_entry(title, content) return render(request, "encyclopedia/title.html", { "title": title, "content": util.get_entry(title) }) else: return render(request, "encyclopedia/edit.html", { "form": EditForm() }) urls.py: urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.title, name="title"), path("search", views.search, name="search"), path("new_page", views.new_page, name="new_page"), path("random", views.randomizer, name="random"), path("edit", views.edit_page, name="edit") ] title.html: <form action= "{% url 'edit' %}", method= "POST"> {% csrf_token %} <button type="submit" name="edit" value="{{title}}" id="edit">Edit Page</button> </form> and finally edit.html <form action="{% url 'edit' %}" method="POST"> {% csrf_token %} {{form}} <input type="submit"> </form> Someone please help me to solve this issue thanks! -
how to install proj4 in ubuntu , make: *** No targets specified and no makefile found. Stop. geodjango
i'm following the geodjango docs proj4 section , i have installed proj-7.0.1.tar.gz and proj-datumgrid-1.8.tar.gz , and untar them as in the docs mentioned , but when i try to run make command after directory ./configure it returns make: *** No targets specified and no makefile found. Stop. it there something i have missed ! or maybe i have used a wrong version thank you -
Django: Iterate through static files in HTML
I followed this answer. Iterate through a static image folder in django So I have {% with 'images/'|file as image_static %} <img src="{% static image_static %}" alt=""> <a class="gallery-one__link img-popup" href="{% static image_static %}"><i class="tripo-icon-plus-symbol"></i></a> {% endwith %} I did pass the context dict correctly in views, I think, because I saw this in my traceback: context_dict = {} files = os.listdir(os.path.join(settings.STATIC_ROOT, "blog/images/gallery")) context_dict['files'] = files But I'm not sure why it's giving me the following error django.template.exceptions.TemplateSyntaxError: Invalid filter: 'file' I also tried {% load crispy_forms_filters %} at the start of the HTML but it's not making a difference. I'm quite new to this, so I'm probably doing something stupid, and I cannot find any docs referring to this specific instance -
Django Rest Framework append object to many to many field without deleting the previous one
I am new to DRF and could not figure it out how to append an object to the many to many field without deleting the previous one. I am using PATCH to update the field MONITORS however the previous value gets substituted by the actual one. I want to append it. API GET is: ''' { "id": 1, "created": "2018-05-02T23:43:07.605000Z", "modified": "2021-04-03T10:25:12.280896Z", "companies_house_id": "", "name": "Ellison PLC", "description": "", "date_founded": "2018-04-28", "country": 4, "creator": 7, "monitors": [ 3 ] } ''' after PATCH {"monitors":[11]} I get: ''' { "id": 1, "created": "2018-05-02T23:43:07.605000Z", "modified": "2021-04-03T10:25:12.280896Z", "companies_house_id": "", "name": "Ellison PLC", "description": "", "date_founded": "2018-04-28", "country": 4, "creator": 7, "monitors": [ 11 ] } ''' I want the final GET API to be "monitors": [3 , 11] models.py ''' class Company(TimeStampedModel): companies_house_id = models.CharField(max_length=8, blank=True) name = models.CharField(max_length=200, blank=True) description = models.TextField(blank=True) date_founded = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.PROTECT, blank=True) creator = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='companies_created' ) monitors = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='companies_monitored', help_text='Users who want to be notified of updates to this company' ) def __unicode__(self): return u'{0}'.format(self.name) ''' serializers.py ''' from rest_framework import serializers from .models import Company from django.contrib.auth import get_user_model class CompanySerializer(serializers.ModelSerializer): class Meta: model = … -
Why is custom user password not getting set and authenticated?
I thought it would be a breeze to swap the User model's username with its email. So I am using a CustomUser. from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import UserManager class CustomUser(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() Since CustomUser is inherited from AbstractUser model, I thought I was done, but I guess I am still far from it. Here's my django shell interaction: >> from django.contrib.auth import get_user_model >> User = get_user_model() >> User.objects.get(email='dave@gmail.com').password '123' # wutt? why is this plaintext? >> User.objects.get(email='dave@gmail.com').set_password('abc') >> User.objects.get(email='dave@gmail.com').password '123' # still same! So functionally, this is completely useless. Since django.contrib.auth.authenticate for the users always returns None. What am I doing wrong? How can I achieve the minimal functionality that my CustomUser is only different from default django User model in that my CustomUser should use email as the username? I have already checked out the SO hits: Django User password not getting hashed for custom users django custom user model password is not being hashed EDIT: I'm using the following as my UserManager from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): … -
Hi there !, I'm learning django as my first framework for backend, i face this error and not yet find way to fix it? hope someone will help me
File "C:\Users\tumatijr\Desktop\portfolio-project\portfolio\urls.py", line 24, in Path('/', views.home, name='home'), NameError: name 'Path' is not defined and this is the urls from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), Path('', jobs.views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
add_to_cart() missing 2 required positional arguments: 'product_id' and 'quantity'
i am beginner I don't know what to do sorry please help me Traceback Traceback (most recent call last): File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /cart/add/ Exception Value: add_to_cart() missing 2 required positional arguments: 'product_id' and 'quantity' urls.py from django.urls import path from .views import ( cart_home, add_to_cart, remove_from_cart, checkout_home, checkout_done_view ) app_name = 'carts' urlpatterns = [ path('', cart_home, name='home'), path('checkout/success', checkout_done_view, name='success'), path('checkout/', checkout_home, name='checkout'), path('add/', add_to_cart, name='add-item'), path('remove/<product_id>/', add_to_cart, name='remove-item'), ] views.py def add_to_cart(request, product_id, quantity): product = Product.objects.get(id=product_id) cart = Cart(request) cart.add(product, product.unit_price, quantity) def remove_from_cart(request, product_id): product = Product.objects.get(id=product_id) cart = Cart(request) cart.remove(product) def cart_home(request): cart = Cart(request) return render(request, 'carts/home.html', {"cart":cart}) -
django wsgi with apache2 configuration gives page not found 404
For assumption here testsite.com which is my php application and testsite.com/project is python-django application I have following settings in my apache site config file /etc/apache2/sites-available/site.conf <VirtualHost *:443> ServerAdmin webmaster@testsite.com ServerName testsite.com DocumentRoot /var/www/html WSGIDaemonProcess test python-path=/var/www/html/projectenv/test-project python-home=/var/www/html/projectenv WSGIProcessGroup test WSGIScriptAlias /project /var/www/html/projectenv/test-project/test-project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> NOTE: I have to keep WSGIScriptAlias as /project since only for this url my django project should work. But when I hit testsite.com/project its giving following error Page not found (404) Using the URLconf defined in test-project.urls, Django tried these URL patterns, in this order: admin/ project/ The empty path didn't match any of these. Here is my project url structure urlpatterns = [ path('admin/', admin.site.urls), path('', include('projectapp.urls')) ] projectapp/urls.py from django.urls import path from . import views urlpatterns = [ path('project/', views.home, name='project'), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'projectapp', ] Please suggest solution that when I hit this url testsite.com/project it should go through my defined django app and render the page which is linked to this view, Its observed that wsgi is not able to pass through the django project structure and due to which its not identifying the url given in app. … -
How to use the file path of a .csv file in Django project(Web app)
I have a Django project that can get the .csv file from the user. Now I want to do analyze the .csv file on my Django project. How can I get the path of the file from my Django project to do this? Here is my Django settings: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'files') I would like to analyze the data saved in the media and then try to show the result like a table in the web application. If you any sample code that helps me in that case please share it. I hope you understand the problem. Thanks in advance