Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter Products by category when category page loads angular
I have a angular webapp that displays all the categories from the category model. The category model is a foreign key the products model. I want to be able to filter and view all the products that has that category when I click and load that specific category view. When I click on a category at the minute it takes me to a details page where I can see the category name, image and description. I can also see all of the products in my DB within that details view. I want to filter these so that only the products that contain that specific category in its foreign key field will be shown in the category details view rather than all of the products. If anyone could help me out here it would be greatly appreciated! Here is what I have so far: department.component.ts import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CookieService } from 'ngx-cookie-service'; import { ApiService } from 'src/app/api.service'; import { Category } from '../../models/Category'; import { Product } from '../../models/Product'; @Component({ selector: 'app-department', templateUrl: './department.component.html', styleUrls: ['./department.component.css'] }) export class DepartmentComponent implements OnInit { categories: Category[] = []; … -
NGINX HTTP 499s with AWS NLB & Gunicorn _ Django
I am running a NGINX + Gunicorn setup to serve my Django app from AWS EC2s, which have a Network Load Balancer on the front. Recently I have been getting a lot of HTTP 499s from my NGINX, all of them continuous and not a one-off. AWS Network Load Balancers have a fixed idle timeout of 350s, which cannot be modified I believe. All my NGINX timeouts are set at 600. What else can be the reason for this? Below is my NGINX config user <someuser>; worker_processes auto; error_log /var/log/<somedir>/nginx_error_main.log; pid /var/run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/<somedir>/nginx_access_main.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 600; types_hash_max_size 2048; proxy_ignore_client_abort on; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; index index.html index.htm; # Enable upgrading of connection (and websocket proxying) depending on the # presence of the upgrade field in the client request header map $http_upgrade $connection_upgrade { default upgrade; '' close; } # Create an upstream alias to where we've set daphne to bind to upstream … -
Django login problem which is being linked with the admin side
I am working on a Django project and have implemented login and logout functionalities. The project is a job portal. When I login as a recruiter, previously I was able to open another tab in my browser and use the django admin panel. Now, whenever I do that, it says that I am logged in as my recruiter email address and I have to log in using another account. Now, when I log in using my admin credentials, simultaneously, I am being logged in on my website using my admin credentials which I have never registered on the site. Why am i getting this??? Thank you for your reply guys. This has impeded my work progress since hours -
How can i put the commas for urls when i need 3 differents on javascript?
How can i put the commas? Hello im trying to insert a image with a JavaScript append funtion. Loading the static folder from Django and i cant quotation the url imagen (needed where are ##) because im using '' to delimiter the line of js and "" to delimiter src="" tag for html: '<a href="#" class=""><img src="{% static ##images/img_1.jpg## %}" alt="Image" class="img-fluid coche-img"></a>' What can i do? Can i put 3 different commas? -
How do I restrict access in django?
I have an application in which all users, after registration, can publish articles, how can I make it so that only those who have the rights for this can publish (something like ordinary users and moderators / editors and how to grant these rights. Below is the attached code: models.py/blogapp class Post(models.Model): title = models.CharField(verbose_name=("Заголовок"), max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) header_image = models.ImageField(verbose_name=("Заглавное Изображение"), null=True, blank=True, upload_to="images/" ) body = RichTextField(verbose_name=("Тело Статьи"), blank=True, null=True) #body = models.TextField(blank=True, null=True) post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(verbose_name=("Категория"), max_length=200) snippet = models.CharField(verbose_name=("Фрагмент Статьи"), max_length=200) likes = models.ManyToManyField(User, related_name='blog_post') updated_on = models.DateTimeField(auto_now= True) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) views.py/members class CreateProfilePageView(CreateView): model = Profile form_class = ProfilePageForm template_name = "registration/create_user_profile.html" #fields = '__all__' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class EditProfilePageView(generic.UpdateView): model = Profile template_name = 'registration/edit_profile_page.html' fields = ['bio', 'profile_pic', 'website_url', 'instagram_url', 'twitter_url', 'status', 'age'] success_url = reverse_lazy('home') class ShowProfilePageView(DetailView): model = Profile template_name = 'registration/user_profile.html' def get_context_data(self, *args, **kwargs): #users = Profile.objects.all() context = super(ShowProfilePageView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(Profile, id=self.kwargs['pk']) context["page_user"] = page_user return context class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangingForm #form_class = PasswordChangeForm success_url = reverse_lazy('password_success') … -
How to migrate MyIsam to InnoDB with relation (Foreign key constraint is incorrectly formed)?
Previously, the attribute_values table had an int attribute_id field. I want to convert it to a ForeignKey to the attributes table, but I get the error "Foreign key constraint is incorrectly formed" (also the tables used to be MyIsam, I converted them to InnoDB). The migration looks like this: operations = [ migrations.RemoveField( model_name='attributevalue', name='attribute_id', ), migrations.AddField( model_name='attributevalue', name='attribute', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='attributes.attribute'), ), ] atrributes attribute_values -
Building elasticsearch indexes from another container
I have a Django project that uses django-elasticsearch-dsl. The project is dockerized, so elasticsearch and the web projects leave in separate containers. Now my goal is to recreate and repopulate the indices running python manage.py search_index --rebuild In order to do that, I try to run the command from the container of the web service the following way: docker-compose exec web /bin/bash > python manage.py search_index --rebuild Not surprsiginly, I get an error Failed to establish a new connection: [Errno 111] Connection refused) apparently because python tried to connect to elasticsearch using localhost:9200. So the question is, how do I tell the management command the host where elasticsearch lives ? Here's my docker-compose.yml file: version: '2' services: web: build: . restart: "no" command: ["python3", "manage.py", "runserver", "0.0.0.0:8000"] env_file: &envfile - .env environment: - DEBUG=True ports: - "${DJANGO_PORT}:8000" networks: - deploy_network depends_on: - elasticsearch - db elasticsearch: image: 'elasticsearch:2.4.6' ports: - "9200:9200" - "9300:9300" networks: - deploy_network db: image: "postgres" container_name: "postgres" restart: "no" env_file: *envfile ports: - "5432:5432" volumes: - db_data:/var/lib/postgresql/data volumes: db_data: networks: deploy_network: driver: bridge UPDATE: In the Django project's settings I setup the elasticsearch dsl host: # settings.py ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' } } -
(M1 Mac) Geodjango GDAL: mach-o, but wrong architecture
I am trying to get GeoDjango running on mac os and have hit a problem with GDAL. I have downloaded and installed GDAL without problem (Gdal Complete Binary) also installed from homebrew too. Unfortunately when i was installed gdal with homebrew django can't find the gdal and throws gdal did not find error, after that. I installed from KyngChaos GeoDjango Binary django find gdal but now throws that; OSError: dlopen(/Library/Frameworks/gdal.framework/gdal, 6): no suitable image found. Did find: /Library/Frameworks/gdal.framework/gdal: mach-o, but wrong architecture /Library/Frameworks/gdal.framework/gdal: mach-o, but wrong architecture /Library/Frameworks/GDAL.framework/Versions/3.1/GDAL: mach-o, but wrong architecture /Library/Frameworks/GDAL.framework/Versions/3.1/GDAL: mach-o, but wrong architecture I think the Kyngchaos build not compaitable with arm platform Any help would be much appreciated. Django Version : 3.0 also tried 3.2 Gdal Version : 3.2/3.1/2.4 All of them tried Python Version: 3.8 Postgresql Version : 13 Postgis/Geos installed gdal-config --libs: -L/opt/homebrew/Cellar/gdal/3.2.2_3/lib -lgdal -
Error while executing Pylint command from terminal on Django Project directory
When i run the below command from my terminal i end up getting the below error, i am running this pylint on my django-project. (venv) mypc:~/path/django-project$ pylint --rcfile=.pylintrc ./* > lint_ouput.txt Error: Traceback (most recent call last): File "/usr/lib/python3.6/tokenize.py", line 390, in find_cookie line_string = line.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfa in position 9: invalid start byte pylint.exceptions.InvalidMessageError: Message E0001 must provide line, got None -
Will a class work good without being a model in Django?
I'm currently developing an app which requires simple otp authentication using django In models.py of an app accounts I've created a class to store the otp without making it as a model as follows, class temp: def __init__(self,otp): self.otp = otp print(self.otp) In views.py the code goes as, g = globals() ... some code g["user"+ str(request.POST['username'])] = models.temp(the_otp) This works completely fine in localhost, Will this work if I deploy this to heroku. If not suggest some other way to store the otp temporarily without making models. Thanks in advance. -
django_migrations outputs ORA-02000: missing ALWAYS keyword?
when i try to run python manage.py migrate command i get the following error raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-02000: missing ALWAYS keyword) Note: I can read and write to oracle database nd using pycharm IDE. Thanks. -
How I can join two ManyToManyField number to Integer Field in Django
I want to get the numbers of values in Two ManyToMany Field and compain both to one Integer Field by function (def) class Video(models.Model): viewers = models.ManyToManyField(Account, related_name='video_views') viewers_by_ip = models.ManyToManyField(UsersByIP, default='192.168.0.1', blank=True) viewers_count = models.IntegerField('Here I want to get the number of both field') -
Is there a django messaging library that actually works?
I have tried now almost all django one to one messaging systems Pinax_messages Django_messages None seem to work. -
'User' object has no attribute 'password_2'
I'm getting this error when I'm trying to register an user. The thing is, password_2 is just a field to check if the password was well written by the user (it'll return an error if they don't match). Therefore, password_2 is not in the model because it does not need to be stored along with the actual password. So I get this error because I added the field to my serializer. How can I solve it? This is the model: class UserManager(BaseUserManager): @transaction.atomic def create_user(self, email, username, password=False): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() return user def get_by_natural_key(self, username): return self.get(username=username) def create_superuser(self, username, password, email): user = self.create_user( username=username, email=email, password=password, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name= 'username', max_length= 50, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return str(self.username) This is the serializer: class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) email = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) password = serializers.CharField( required=True, … -
How do I prevent template tags from loading when template is cached?
I have an HTML file that I'm caching with {% cache %} template tag. In order to render the template, I'm loading several template tags: {% load static l10n ... etc %}. I do not want these to load when the template is cached. Would moving this load statement inside {% cache %} tag prevent them from loading if template is in cache? Example: {% cache TTL PRODUCT product.id %} {% load static l10n %} ... html code ... {% endcache %} -
Django - Get count of child objects associated with the Parent object
I am trying to get the count of existing child objects associated with the Parent object. I have a Parent Model like: class ParentObj(models.Model): name = .CharField(verbose_name='Name', max_length=50) Now I have these Child models. class ChileObj1(models.ParentForm): parent = models.ForeignKey(Product) name = models.CharField(verbose_name='Name', max_length=50) class ChileObj2(models.ParentForm): parent = models.ForeignKey(Product) name = models.CharField(verbose_name='Name', max_length=50) class ChileObj3(models.ParentForm): parent = models.ForeignKey(Product) name = models.CharField(verbose_name='Name', max_length=50) Now it could be that there are only two child objects for the parent object, instead of 3. How can get a count of them using a query. TIA -
I accidentally, deleted table of a model in db.sqlite (manually). How can I recreate it?
I accidentally, deleted table of a model in db.sqlite. How can I recreate it? When I run command 'python manage.py makemigrations' it works but when I run'python manage.py migrate' it says 'No migrations to apply' -
How can i put the commas?
Hello im trying to insert a image with a JavaScript loading the static folder from Django and i cant put the commas for the imagen (needed where are ##): '<a href="#" class=""><img src="{% static ##images/img_1.jpg## %}" alt="Image" class="img-fluid coche-img"></a>' What can i do? -
Session lost and user logs out on external redirect from payment gateway in Django Oscar
I've integrated a 3rd party payment gateway in Django Oscar. On checkout user is redirect to Payment Gateway where user fills payment details and on successful payment, the payment gateway post back success response to my custom URL on my website. But when I receive the response, user becomes anonymous, session data is lost and user is logged out of the website on redirect to ThankYou page. Please guide me if someone has solved this issue before. Thanks. -
got page not found error with url in django
This is urls.py: urlpatterns = [ path('', views.first_page.as_view(), name='first_page'), path('all_ads/', views.all_ads.as_view(), name='all_ads'), re_path(r'^all_ads/(?P<pk>\d+)/$', views.all_ads.as_view(), name='all_ads_filtered'), re_path(r'^ads_detail/(?P<pk>\d+)/$', views.AdsDetailView.as_view(), name='ads_detail'), ] I have this link in template.html: <a href="/ads_detail/?source_token={{Catalogue.source_token}}"></a> that returns a link like this: /ads_detail/?source_token=AYFWWw1k But, I got page not found error. -
Uncaught TypeError Cannot read property 'call' of undefined Bootstrap 5 , Django
I am using bootstrap5 with my Django project {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Doc</title> <link rel="stylesheet" href="{% static "css/bs/bootstrap.min.css" %}"> <link rel="stylesheet" href="{% static "css/selectBox.css" %}"> <link rel="stylesheet" href="{% static "css/style.css" %}"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Oswald&display=swap" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% block css %} {% endblock %} </head> <body> {% block content %} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> </body> <script src="{% static "js/index.js" %}"></script> {% block js %} {% endblock %} </html> First I downloaded the bootstrap 5 js and css files and used as static file <head> <link rel="stylesheet" href="{% static "css/bs/bootstrap.min.css" %}"> </head> <body> <script src={% static "js/bs/bootstrap.bundle.min.js" %}></script> </body> Bootstrap 5 css is working perfectly but javascript is not working, I am trying to make a dropdown button, the dropdown is not working. Whenever I click drop down this errors are showing up selector-engine.js:18 Uncaught TypeError: Cannot read property 'call' of undefined at Object.find (selector-engine.js:18) at carousel.js:608 at i (event-handler.js:101) find @ selector-engine.js:18 (anonymous) @ carousel.js:608 i @ event-handler.js:101 load (async) C @ event-handler.js:196 on @ event-handler.js:224 (anonymous) @ carousel.js:607 (anonymous) @ bootstrap.bundle.min.js:6 (anonymous) @ bootstrap.bundle.min.js:6 selector-engine.js:18 Uncaught TypeError: Cannot read property 'call' of … -
how to update some fields of an object if it exists? django
I've made a project for a store sometimes happen for example we have :product = mouse , quantity=100 , buying_price = 10$ , in another time we add the same kind of product(mouse) in this case we have to prevent from creating another object quantity = 120,buying_price=12$ , in this situation i expect to (100 * 10+120 * 12)/220 in order to get the buying average . i have to implement this : ((quantity * buying_price + new quantity * new buying_price)/quantity + new quantity) class Item(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() buying_price = models.DecimalField(max_digits=30,decimal_places=3) views.py def createNewProduct(request): form = ItemForm() if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): form.save() return render(request,'temp/add_item.html',{'form':form}) database : mysql -
how to make syntax highlighting on a website for your own language on django?
I'm making a website in django and I need to implement syntax highlighting of the LibSl language( currently this language is not used anywhere, so I need to do it myself). Are there any libraries on Django that could do this? I use html templates Django enter image description here -
Can't embedded a django backend html in a angular front-end
As mentioned in the question, I am trying to embed an html form web page located in a django backend in a front-end (maked with angular, in another server), but when I acces to the front-end page (where the backend page is embedded) the following error appears: [Error] Blocked autofocusing on a form control in a cross-origin subframe. [Error] Blocked a frame with origin "https://...{backend address}..." from accessing a frame with origin "http://...{frontend address}...". The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match. (x8) [Error] Refused to display 'https://...{backend address}.../register_student' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. [Error] Failed to load resource: the server responded with a status of 403 () (register_student, line 0) So in order to solve the problem I modificate settings.py file by adding MIDDLEWARE = [ ... 'django.middleware.clickjacking.XFrameOptionsMiddleware', ... ] SESSION_COOKIE_DOMAIN=".ynsat.com" X_FRAME_OPTIONS = 'SAMEORIGIN' And I also modificate views.py with the follow signal: @xframe_options_exempt def register_student(request): ... The thing is the frontend page shows the iframe correctly, but when it send the form the error shown above appears. Here is my code: views.py ... @xframe_options_exempt def register_student(request): if request.method == 'POST': form … -
django - testing send_mail function in a view
I'm trying to test a send_mail function which is placed in the following view (skip to the end to see the send_mail execution): @login_required def item_create(request, idType, idSubType=None): type = Type.objects.get(id=idType) form = item_Form(request.POST or None) form.fields['subType'].queryset = SubType.objects.filter(type=type).order_by('name') if idSubType: form.fields['subType'].initial = SubType.objects.get(id=idSubType) form.fields['company'].queryset = request.user.profile.companies context = { 'form': form, 'title': 'INSERIMENTO ' + type.name.upper(), # primo tab dei dati anagrafici 'tab_active_1': True, } form_specs = None if type.name == 'Mezzi' and idSubType: subType = SubType.objects.get(id=idSubType) specs_name = subType.subTypeGroup.name form_class = getattr(forms, specs_name + 'Form') form_specs = form_class(request.POST or None) context['form_specs'] = form_specs context['title_specs'] = 'Dati Specifici ' + subType.name if request.method == 'POST': if form.is_valid(): if form_specs: if form_specs.is_valid(): item = form.save() specs = form_specs.save(commit=False) specs.item = item specs.save() else: return render(request, 'equipment/item_detail.html', context) else: item = form.save() mail_context = { 'base_url': settings.GESTIONALE_URL, 'subType': item.subType, 'brand': item.brand, 'model': item.model_type, 'serial_number': item.serial_number, 'supplier': item.supplier.legal_name, 'item_abs_url': item.get_absolute_url(), } payload = render_to_string('equipment/mails/new_item_message.html', mail_context) carlo = User.objects.filter(username__icontains='carlo.cogni').first() monica = User.objects.filter(username__icontains='monica').first() send_mail('Avviso inserimento nuova attrezzatura', payload, settings.EMAIL_HOST_USER, (carlo.email, monica.email), html_message=payload) ######### messages.success(request, f'Dati aggiornati correttamente', fail_silently=True) return HttpResponseRedirect(item.get_absolute_url()) else: return render(request, 'equipment/item_detail.html', context) else: form.fields['is_purchased_new'].initial = True return render(request, 'equipment/item_detail.html', context) If the objects is created correctly, an email is automatically sent. …