Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send notifications to users in Django
I have a more general Django question on how to approach the following functionality. Think of the Facebook/Messenger; once you receive a like or message, you will instantly receive a red circle at the top with "1" (or just think of any other notification). I have a scenario where I wan't a user to get a notification if I for example add them to a certain group, preferably without having to reload the page. I have googled around and I think that WebSockets are the way to go, but it seems fairly complex and not many tutorials out there. Anyone has any feedback or if someone could point me in the right direction? If not in realtime and without having to refresh the page, I would somehow want the user to get a (1) notification in the navbar. Any thoughts/feedback appreciated! -
Object.Filter() error using boolean fields
When I try to use model.objects.filter(mybooleanfield=True) gives me this error ('42000', "[42000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server] A non-Boolean expression was specified in a context where a condition was expected, near 'mybooleanfield'. (4145) (SQLExecDirectW) ") But this only happens when use the filter with some BooleanField if I use PositiveIntegerField, CharField, DateTimeField or TextField there's no problem with the filter. I think this could be for the verions I use Python 3.9.0 Django 3.1.3 Pyodbc 4.0.30 Django-mssql-backend 2.8.1 I need to use as condition my BooleanField. Someone knows why this happend? -
Secured connection for Django app deployed with Docker
I've remote server with installed Ubuntu 20.04, Docker and Docker Compose. My Django app is deployed with Docker and running at http://my_server_ip_address:8000 How to make it use https instead of http??? Here is my Dockerfile content: FROM python:3 ENV PYTHONUNBUFFERED=1 RUN cd /usr/local/bin && python -m pip install --upgrade pip WORKDIR /code RUN ls . COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN ls . VOLUME /code And here is my docker-compose.yml file content: version: "3.8" services: db: restart: always image: postgres container_name: my_api_db environment: - POSTGRES_DB=my_api_db - POSTGRES_USER=my_api_db_user - POSTGRES_PASSWORD=my_api_db_password api: restart: always image: my_docker_image depends_on: - db container_name: my_api env_file: .env ports: - "8000:8000" command: bash -c " python manage.py makemigrations && python manage.py migrate && python manage.py create_super_user && python manage.py runserver 0.0.0.0:8000" Thank you in advance for any help! -
Django Dates and Times
I am trying to build a simple django eCommerce site. However, there are two issues I can't seem to solve(As of right now, I did not code anything up yet because I am brainstorming): Dates: How can I allow a user to select the dates for the items to be delivered or picked up? Also, I am wondering how I would take into account during leap years and possibly Daylight Saving? Example: If a user wanted to buy something, it should show the following days where users can pick which day the items to be delivered or picked up: (Today, Dec 7) , (Tomorrow, Dec 8) , (Wed, Dec 9) , (Thu, Dec 10) , (Fri, Dec 11) , (Sat, Dec 12), etc. . If the user decided to exit the page and came back to the page tomorrow, In addition, if the user decided to exit the page and came back to the page tomorrow, how can I show tomorrow's date and the future dates. Hours: How can I allow the business owner or third party seller set the hours for the items to be delivered or picked up? Preferably in like intervals? Example: Business owner/third party seller set … -
How to render ajax response by Django template language?
Render ajax response by Django template language I have template_name = "buzz.html" in class IndexView(TemplateView): Its get_context_data function defines json context and returns it. The content is rendered in the buzz.html using template language. The IndexView class also contains a function called def post(self, request, *args, **kwargs): The post function returns JsonResponse({"hi": "just testing"}) This post function gets called via ajax when I click a button on my html template. The success function in ajax defines the following: $("#res").html(json.hi); to show the content of hi in the div with id "res". The string "just testing" is displayed How can I get the post function to behave like the IndexView class so that I can use {{ hi }} template language instead of $("#res").html(json.hi)? -
Python Crash Course 19-1 project troubles
19-1. Blog: Start a new Django project called Blog. Create an app called blogs in the project and a model called BlogPost. The model should have fields like title, text, and date_added. Create a superuser for the project, and use the admin site to make a couple of short posts. Make a home page that shows all posts in chronological order. Create a form for making new posts and another for editing existing posts. Fill in your forms to make sure they work. I'm having issues trying to show the blog post title as well as the paired body of text underneath it. My current setup is showing the correct titles in order, but it's only showing the last entry for each bullet. models.py from django.db import models # Create your models here. class Blog_post(models.Model): """ Create new blog post """ title = models.CharField(max_length=60) date = models.DateTimeField(auto_now_add=True) body = models.TextField() def __str__(self): """ Return string representation of the title""" return self.title urls.py """ Define URL patterns for blog_app """ from django.urls import path from . import views app_name = 'blog_app' urlpatterns = [ # Home page path('', views.index, name='index'), ] views.py from django.shortcuts import render from .models import Blog_post # … -
How to make URL to the same location as a form in Django?
I have some Django app, which has a geolocation form, which I would like to understand how it works as an example. I can fill form with from and to addresses and when I press Go button it will open the following url http://mysite/?route_from=32.71568%2C-117.16171&route_to=34.05361%2C-118.2455&auto_update=false and it shows the route between cities. The form is encoded with {% block content %} {% with action=using_next|default:"home" %} <form method="get" action="{% url 'ui:'|add:action %}"> ... <input name="auto_update" type="hidden" value="false"/> <button type="submit">{% if using_next %}Go!{% else %}Save{% endif %}</button> </div> </div> </div> </form> {% endwith %} I was wishing to make static URL to instantly open the same route and added inside with <div class="row"> <div class="col-sm-10"> <div class="box"> <div id="predefined_01"> Example 01: <a href="{% url 'ui:'|add:action route_from='32.71568,-117.16171' route_to='34.05361,-118.2455' auto_update='false' %}">San Diego - Lon Angeles</a> </div> </div> </div> </div> I was thinking it will fill the same arguments as a form and navigate to the same place. Unfortunately, it swears upon render: NoReverseMatch at /settings/ Reverse for 'tracker' with keyword arguments '{'route_from': '32.71568,-117.16171', 'route_to': '34.05361,-118.2455', 'auto_update': 'false'}' not found. 1 pattern(s) tried: ['$'] settings is a current page. What I did wrong and how to fix? -
Timeout information in django q task
I'm running some functions with async_task() and I set the timeout. When the task exceeds the timeout I want to run the other function which tells the user about the failure. The problem is that I don't know how to get the information about stopping the task because of timeout. -
PisaDocument Not converting Image to Circular
I was making a pdf from html using xhtml2pdf.pisa in Django. But, after using a border-radius in image, the pdf shows image at rectangle. Here is my code:- def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() print(result.getvalue()) pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) return HttpResponse(result.getvalue(), content_type='application/pdf') In the html, #logo{ border-radius : 50%; width : 60px,; height : 60px; } {% if logo.url %} <img src="{{ logo.url }}" id="logo"> {% endif %} I checked and it is rendering properly in html, but not in the pdf. How can I make my images circular?? -
Error in Custom Implementation of Refreshing JWT Token
I used the simpleJWT in Django. The login works fine, however I want to implement a view for the refresh toke. So I get in the request body the access and refresh tokens, I check if the access token is still valid, and if its not then I generate a new one. However this implementation does not seem to work. (testing it with postman with given tokens it requests for the users details) serializers.py class RefreshSerializer(serializers.Serializer): accessToken = serializers.CharField(max_length=255, required=True) refreshToken = serializers.CharField(max_length=255, required=True) views.py class TokenRefreshView(APIView): permission_classes = () authentication_classes = () def post(self, request): received_json_data = request.data serializer = RefreshSerializer(data=received_json_data) if serializer.is_valid(): accessToken = received_json_data['accessToken'] refreshToken = received_json_data['refreshToken'] if (rest_framework_simplejwt.views.token_verify(accessToken).status_code != 200): user = rest_framework_simplejwt.authentication.JWTAuthentication.get_user(accessToken) refresh = RefreshToken.for_user(user) newaccesstoken = str(refresh.access_token) return JsonResponse({ 'accessToken': newaccesstoken }, status=200) else: return JsonResponse({ 'message': 'Token still valid', }, status=403) else: return JsonResponse({'message': serializer.errors}, status=400) -
Associating products with the Current Users in django
Currently If i try adding a new product , i get this error IntegrityError "Cannot assign "(<Merchant: aliyu>, False)": "Product.merchant" must be a "Merchant" instance" . what i want to achieve is product to be associated with the current user. class Product(models.Model): name = models.CharField(max_length=255, unique=True) date_added = models.DateTimeField(auto_now_add=True) merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE,null=True) class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) views.py def addproduct(request): if request.method=='POST': form=ProductForm(request.POST) if form.is_valid(): new_product=form.save(commit=False) new_product.merchant__user=request.user new_product.save() return HttpResponseRedirect('users:users_homepage') else: form=ProductForm() context={'form':form} return render(request,'users/addproduct.html',context) please help me.thanks beforehand. -
Django/Celery/WSGI Dropping telemetry
My Django app is giving this error while some HTTP requests are happening. Using Django, Celery, and WSGI with MSSQL, and frontend react -
Django CBVs to return a JsonResponse?
I have been using Django for quite some time, but running into some issues with trying something new. I have built API's with Django-Rest-Framework using Class Based Views, and I have also built API's using Function based views returning a JsonResponse Now what I am tasked to do is use CBV's to return a JsonResponse without using DRF. I am trying to produce a simple get request class BusinessDetailView(DetailView): model = BusinessDetail def get_queryset(self): business = BusinessDetail.objects.get(id=self.kwargs.get('pk')) return JsonResponse({'business': list(business)}) Using the models pk I keep running into issues with this simple request. I am getting a TypeError 'BusinessDetail' object is not iterable and if I make some small changes and override get_object I'll get the same error, or I'll even get a 'BusinessDetail' object is not callable Does anybody have any tips with using CBVs to return Json, without using DRF? Thank you all in advance! -
Save content of Modelchoicefield Django
I have a form PurchaseOrderDetailsForm contain product_attr CharField which not related to any other model. In the form, I'm using product_attr field as a model choice field with ProductAtrributes instance and get data with ajax by product id. Now I'm trying to save product_attr filed content into the PurchaseOrder_detail table but unable to save or insert data into the product table. without this, product_attr filed it's working fine. Any help would be greatly appreciated. Model: PurchaseOrder_detail product = models.ForeignKey('Product', blank=True, null=True, on_delete=models.SET_NULL) product_attr = models.CharField(max_length=50, blank=True, null=True) Model: ProductAttributes class ProductAttributes(models.Model): product = models.ForeignKey('Product', blank=True, null=True, on_delete=models.SET_NULL) size = models.ManyToManyField('ProductSize', blank=True) colour = models.ManyToManyField('ProductColour', blank=True) cupsize = models.ManyToManyField('ProductCupSize', blank=True) def __str__(self): return str(self.product) Form: class PurchaseOrderDetailsForm(forms.ModelForm): product = forms.ModelChoiceField(label=('Product'), required=True, queryset=Product.objects.all(), widget=Select2Widget(attrs={'style': 'width:100%;', 'class': 'form-control'},)) product_attr = forms.ModelChoiceField(label=('Attributes'), queryset=ProductAttributes.objects.none(), widget=Select2Widget()) class Meta: model = PurchaseOrder_detail exclude = () ajax: // load attributes $(document).on("change", ".product", function() { var selector = $(this) $.ajax({ url: '/purchase/ajax/load-attrs/', type: "POST", data: { 'product': $(this).parents('tr').find(".product").val() }, success: function (data) { selector.parents('tr').find(".product_attr").html(data); } }); }); Template: <option value="">---------</option> {% for attr in attrs %} <option value="{{attr.product|default_if_none:"" }}{{attr.colour__name|default_if_none:"" }}{{attr.size__name|default_if_none:"" }}{{attr.cupsize__name|default_if_none:"" }}"> {{attr.colour__name|default_if_none:"" }}{{attr.size__name|default_if_none:"" }}{{attr.cupsize__name|default_if_none:"" }} </option> {% endfor %} view: def form_valid(self, form): context = self.get_context_data() order_details = … -
Heroku forcing my Django application to use SSL doesnt work
I followed instructions of Heroku devcenter: MIDDLEWARE = [ # SecurityMiddleware must be listed before other middleware 'django.middleware.security.SecurityMiddleware', # ... ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True On Heroku setting its said that "Your app can be found at https://----------.net" so the SSL is configured fore sure, nethertheles when I write on browser only domain name without protocol I get ERR_SSL_PROTOCOL_ERROR (Chrome) and on Safari - "Safari can not open the page because it could not estabish a secure connection to the server" Any hint please what more can I do? -
Django using select options in registration forms.py
I put some teams in my models.py in this way: class Account(AbstractBaseUser): TEAM = (('python', 'python'), ('php', 'php')) ... username = models.CharField(max_length=16, unique=True) first_name = models.CharField(max_length=16, unique=True) last_name = models.CharField(max_length=16, unique=True) member_of = models.CharField(max_length=20, choices=TEAM, default=STATUS[0][0]) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = AccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True and my forms.py is like: class RegistrationForm(UserCreationForm): #email = forms.EmailField(max_length=50) class Meta: model = Account #fields = '__all__' fields = ['username', 'first_name', 'last_name', 'password1', 'password2', 'member_of'] So when I want to use it in my registration.html I am not able to create account: <div class="group text-left"> <label for="exampleFormControlInput1">team</label> <select name="status" class="form-control" id="exampleFormControlSelect2"> {% for team in registration_form.member_of %} {{team}} {% endfor %} </select> </div> and also it is not important to use registration_form.member_of. If I only put member_of in my forms.py I can't register new users -
Post request fails in Django Rest Framwork due to CSRF Token missing
I am trying to make a POST request to my DRF API Endpoint through a React frontend. I get a 403 Forbidden (CSRF token missing or incorrect.): /api/content/wishlists error. I looked at other solutions, and most of them point out that the default django authentication classes need to be adapted to DRF. I am working with django-rest-knox for authentication purposes so my settings.py contains: # REST Framework Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',) } I still keep receiving this error. Here is the api.py class WishlistViewset(viewsets.ModelViewSet): serializer_class = WishlistSerializer queryset = Wishlist.objects.all() permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] def list(self, request): queryset = Wishlist.objects.all() serializer = WishlistSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Wishlist.objects.all() wishlist = get_object_or_404(queryset, pk=pk) serializer = WishlistSerializer(wishlist) return Response(serializer.data) def perform_create(self, serializer): serializer.save(owner=self.request.user) My Javascript code to trigger the api call const createWishlist = (content, setCreated) => { axiosInstance .post(`/content/wishlists`, content, tokenConfig(auth.token)) .then((res) => { dispatchMessages(createMessage({ contentAdded: "Wishlist created" })); setCreated(res.data.id); }) .catch((err) => dispatchErrors(returnErrors(err.response.data, err.response.status)) ); }; Where the tokenConfig function basically just adds a header with the authentication token to the request like this: export const tokenConfig = (token) => { // headers const config = { headers: { "Content-Type": "application/json", }, … -
How to make a input in Admin page as password type?
hello i create a model wich have 3 fields, name,email,password. i want the password in the admin to not show as clear text or to not show even . any ideas to change input type in the admin page from type='text' to type='password' image of password input in my admin page Models.py class Artist(models.Model): artist_name = models.CharField(max_length=255,null=False,blank=False) email = models.EmailField(max_length=255, null=False,blank=False) password = models.CharField(max_length=20, null=False,blank=False) def __str__(self): return self.artist_name admin.py from django.contrib import admin from home.models import Track , Artist , Region , User admin.site.register(Artist) -
Django error: type object 'Enter' has no attribute 'objectes'
Screenshot from 2020-12-07 21-23-28.png Hello my friends I am facing this problem and I have not found a solution. I hope you will help me -
Associating New products with the Current User in django
Currently If i try adding a new product , i get this error IntegrityError "NOT NULL constraint failed: products.merchant_id" what i want to achieve is product to be associated with the current user. models.py class Product(models.Model): name = models.CharField(max_length=255, unique=True) date_added = models.DateTimeField(auto_now_add=True) merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE,null=True) class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) views.py def addproduct(request): if request.method=='POST': form=ProductForm(request.POST) if form.is_valid(): new_product=form.save(commit=False) new_product.merchant__user=request.user new_product.save() return HttpResponseRedirect('users:users_homepage') else: form=ProductForm() context={'form':form} return render(request,'users/addproduct.html',context) -
How to update a related Django model for a newly created instance
I am trying to create a database object and also update the related payouts table at the same time. When I try to update table using the related name payouts__payout_status_client="Hello" it doesn't work. models.py class Invoices(models.Model): invoice_ref = models.CharField(max_length=10, default="", blank=True) week_start_date = models.DateTimeField(auto_now_add=False) week_end_date = models.DateTimeField(auto_now_add=False) invoice_gross_value = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS, class Payouts(models.Model): invoice = models.ForeignKey( Invoices, null=True, related_name="payouts", on_delete=models.PROTECT ) payout_status_client = models.CharField(max_length=10, default="Pending", blank=True) payout_status_hungryme = models.CharField(max_length=10, default="Pending", blank=True) views.py create_record = Invoices.objects.update_or_create(invoice_ref=invoice_ref, payouts__payout_status_client="Hello") -
Django + Gunicorn + Nginx. 404
I am trying to run django + gunicorn + nginx locally. For some reason nginx is not getting data from static. Please tell me what am I doing wrong? Gunicorn: gunicorn config.wsgi:application --bind 127.0.0.1:8001 Nginx config: # mysite_nginx.conf upstream project_server { server 127.0.0.1:8001; } # the upstream component nginx needs to connect to # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name localhost; # substitute your machine's IP address or FQDN # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/ferom/Programming/my_avatar_clock/media; # your Django project's media files - amend as required } location /static { alias /home/ferom/Programming/my_avatar_clock/my_avatar_clock/proj/static; # your Django project's static files - amend as required } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } Folders: In settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') But when I open http://127.0.0.1/admin/ Nginx say me: 404. cat /var/log/nginx/error.log - empty What am I doing wrong? -
How do I add a default value to a nested serializer?
I am trying to have my "address" API return the default value (empty string ""), but when I use default="" in the serializer field it returns null instead. This is my main serializer (LocationSerializer) class LocationSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) business_id = serializers.PKRelatedField(Business.any.all(), "business") city_id = serializers.UUIDField(required=True) name = serializers.CharField(max_length=48, required=True) tax_number = serializers.CharField(max_length=48) phone = serializers.PhoneNumberField() address = serializers.CharField() address_details = AddressEmbeddedSerializer(default="", source="addresses") footer = serializers.CharField() is_active = serializers.BooleanField(required=True) has_kds = serializers.BooleanField(read_only=True) position = serializers.PointField() image = serializers.ImageField() # profile = LocationProfileSerializer() permissions = PermissionSerializer(many=True, read_only=True) payment_methods = PaymentMethodEmbeddedSerializer(many=True, read_only=True) class Meta: model = Location fields = ( "id", "business_id", "city_id", "name", "tax_number", "phone", "address", "address_details", "footer", "is_active", "has_kds", "position", "image", "permissions", "payment_methods" ) and this is my nested serializer (AddressEmbeddedSerializer) class AddressEmbeddedSerializer(serializers.ModelSerializer): city = serializers.CharField(default="") area = serializers.CharField(default="") block = serializers.CharField(default="") avenue = serializers.CharField(default="") long = serializers.CharField(default="") lat = serializers.CharField(default="") class Meta: model = LocationAddress fields = ( "city", "area", "block", "avenue", "long", "lat" ) The value that I am expecting is: "address_details": { "city": "", "area": "", "block": "", "avenue": "", "long": "", "lat": "" } Instead what I am getting is: "address_details": null Please note that all CRUD operations are working, this is only a default value … -
When trying to get a model field i get DeferredAttribute object Django
Hello so basically i have a profile model that keeps track of points. And i group those profiles into groups as students. So basically in the groups i have a method going through all of the students in the group and returning a list of points but it's intended to be sum(), (since im getting an error i tried a list to debug). How do i get the actuall value instead of the object? This is the code: class profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.SmallIntegerField(default=0) def __str__(self): return self.user.username def addPoints(self, amount): self.points += amount def subtractPoints(self, amount): self.points -= amount def changePoints(self, amount): self.points += amount class skupine(models.Model): choices = ( ('#52A2D9', 'Modra'), ('#8ec641', 'Zelena'), ('#f3c12f', 'Rumena'), ('#e2884c', 'Oranžna'), ('#f37358', 'Rdeča'), ('#b460a5', 'Vijolična') ) teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='teacherToSkupina') title = models.CharField(max_length=30) desciption = models.CharField(max_length=120, null=True) color = models.CharField(max_length=7, choices=choices) students = models.ManyToManyField(profil, related_name='studentsToSkupina') def __str__(self): return self.title def get_total_points(self): return list(profil.points for items in self.students.all()) class Meta: verbose_name_plural = "skupine" What i get when i call the method : >>> s.get_total_points() [<django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute object at 0x03D957D0>, <django.db.models.query_utils.DeferredAttribute … -
How to add a folder to Django?
So my question looks like this Creating a new project django-admin startproject firstapp Creating a new app python manage.py startapp blog So, my question is . I've added a new folder called "projects" within the app "blog" Django doesn't see the folder. How to connect? via INSTALLED_APPS (I've tried it doesn't work)