Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django http cookies: set-cookie vs. cookies
I am trying to figure out how Django is setting a cookie. Is it returning it as a set-cookie header including the cookies in the response payload object? See info here. -
Get scrapy spider response back on django Rest api GET
I'm working project it contains a GET request with a few parameters suchas (airline code and flight date), I pass those parameters to a crawler coded using scrapy . I've created Django command in management/commands to hit the scrapy crawler and as soon the scraping is done the data being saved in particular models. As I want to return that saved data to the same GET request, I have a few questions regarding it. How to return data in GET request? As I couldn't find a way to get returned data from scrapy crawler. How do I make wait that GET request for a particular time when scraping is being done. Assuming GET request is on waiting and scrapping is done now I have to validate if there is scraped data present in database accordingly to the params. Assuming the data is found in database and then how can I return it to the same GET request? If I want to use celery in this whole process what could be the best use of it? -
How to secure a spyne web service with Basic authentication in django
I have a soap service in django application and I covered this service with login required decorator. Client should send soap request with Authorization(Basic) headers and with these credentials I have to authenticate this client. I found one example for http headers in spyne: class RequestHeader(ComplexModel): __tns__ = 'spyne.examples.authentication' username = unicode() ee = unicode() class UserService(ServiceBase): __tns__ = 'spyne.examples.authentication' __in_header__ = RequestHeader @rpc(Mandatory.String, _returns=String) def get_head(ctx, user_name): print '*'*20 print ctx.in_header_doc print ctx.in_body_doc print ctx.in_header.ee retval = "Where's the header" return retval But I thought it did not match with my requirements Because client should authenticate with given credentials from me. I would appreciate any help(links, tutorials, similar answered questions) -
Django Register login
When we click on the register link register form should appear Register page Requirement o Username o Password o Confirm password o Submit button When we click on submit button then it should direct to the login page After login need to move to a new page The new page should contain a button When we click on the button a form should appear How to solve this in Django? Tags -
How to apply advance django query set filters based on two different columns?
I am new to django. I am working on a test project. Where I have a Model CollectFee with structure given below: Database table screenshot I want to apply a query set in the views which will display all the records where feetype_id is not 2, when this record is excluded then also exclude those records which have the same boarder_id as of already excluded record. For example, Exclude the second row as it has feetype_id = 2 then also exclude the third row because it has the same boarder_id as of second row. As I am new, I was able to just implement the filter below: def feedue(request): fee_type = 2 duefee= CollectFee.objects.exclude(feetype_id=2) context = {'duefee':duefee} return render(request, 'fee-due.html', context) -
Add additional field to response in pytest-django
I'm new to testing and I spent a day finding a solution for my problem but I couldn't find any. this is my serializer serilaizer.py class LeadSerializer(serializers.ModelSerializer): def create(self, validated_data): user = self.context['user'] return Lead.objects.create(organizer=user.organizeruser, **validated_data) class Meta: model = Lead fields = ['id', 'first_name', 'last_name', 'age', 'agent', 'category', 'description', 'date_added', 'phone_number', 'email', 'converted_date' ] I have two types of users, organizer, and agent. organizer can create a lead but agent can't. and as you see I don't have organizer field. authenticated user will be added to the organizer field when a Lead is created. test.py def test_if_lead_exist_return_200(self, api_client, leads_factory, user_factory): user = user_factory.create(is_organizer=True) api_client.force_authenticate(user=User(is_staff=True)) lead = leads_factory.create() serializer = LeadSerializer(context={'request': user}) print(serializer) # here I can see the user response = api_client.get(f'/api/leads/{lead.id}/', ) assert response.status_code == status.HTTP_200_OK assert response.data == { 'id': lead.id, 'first_name': lead.first_name, 'last_name': lead.last_name, 'age': lead.age, 'organizer': lead.organizer.id, 'agent': lead.agent.id, 'category': lead.category.id, 'description': lead.description, 'date_added': lead.date_added, 'phone_number': lead.phone_number, 'email': lead.email, 'converted_date': lead.converted_date, } because there is no organizer field in the serialzier test won't pass and this is the result of the test what can I do here? can I pass the organizer user to the response? -
Webhook from Django 4.1 to python-telegram-bot 20.0a2
I use the python-telegram-bot 20.0a2 library and Django 4.1 The bot runs by main.py script: if __name__ == "__main__": asyncio.run(main()) Inside of the main script I also run uvicorn in the same ascynhronous context as Application instance # Run application and webserver together async with application_tg: await application_tg.start() await server.serve() # uvicorn await application_tg.stop() What is the problem? I use webhook for my bot Django's url.py calls async view but the view can't get initalized Application instance of the bot. so the question is: How can to rearrange a scheme of interaction between python-telegram-bot 20 and Django 4.1 in a way that I can access Application instance from a Django hook? Addition: It's easy to achieve by using other frameworks such as starlette as it mentioned on the official wiki page of PTB library: https://docs.python-telegram-bot.org/en/v20.0a2/examples.customwebhookbot.html My main script: https://gist.github.com/SergSm/6843fadf505b826f83a10bf7eebc3fa0 my view: import json from django.views import View from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt from telegram import Update from bot.tgbot.main import application_tg async def telegram_handle(request): if request.method == 'POST': await application_tg.update_queue.put( Update.de_json(data=json.loads(request.body), bot=application_tg.bot) ) return JsonResponse({"ok": "POST processed"}) else: return JsonResponse({"ok": "GET processed"}) -
AssertionError : List Differ in pytest django
I created a simple test to test the API endpoint. However it kept returning AssertionError: Lists differ: [] != [{'field_value': {'id': 1, 'panel_name': '[420 chars]: 2}] and Second list contains 4 additional elements. First extra element 0: {'field_value': {'id': 1, 'panel_name': 'Clinic A', 'panel_type': 1}, 'field_type': 'clinic', 'count': 3}. Does anyone know why is this happening ? Does it means the expected content is not present inside the list ? def test_api(self, query, expected): username = "jeff" password = "test" client = Client() response = client.post('/admin/login/', {'username': username, 'password': password}) self.assertEqual(response.status_code, 302) balance_type_collection = [ 'medical', 'dental' ] for balance_type in balance_type_collection: if query == '': query += '?' else: query += '&' query += 'balance_type=' + balance_type response = client.get('/api/v1/medical/clinicvisit/stats/'+ query) self.assertEqual(response.status_code, 200) content = json.loads(response.content) self.assertEqual(content, expected[balance_type]) -
local variable 'user' referenced before assignment error in django function
I have this function in django that adds a new item to the wishlist, the function is doing what it should do but when I add a new user that was not registered, when adding an item to the wish list it returns this error, but when i refresh the page the error no longer exist. I think the problem is that when a new user registers, he still does not have the database created in the wishlist model, so the try: condition fails because the user does not yet exist in the model, passing the except: condition where the user database is created, but I have to manually refresh the page so that the page no longer shows me the error. How can I fix this so that the page no longer shows me this error? def add_or_remove(request, listing_id): if request.method == "POST": if (request.POST["action"]) == "add": try: user = Wishlist.objects.get(user=request.user) listing = Listing.objects.get(pk=listing_id) user.item.add(listing) except: create = Wishlist( user=request.user, ) create.save() user.item.add(listing) messages.success(request, 'you added to Wishlist') elif (request.POST["action"]) == "remove": user = Wishlist.objects.get(user=request.user) item = user.item.get(id=listing_id) user.item.remove(item) messages.success(request, 'you removed from Wishlist') return redirect(reverse("listing", args=[listing_id])) -
Best way to incorporate a "utils" module in a django project?
I'm creating a project that will have several app named after states, such as: |-my_state_project |---my_state_project |---new_jersey |---alabama |---rhode_island I want to create a utils module that each app can import from. The utils.py file inside the utils module will have functions used to scrape data from the web using bs4. Each app will have a jobs.py script to import from utils.py. So the project will look like: |-my_state_project |---my_state_project |---new_jersey |------jobs.py |---alabama |------jobs.py |---rhode_island |---utils |------utils.py My questions are: Is this how Django projects are usually structured? I'm getting a ModuleNotFoundError: No module named 'utils.py' while trying to import inside one of the jobs.py files. I'm importing it using from utils import utils. Why is it complaining? This should be rudimentary The alternative would be to create a utils.py file inside each app which doesn't seem very pythonic (especially since the utils.py file may grow and updating each file individually would be torture :) -
NGINX throughs 404 and wont load static
Hopefully, Y'all can help me with this one and hopefully I am in the right areas to post this. Just recently began learning Django and I am trying to get it deployed to Linux. I have been using gunicorn and nginx for this deployment and for the most part I have been successful. I am able to successfully deploy and interact with my app, navigate pages and interact with some of the post requests. The only thing I have been banging my head around trying to figure out what is going on with my static files. All of my css and images do not display currently and I have tried searching everywhere for the resolution. I have tried using an alias in the nginx file and I have made sure that my static root and URL is fine, nothing i have tried has done the trick. the weird this is, when looking at the access logs from nginx it shows the Get request going to the correct file and path, but shows 404? I am at a loss here lol! What is really weird is that the static folder contains a few csv's that are processed and served by a … -
How can I get Sum for customer in current month django views
I am working on Django project where I want to get total (sum) deposit for each customer in the current month of the year in a list. I am not able to figure it out yet since there is no ID in use in the function request in order to use the .get() method to filter by the customer id. Below are my Model and views Code: class Customer(models.Model): surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=20, null=True) account_number = models.CharField(max_length=10, null=True) address = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=11, null=True) date = models.DateTimeField(auto_now_add=True, null=True) #Get the url path of the view def get_absolute_url(self): return reverse('customer_create', args=[self.id]) #Making Sure Django Display the name of our Models as it is without Pluralizing class Meta: verbose_name_plural = 'Customer' # def __str__(self): return f'{self.surname} {self.othernames} - {self.account_number}' class Deposit(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Views Code: def create_account(request): current_date = datetime.now().date() customers = Customer.objects.all() act = customers.account_number deposited_this_month = Deposit.objects.filter(customer__account_number=act, date__year=current_date.year, date__month=current_date.month).aggregate(deposited_this_month=Sum('deposit_amount')).get('deposited_this_month') or 0 I am having error which says 'QuerySet' object has no attribute 'account_number'. A … -
How to display the comments for each author of the article in the profile and site manager?
I'm writing a multi-author website with Django. I have used django-comments-dab for the comments section But I don't know how to display the comment of each article for its author in the panel? -
ImportError: cannot import name 'url' from 'django.conf.urls' for Django 3.2.8
My program got "ImportError: cannot import name 'url' from 'django.conf.urls'" for Django version 3.2.8 suddenly. It can work hours before... . How to fix this? -
python dcc.Location opening new page within a page
I have several dash apps in a html files, example of html with app 'viewer': {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} <h1>Viewer</h1> <div class="{% plotly_class name='viewer' %} card" style="height: 100%; width: 100%"> {% plotly_app name='viewer' ratio=0.7 %} </div> <br> {{ plot1 | safe }} {% endblock %} I am trying to open another html from a dash app using dcc.Location (a callback provides a href back to this after a button is clicked) but it loads the html within the current html so I end up with two of all the side menu's, search bars etc.. How do I get the app to load a whole new page? Even opening the link on a new tab would suffice. Thank you for any help with this. -
Django Rest Framework invalid serializer data, can not figure out why
I am creating a simple model with a many-to-many field. The model works fine and I can create model through the admin panel, and I can make a get request to see that model (except that it only returns user IDs instead of the user models/objects). My problem is when creating a post request to create said model. I get one of the two errors depending on the changes I make, The serializer field might be named incorrectly and not match any attribute or key on the 'str' instance. or AssertionError: You cannot call '.save()' on a serializer with invalid data., either way it has something to do with my serializer. The following is my model, class Schema(models.Model): week = models.PositiveIntegerField(primary_key=True, unique=True, validators=[MinValueValidator(1), MaxValueValidator(53)], ) users = models.ManyToManyField(MyUser, related_name="users") class Meta: ordering = ('week',) My View, class SchemaView(APIView): permission_classes = (SchemaPermissions,) def get(self, request): schemas = Schema.objects.all() serializer = SchemaSerializer(schemas, many=True) return Response(serializer.data) def post(self, request): data = request.data serializer = SchemaSerializer(data=data) serializer.is_valid() serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) And my serializer, class SchemaSerializer(serializers.ModelSerializer): class Meta: model = Schema fields = ('week', 'users') def create(self, validated_data): users_data = validated_data.pop('users') users = MyUser.objects.filter(id__in=users_data) schema = Schema.objects.create(week=validated_data.week, users=users) return schema def update(self, instance, validated_data): … -
Negative impact of a Django model with multiple fields (75+ fields)
I'm in the process of building a web app that takes user input and stores it for retrieval and data manipulation. There are essentially 100-200 static fields that the user needs to input to create the Company model. I see how I could break the Company model into multiple 1-to-1 Django models that map back the a Company such as: Company General List item Company Notes Company Finacials Company Scores But why would I not create a single Company model with 200 fields? Are there noticeable performance tradeoffs when trying to load a Query Set? -
Cannot import from or debug models.py
I've created 5 classes in a models.py inside my app city. I successfully created a db in postgres by importing each class inside the console accordingly. Next, I created a jobs.py script inside the city app so I can automatically scrape data using bs4 and populate/update a db accordingly. The problem occurs when I try to import each class from models.py at the top of my jobs.py script: from city.models import restaurants, barbers, apartments, bars, parks Generates: 'Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.' Any idea why I'm unable to import the classes from models.py into the jobs.py script? I also created a python package utils inside my project. Inside utils is a name_directory.py script that I'm also unable to import into my jobs.py script. Also, I just tried debugging my models.py file and it generated the same error! -
How to deploy tailwind flowbite and django application on Heroku server
I'm a tailwind CSS fanatic and a Django developer. On my own system, I was able to successfully install flowbite using django. On my local system, I ran correctly, however when I launched to a Heroku server, nothing happened. On the internet, I was unable to locate a useful tutorial on how to do it. Would you kindly direct me to a blog post or instructional video that describes how to host a Django and Flowbite application on a development server like Heroku? -
Django / How to refer to a specific news in views so that it is possible to leave a comment on the site through the form?
When submitting a form on the site, the "news_id" value is not pulled into the database (into the table with comments). Accordingly, it is not clear to which news a comment was left so that it could be published later. There are Russian symbols in the code, but they do not affect the essence of the problem in any way. models: class News(models.Model): title = models.CharField(max_length=255, verbose_name="Заголовок") slug = models.CharField(max_length=255, unique=True, db_index=True, verbose_name="URL") content = models.TextField(verbose_name="Содержимое") photo = models.ImageField(upload_to="news/%Y/%m/%d/", verbose_name="Изображение") video = models.URLField(max_length=255, blank=True, null=True, verbose_name="Ссылка на видео") time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения") category = models.ForeignKey("NewsCategories", on_delete=models.PROTECT, verbose_name="Категория") def __str__(self): return self.title def get_absolute_url(self): return reverse("show_news", kwargs={"news_slug": self.slug}) class Meta: verbose_name = "Новость" verbose_name_plural = "Новости" ordering = ["-time_update"] class Comments(models.Model): news = models.ForeignKey( News, on_delete=models.CASCADE, related_name='comments_news', verbose_name="Новость" ) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Автор комментария") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") content = models.TextField(verbose_name="Содержимое") status = models.BooleanField(verbose_name="Публикация комментария", default=False) def __str__(self): return self.content class Meta: verbose_name = "Комментарий" verbose_name_plural = "Комментарии" ordering = ["-time_create"] forms: class CommentForm(forms.ModelForm): content = forms.CharField( label='Добавить комментарий', widget=forms.Textarea(attrs={'rows': '4', 'class': 'form-control'})) class Meta: model = Comments fields = ['content'] utils: class DataMixin: def get_user_context(self, **kwargs): context = kwargs cats = NewsCategories.objects.annotate(Count('news')) context["cats"] = cats if "category_selected" … -
I can't get the posts to be in the position I want
<!DOCTYPE html> <!-- Created by CodingLab |www.youtube.com/CodingLabYT--> <html lang="en" dir="ltr"> {% load static %} <head> <meta charset="UTF-8"> <title>EBOT Maintenance </title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- Boxiocns CDN Link --> <link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div class="sidebar close"> <div class="logo-details"> <i class='bx bx-menu'></i> <span class="logo_name">EBOT</span> </div> <ul class="nav-links"> <li> <a href="{% url 'home' %}"> <i class='bx bx-grid-alt' ></i> <span class="link_name">Anasayfa</span> </a> <ul class="sub-menu blank"> <li><a class="link_name" href="{% url 'home' %}">Anasayfa</a></li> </ul> </li> <li> <div class="iocn-link"> <a href="{% url 'userSettings' %}"> <i class='bx bx-collection' ></i> <span class="link_name">Kullanıcı Ayarları</span> </a> <i class='bx bxs-chevron-down arrow' ></i> </div> <ul class="sub-menu"> <li><a class="link_name" href="{% url 'userSettings' %}">Kullanıcı Ayarları</a></li> <li><a href="{% url 'register' %}">Kullanıcı Ekle</a></li> <li><a href="{% url 'delete' %}">Kullanıcı Sil</a></li> <li><a href="#">Şifre Reset</a></li> </ul> </li> <li> <div class="iocn-link"> <a href="{% url 'users' %}"> <i class='bx bx-collection' ></i> <span class="link_name">Kullanıcılar</span> </a> <i class='bx bxs-chevron-down arrow' ></i> </div> <ul class="sub-menu"> <li class="list-group-item"><a href="{% url 'users' %}"> {% for user in users %} <div> <a href="">{{ user.username }}</a> </div> {% endfor %} </a></li> </ul> </li> <li> <div class="iocn-link"> <a href="{% url 'parameters' %}"> <i class='bx bx-book-alt' ></i> <span class="link_name">Parametreler</span> </a> </div> <ul class="sub-menu"> <li><a … -
Docker couldn't start properly throwing error: web_1 | /usr/bin/env: ‘python\r’: No such file or directory Django
I got error: web_1 | /usr/bin/env: ‘python\r’: No such file or directory after running docker-compose up on windows 10. -
Styling comments in Django
I found this tutorial on Django and Making a Hacker News Clone. Figure it'd be a good starting point as it's an pretty good break down with the Django and some concepts like comment parenting https://www.askpython.com/django/hacker-news-clone-django I thought cool and got through it, started learning more on Django Got my own search implemented into this too. However the comments on this were not great. So I wanted to improve things on it to make commenting prettier than the big colored blocks. However I've been stuck trying to make comment styling more Hacker News or Reddit style. I went searching and found https://css-tricks.com/styling-comment-threads/ though it it still didn't work the way I was figuring and wanted to have a more simplistic style though I'm running into a few issues. My idea would be to having it |Parent comment | Child Comment | Grandchild Comment | Child Comment2 |Parent Comment2 etc My commentpost.html comments section I modified {% for comment in comments %} {% if comment.identifier %} <div class="comment-thread"> <div class="replies"> <div class="comment-heading"> <div class="comment-vote"></div> <div class="comment-info"> <a href="#" class="comment-author"><a href = "{% url 'user_info' comment.creator.username %}">Comment by: {{comment.creator.username}}</a> | <strong>Thread Level: {{comment.identifier}}</strong></p> </div> </div> <div class="comment-body"> <p> <strong> {{ comment.content}} </strong> … -
Can't change dyno with Procfile on Heroku
I'm trying to deploy django project to Heroku using docker image. My Procfile contains command: web: gunicoron myProject.wsgi But when I push and release to heroku - somewhy dyno process command according to a dashboard is web: python3 Command heroku ps tells web.1: crashed And I can not change it anyhow. Any manipulation with Procfile doesn't work. When I deploy the same project with git - everything works fine. But why heroku container deploy does not work. Everything done following heroku instruction. My Dockerfile: FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ My docker-compose.yml: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data # ports: # - "5432:5432" environment: - POSTGRES_DB=${SQL_NAME} - POSRGRES_USER=${SQL_USER} - POSTGRES_PASSWORD=${SQL_PASSWORD} web: build: . # command: python manage.py runserver 0.0.0.0:8000 command: gunicorn kereell.wsgi --bind 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" # env_file: .env environment: - DEBUG=${DEBUG} - SECRET_KEY=${SECRET_KEY} - DB_ENGINE=${SQL_ENGINE} - DB_NAME=${SQL_NAME} - DB_USER=${SQL_USER} - DB_PASSWD=${SQL_PASSWORD} - DB_HOST=${SQL_HOST} - DB_PORT=${SQL_PORT} depends_on: - db My requirements.txt: Django psycopg2 gunicorn Please help me resolve this. Thanks in advance. -
Cannot resolve telethon AuthKeyDuplicatedError
Using Telethon to access a Telegram account and accidentally ran my dev server simultaneously with our production server the other day and now getting this error when trying to create a Telethon connection: telethon.errors.rpcerrorlist.AuthKeyDuplicatedError: An auth key with the same ID was already generated I've switched out the auth key and we deleted all the active sessions in our Telegram account, but to no avail. This is a script in a Django application running in docker on AWS EC2. Could there be a session file lurking somewhere I can't find? I'm using a redis cache, which I've cleared a couple times with no change to the error message either...although I didn't really think it was going to help. Any more ideas would be appreciated. note: I tried the solution steps listed here in this question it did not resolve the problem.