Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to use override_settings class decorator with setUpClass and tearDownClass Django
I am trying to write unittests in django. I encountered different behaviours of override_settings decorator when used with setUpClass and tearDownClass classmethods. Following is the code which doesn't work: import logging from django.test import SimpleTestCase, override_settings from django.http import Http404 from django.core.exceptions import SuspiciousOperation, PermissionDenied from django.urls import path from django.views.defaults import server_error def http_400_view(request): """Test view for 400 """ raise SuspiciousOperation def http_403_view(request): """Test view for 403 """ raise PermissionDenied def http_404_view(request): """Test view for 404 """ raise Http404 def http_500_view(request): """Test view for 500 """ return server_error(request) urlpatterns = [ path('400/', http_400_view), path('403/', http_403_view), path('404/', http_404_view), path('500/', http_500_view), ] @override_settings(ROOT_URLCONF=__name__) class ErrorCodeHandlerTests(SimpleTestCase): """ Tests for error code handlers """ @classmethod def setUpClass(cls): logging.disable(logging.CRITICAL) @classmethod def tearDownClass(cls): logging.disable(logging.NOTSET) status_codes = [400, 403, 404, 500] templates = ['400.html', '403.html', '404.html', '500.html'] user_messages = ['Bad request', 'Permission denied', 'Page not found', 'Internal server error'] def test_correct_html_rendered_on_error_code(self): """Test if correct template and error code exists in response after http errors """ for i in range(len(self.status_codes)): with self.subTest(i=i): response = self.client.get('/' + str(self.status_codes[i]) + '/') self.assertTemplateUsed(response, self.templates[i]) self.assertContains( response, self.user_messages[i], status_code=self.status_codes[i], html=True ) In above code, settings are not overriden and I get 404 for all the urls. Following is the code which … -
how to filter posts in which substring of a field is included in a given list of strings in django?
I have a list of strings as below: items = ['apple', 'shoes', 'milk', 'blue', 'black', 'phone'] and a field in my django model field which has strings separated by (,)comma like below: tag = 'apple, phone, tenis, telvision' I want to filter those posts which have at least one item in their tag field which also listed in the given list. This is what I tried but does not give me result: posts = Post.objects.filter(tag__in=items) -
django.urls.exceptions.NoReverseMatch: Reverse for 'rentals-detail' with no arguments not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/$']
I am trying to add url tag to a template and keeps running to this error: django.urls.exceptions.NoReverseMatch: Reverse for 'rentals-detail' with no arguments not found. 1 pattern(s) tried: ['(?P[0-9]+)/$'] I have tried all the suggested solutions but none seems to work. I'm guessing it is an issue with the template or my urls this is the affected template {% extends 'index.html' %} {% load static %} {%block content%} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <div class="row"> {% for rental in rentals %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ rental.main_image.url}}" class="card-img-top" alt=" A photo of the house"> <div class="card-body"> <h5 class="card-title">{{ rental.size}}</h5> <p class="card-text">{{ rental.rent }}</p> <a href="{% url 'rentals-detail' %}" class="btn btn-primary">View</a> </div> </div> </div> {% endfor %} </div> </div> <!-- end of the cards container --> </div> </div> <!-- end of the main content area of the website --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> {% endblock %} my app's urls from django.urls import path from . import views from .views import RentalsDetailView urlpatterns=[ path('',views.rentals_all,name='rental-home'), path(r'<int:pk>/',RentalsDetailView.as_view(),name='rentals-detail') ] my views from django.shortcuts import render from django.views.generic import ListView,DetailView from .models import rentals def rentals_all(request): Rentals=rentals.objects.all().order_by('-date_posted') context={'rentals':Rentals} return render(request,'rentals/home.html',context) class RentalsDetailView(DetailView): model = rentals and my model from … -
ForwardManyToOneDescriptor' object has no attribute 'slug Django using reverse
I want to use reverse in the model to back a URL, which has three slugs. But it gives me an error. my URL is like this: site.com/category/slug/slug/slug ...> site.com/category/mobile/nokia/n95 Error: 'ForwardManyToOneDescriptor' object has no attribute 'slug' Model: from Django.db import models from Django.shortcuts import reverse class Category(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) child_category = models.ForeignKey('self', max_length=150, null=True, blank=True, on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:brands', args=[self.slug]) class Product(models.Model): category = models.ManyToManyField(to=Category, related_name='products') name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) description = models.TextField() class Meta: ordering = ('name', 'available',) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_details', self.category.model.slug, self.category.model.child_category.slug, self.slug) URL: from Django.urls import path from Shop import views app_name = 'shop' urlpatterns = [ path('<slug:brands_slug>/', views.brands, name='brands'), path('<slug:brands_slug>/<slug:product_slug>/', views.products, name='products'), path('<slug:brands_slug>/<slug:product_slug>/<slug:product_details>/', views.details_products, name='product_details'), ] View: def details_products(request, brands_slug, product_slug, product_details): details = Product.objects.filter(category__child_category__slug=brands_slug, category__slug=product_slug, slug=product_details) context = {'details': details} return render(request, 'shop/product_details.html', context=context) -
Django UpdateView is missing a QuerySet
Even if I defined a model in my UpdateView this one keep raising this queryset error and i don't know how to fix this, the error : django.core.exceptions.ImproperlyConfigured: UpdateClient is missing a QuerySet. Define UpdateClient.model, UpdateClient.queryset, or override UpdateClient.get_queryset(). I have never had to define a QuerySet in my UpdateView before, so I dont get why it is asking for one now. models.py class User(AbstractUser): is_logisticien = models.BooleanField(default=False) is_client = models.BooleanField(default=False) is_livreur = models.BooleanField(default=False) class Adresse(models.Model): adresse = models.CharField(max_length=256) complement_adresse = models.CharField(max_length=256, blank=True) code_postal = models.CharField(max_length=256) ville = models.CharField(max_length=256) def __str__(self): return f'{self.adresse}, {self.code_postal} {self.ville}' class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='client') adresse = models.OneToOneField(Adresse, on_delete=models.CASCADE, related_name='client') entreprise = models.CharField(max_length=256) def __str__(self): return self.entreprise forms.py class AdresseForm(forms.ModelForm): class Meta: model = models.Adresse fields = '__all__' class UserForm(forms.ModelForm): class Meta: model = models.User fields = ('first_name', 'last_name', 'email') class ClientForm(forms.ModelForm): class Meta: model = models.Client fields = ('entreprise',) class ClientMultiForm(MultiModelForm): form_classes = { 'user': UserForm, 'adresse': AdresseForm, 'client': ClientForm } views.py class CreateClient(CreateView): success_url = reverse_lazy('web_app:client-list') template_name = 'web_app/Client/create.html' form_class = forms.ClientMultiForm def form_valid(self, form): user = form['user'].save(commit=False) user.username = fonctions.username_generator() password = fonctions.password_generator() user.set_password(password) user.save() adresse = form['adresse'].save() client = form['client'].save(commit=False) client.user = user client.adresse = adresse client.save() return super(CreateClient,self).form_valid(form) … -
How to set an order on an embedded field in the Djongo?
I want to set an order_by on an embedded field using Djongo module. How could I make this query using Djongo module when I use of MongoDB database. -
Why I get ERR_HTTP2_PING_FAILED on file upload to server with slow internet?
I'm using the Angular app as a frontend and Django rest framework for backend service and Gunicorn application server to interface with my application and Nginx to reverse proxy to Gunicorn to its security and performance features to serve my app. There is one request for uploading the file to the server and it fails when the file is large (about 100mb) and the internet is slow and everything is fine with small files (under 10mb). Here are errors that I get net::ERR_TIMED_OUT net::ERR_HTTP2_PING_FAILED net::ERR_CONNECTION_RESET Here is my Nginx config: location ~ ^(/upload_video/[^/]+) { keepalive_timeout 128; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; client_max_body_size 100M; proxy_pass http://unix:/run/gunicorn.sock; } And here is my Gunicorn service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/rest_api ExecStart=/home/ubuntu/hediehchi_rest_api/myenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --timeout 180 \ --bind unix:/run/gunicorn.sock \ webapp.wsgi:application [Install] WantedBy=multi-user.target What's the problem? comment below if any information needs to be added. -
How to add multiple objects id in Django foreign key field?
Suppose I have a model like as My model.py: class MyMenu(models.Model): title = models.CharField(max_length = 100, blank=True, null=True) user_role = models.ForeignKey(UserRole) I want to set multiple objects in the user_role field. like as user_role = [1,2,3,4....] How is it possible? please anybody help me to solve the problem -
how to make a dynamic url redirect using django after google authentication
By using Django framework I built multiple store based website, each having different slug. http://127.0.0.1:8000/app/<slug:slug> I want to open a google authentication when we visit the above URL. After the verification is complete I want to redirect them to http://127.0.0.1:8000/app/<slug:slug>/shopitems I had successfully implemented google authentication with static URL but not dynamic (using slug variable) like the above. -
PasswordResetConfirmView..as_view() in Django redirect to Django administration site
I am using Django 3 to develop a website where password reset has done through e-mail conformation. After clicking the link in the email, it takes to the Django Administration Password reset confirmation page, rather taking me to the my developed web page. I am following Django 3 by example book. These codes is from chapter 4 of this book. Please help. Thanks in advance. Here is the project GitHub link. Here is the urls.py of the app (named as "account") urlpatterns = [ #path('login/', views.user_Login, name='login'), # Log-in and Logout path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('',dashboard,name='dashboard'), # change password urls path('password_change/',auth_views.PasswordChangeView.as_view(),name='password_change'), path('password_change/done/',auth_views.PasswordChangeDoneView.as_view(),name='password_change_done'), # reset password urls path('password_reset/',auth_views.PasswordResetView.as_view(),name='password_reset'), path('password_reset/done/',auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm'), path('reset/done/',auth_views.PasswordResetCompleteView.as_view(template_engine='accounts/password_change_form.html'),name='password_reset_complete'), ] settings.py INSTALLED_APPS = [ 'account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',] LOGIN_REDIRECT_URL = 'dashboard' LOGIN_URL = 'login' LOGOUT_URL = 'logout' templates/registration/login.html {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content%} <h1>Log-in</h1> {% if form.errors %} <p> Your username and passwoed didn't match. Please try again. </p> {% else %} <p>Please, use the following form to log-in:</p> {% endif %} <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <p><a href="{% url "password_reset" %}">Forgotten your password?</a> </p> <input … -
Converting a gif to webp in pillow saves the first frame only
I'm trying to convert a gif to webp, but it's not animated anymore it just shows the first frame, how to fix that? here's my code: def make_(image): im = Image.open(image) im_io = BytesIO() im.save(im_io, format='WEBP') name = image.name name = name.replace('.gif', '.webp') webp = InMemoryUploadedFile(im_io, 'ImageField', name, 'image/webp',sys.getsizeof(image), None) return webp and also I don't think replacing .gif with .webp in name = name.replace('.gif', '.webp') is the best approach, so if youu have any suggestions to fix that without using os. THANKS -
Implement logging in Angular application with django framework [closed]
I have created application in Angular. Now I want to implement logging to the application with use of django framework. I want to store my users and all database information in SQLite. What to look for in documentation if I want to shoot HTTP requests from Angular to Django to get users information and all other stuff? Or is there any more efficient way to create backend API for Angular application? I wanted to use Django Framework because it has already implemented users and permissions. Also I want to have secure connection so I want to know how to do it. -
comparison page for products in django
I created a comparison page for products. I compare three products, the first product is selected when the user requests a comparison and directs the user to the comparison page, I can also select the second product, but when I select the third product, the information about the second product from Will be deleted Also, if I select the third product, the information about the second product will be deleted. What should I do to save the information after submit the form? (So that the previous form information is not deleted by selecting the next form) view: def test(request, id): products = get_object_or_404(Product, id=id) new = Product.objects.filter(category__cat__name=products.name) if request.method == 'POST' and 'data1' in request.POST: product_id = request.POST.get('data1') filter = Product.objects.get(id=product_id) return render(request, 'home/new.html', {'products': products, 'filter': filter, 'new': new}) if request.method == 'POST' and 'data2' in request.POST: product2 = request.POST.get('data2') filter2 = Product.objects.get(id=product2) return render(request, 'home/new.html', {'products': products, 'filter2': filter2, 'new': new}) else: return render(request, 'home/new.html', {'products': products, 'new': new}) template: <div class="row"> <div class="col-4"> <div class="card bg-info p-5"> <h2>{{ products.name }}</h2><br><br> <p>{{ products.unit_price }}</p><br> <p>{{ products.discount }}</p><br> <p>{{ products.collection }}</p><br> <img src="{{ products.image.url }}" style="width: 200px; height: 200px" alt=""> <a href="{% url 'home:details' products.id %}"> <button type="submit" class="btn … -
Django channels not connecting client using Nginx
I'm trying to deploy a Django app that uses Django Channels. I deployed the app using Nginx and Gunicorn, since i want Daphne to handle only all the Websocket-related stuff. I created a systemtl service for daphne, here it is: [Unit] Description=Daphne service After=network.target [Service] PIDFile=/run/daphne/pid User=root Group=root WorkingDirectory=/django-vue-mpa ExecStart=/django-vue-mpa/venv/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 django_vue_mpa.asgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-abort PrivateTmp=true [Install] WantedBy=multi-user.target And here is my actual nginx conf: server { listen 80; server_name http://138.68.97.153/; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /django-vue-mpa/django_vue_mpa; } location / { include proxy_params; proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock; } } The problem is that every time i try to connect to a websocket consumer i get a TIMED OUT error. What do i need to edit in my nginx config file in order to handle websocket requests to Django Channels? Any advice is appreciated! -
Is it possible to next lookup fields in Django RestFramework?
Suppose I have a model with a ManyToManyField and would like to add or remove entries using the drf. Is there a way to nest these so that the endpoint url looks like mainmodel/{mainmodel_id}/many_to_many_name/{entry_id}? I tried using 'lookup_fields' as class parameter, which didn't work and nesting Viewsets like this: class MainModelAPI(viewsets.GenericViewSet): model = MainModel serializer_class = MainModelSerializer queryset = MainModel.objects.all() lookup_field = 'mainmodel_id' class SubModel(viewsets.GenericViewSet): model = SubModel lookup_field = 'entry_id' ... But both obviously didn't work. I searched the API but didn't find any reference for "nesting viewsets" or "multiple lookup fields / ids". -
runtests.py after install and cloning django in linux terminal
I don't know if I've gone wrong somewhere. But ive cloned and activated django in the linux terminal on my chromebook. It says it can take a while for the runtests.py to complete but it's my second attempt and i'm getting endless periods and random 's' was being thrown in every so often. I'm not very good with the linux terminal and I have only the past hour started trying to understand django. But this is currently what my terminal looks like and it is never ending: ..............................................................................................................................................................................................................................................ssssssssssssssssssssssssssssssssssss...................................s..s........................................s............................s...........s.sss...s......................................................................................................................sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss.s................................sss..............................................................................................................................s.........s.......ss..................s......................................s...................s.........s.s...s...s.s.......s.s......s..s.....................................s.......................................................................................... Have I gone wrong somewhere? Everything else seemed to work fine (I am following a tutorial). Sorry if I sound like an idiot -
Get fields of foreign key in serializer django
I'm 2 weeks into django so this might be dumb! In my django project, I have 3 models, Teacher, Student and a CustomUser. CustomUser has 2 fields first_name and last_name. Student has 3 fields grade, field_of_study and user which is a foreign key to CustomUser. Now inside my StudentSerializer I want to serialize first_name, last_name, grade and field of study. But because the last 2 field are not direct fields of Student, I cannot do that. Anyone know how this should be handled? I also came across this Retrieving a Foreign Key value with django-rest-framework serializers but the answer didn't help really. -
Logging Errors not going to correct file
I`m currently working with Django and the errors are not going to error_log, but they are going to log. The settings are: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', 'datefmt' : "%d/%b/%Y %H:%M:%S", }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s', 'datefmt' : "%d/%b/%Y %H:%M:%S", }, }, 'handlers': { 'file': { 'level': 'INFO', #'class': 'logging.FileHandler', 'class':'logging.handlers.TimedRotatingFileHandler', 'when': 'D', 'filename': os.path.join(BASE_DIR, 'logs', 'log'), 'formatter': 'simple', }, 'error_file': { 'level': 'ERROR', #'class': 'logging.FileHandler', 'class':'logging.handlers.TimedRotatingFileHandler', 'when': 'D', 'filename': os.path.join(BASE_DIR, 'logs', 'error_log'), 'formatter': 'simple', }, 'console':{ 'level': 'INFO', 'class':'logging.StreamHandler', 'formatter': 'simple', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True, }, 'error_file': { 'handlers': ['console', 'error_file'], 'level': 'ERROR', 'propagate': True, } }, } Can someone help me understand why is that? I was looking for it and did not find the error. Django documentation: "It isn’t enough to just put logging calls into your code. You also need to configure the loggers, handlers, filters, and formatters to ensure you can use the logging output. Python’s logging library provides several techniques to configure logging, ranging from a programmatic interface to configuration files. By default, Django uses the dictConfig format. In order … -
Braintree Payment store_in_vault: false not working
I'm using Python and Braintree with the Drop-In. I try to not store a credit card in the vault, but the option seems to get ignored. Here is my code: result = gateway.transaction.sale({ "amount": order.total_amount, "payment_method_nonce": request.data.get('nonce', 'none'), "options": { "submit_for_settlement": True, "store_in_vault_on_success": False }, }) Although the option is set to false after a successful payment (sandbox) and a page refresh the payment method is stored. -
django makemigrations command takes too long because of directory node_modules
I put the frontend code inside my django project. When I execute makemigrations command using manage.py , django simply stuck at '''Tracking file by folder pattern: migrations''' and takes much time to finish. I have to remove the node_modules directory in the front-end source code dir to make 'makemigrations' to function again. Is there a workaround so that I can make manage.py ignore the node_modules directory so it can run makemigrations? -
I'm getting a NoReverseMatch error but I think my files are valid
From my base.html: <div id="button_container"> <button class="button"><a href="{% url 'home' %}"> HOME </a></button> <button class="button"><a href="{% url 'rooms' %}"> ROOMS & SUITES </button> <button class="button"><a href="{% url 'roomBookingsList' %}"> ROOM BOOKINGS </button> </div> Urls.py: path('rooms/mybooking', views.roomBookingsList, name='roomBookingsList'), Views.py: def roomBookingsList(request): suiteBookingList = Suite_booking.objects.all() context = { 'suiteBookingList': suiteBookingList, } return render (request, 'roomBookingsList.html', context=context) roomBookingsList.html: {% for suiteBookingList in suiteBookingList %} <li> {{ suiteBookingList }}</li> {% endfor %} So when I run it and click the ROOM BOOKINGS from the base.html, it will show me whatever rooms I have booked. No problem here. I also want to add an edit button here so I can update the booking if I accidentally typo the name or something. So I added in the roomBookingsList.html: {% for suiteBookingList in suiteBookingList %} <li> {{ suiteBookingList }}</li> - <a href="{% url 'edit_suite' suite.id %}">Edit</a> {% endfor %} Added in urls.py: path('rooms/suite/edit/<int:suite_id>', views.edit_suite, name='edit_suite'), Added in views.py: def edit_suite(request, suite_id): if request.method == 'POST': suite = Suite_booking.objects.get(pk=suite_id) form = BookingForm(request.POST, instance=suite) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('roomBookingsList')) else: suite = Suite_booking.objects.get(pk=suite_id) fields = model_to_dict(suite) form = BookingForm(initial=fields, instance=suite) context = { 'form': form, 'type': 'edit', } return render(request, 'roomBookingsList.html', context=context) Then I tried to run it again, … -
how to write 3 dependant table join query in Django
I am new in django , I want to create join query in django, my model is as follow Model.py Class area_country(models.Model): country_id = models.AutoField(primary_key=True) country_name = models.CharField(max_length=100, null=True) short_name= models.CharField(max_length=20, null=True) flag_enable = models.SmallIntegerField() class Meta: db_table = "area_country" class area_state(models.Model): state_id = models.AutoField(primary_key=True) state_name = models.CharField(max_length=100, null=True) short_name = models.CharField(max_length=20, null=True) country_id = models.ForeignKey(area_country, on_delete=models.CASCADE) flag_enable = models.SmallIntegerField() class Meta: db_table = "area_state" class area_city(models.Model): city_id = models.AutoField(primary_key=True) city_name = models.CharField(max_length=100, null=True) short_name = models.CharField(max_length=20, null=True) state_id = models.ForeignKey(area_state, on_delete=models.CASCADE) flag_enable = models.SmallIntegerField() class Meta: db_table = "area_city" i need query like SELECT "area_country"."country_id", "area_country"."country_name", "area_state"."state_id", "area_state"."state_name", "area_city"."city_id", "area_city"."city_name" FROM "area_country" LEFT OUTER JOIN "area_state" ON ("area_country"."country_id" = "area_state"."country_id_id") LEFT OUTER JOIN "area_city" ON ("area_state"."state_id" = "area_city"."state_id_id") ** Try by me ** view.py result = area_country.objects.all().select_related('area_state').values('country_id', 'country_name', 'area_state__state_id', 'area_state__state_name') when i print it by using query = result.query SELECT "area_country"."country_id", "area_country"."country_name", "area_state"."state_id", "area_state"."state_name" FROM "area_country" LEFT OUTER JOIN "area_state" ON ("area_country"."country_id" = "area_state"."country_id_id") this is ok now i try result = area_country.objects.all().select_related('area_state').select_related('area_city').values('country_id', 'country_name', 'area_state__state_id', 'area_state__state_name','area_city__city_id','area_city__city_name') it show me error Cannot resolve keyword 'area_city' into field. Choices are: area_state, country_id, country_name, flag_enable, short_name please help me. -
Hyperlinks in Django for loop are linking to the same page
On a user's profile page right now it is displaying the number of people they are following and the usernames of the people they are following. When the user clicks on a username, I quite simply want it to take the user to that user's profile page but right now it is linking back to the same user's profile page, so essentially just reloading the page. I am guessing it is because I am passing in user.username as a keyword argument because when I follow this same format but instead using user.id I don't run into this problem. I would like to use user.username so that the username can be displayed in the url. profilePage.html {% block body %} <h3>{{ user.username }}</h3> <br> <br> <p>{{ profile.number_of_friends }}</p> <p>{% for friend in profile.get_friends %}</p> <a href="{% url 'profile' profile.user.username %}">{{ friend }}</a><br> {% endfor %} {% endblock %} views.py def profile_page(request, user_username): profile = get_object_or_404(Profile, user__username=user_username) return render(request, "network/profilePage.html", { "profile": profile }) urls.py path("profile/<str:user_username>", views.profile_page, name="profile"), models.py class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) -
Django Channels after sending message, current tab showing 2 messages(sender + receiver) but other tab does not show anything?
I am following this tutorial Channels Tutorial Link My Goal was to make a simple asgi chat server. But It is showing weird behaviour. The message sent from one tab..should print "HI" in current tab..and also "HI" in the tab connected in the same room. but its printing the both "HI" in the current tab, no message is shown in the other tab connected in the same room. my consumers.py is simeple, just from the tutorials file... import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) my settings file is configured to receive redis connection in 127.0.0.1. I am using docker redis image just s the tutorial said. ASGI_APPLICATION = 'mysite.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': … -
How to add a gitignore folder to github actions?
I have a Django Project and created a dev branch. In my .gitignore file I have the "media" folder. My project looks like this: - Django Project/ - app1/ - app2/ - media/ - profile_pics/ - default.jpg - .gitignore In my gitignore I added media. I've been trying to add github actions, so I created this ci.yml name: Testing on: push jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.6, 3.7, 3.8] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test When I push the repo I received this message from Github Actions: FileNotFoundError: [Errno 2] No such file or directory: '****/media/default.jpg' What is the best way to deal with this? I could use git add media -f but I do not know if then this file would be in my repo and when I merge it with main and deploy it I would have that folder and overwrites the media in deployment.