Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
External API Calls are blocking django view
I am facing a problem. Django view is not rendering until the api calls are fininshed. Here is code below. the following code takes data from google autocomplete api and store it in database. from django.http import HttpResponse, HttpResponsePermanentRedirect from django.shortcuts import redirect, render import requests import uuid import json from api.models import report # Create your views here. headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def index(request): if(request.method == 'GET'): return redirect('/') elif(request.method == 'POST'): var = request.POST['keyword_google'] if(var == ""): return HttpResponse("You should have entered something") else: identifier = str(uuid.uuid4()) insert = report() insert.id = identifier insert.title = var google_autocomplete_url = "https://google.com/complete/search?client=chrome&q=" insert.null_keywords = json.loads(requests.get(google_autocomplete_url+var, headers=headers).text)[1] insert.vs_keywords = json.loads(requests.get(google_autocomplete_url+var+"+vs", headers=headers).text)[1] insert.versus_keywords = json.loads(requests.get(google_autocomplete_url+var+"+versus", headers=headers).text)[1] insert.or_keywords = json.loads(requests.get(google_autocomplete_url+var+"+or", headers=headers).text)[1] insert.and_keywords = json.loads(requests.get(google_autocomplete_url+var+"+and", headers=headers).text)[1] insert.like_keywords = json.loads(requests.get(google_autocomplete_url+var+"+like", headers=headers).text)[1] insert.with_keywords = json.loads(requests.get(google_autocomplete_url+var+"+with", headers=headers).text)[1] insert.near_keywords = json.loads(requests.get(google_autocomplete_url+var+"+near", headers=headers).text)[1] insert.is_keywords = json.loads(requests.get(google_autocomplete_url+var+"+is", headers=headers).text)[1] insert.for_keywords = json.loads(requests.get(google_autocomplete_url+var+"+for", headers=headers).text)[1] insert.to_keywords = json.loads(requests.get(google_autocomplete_url+var+"+to", headers=headers).text)[1] insert.without_keywords = json.loads(requests.get(google_autocomplete_url+var+"+without", headers=headers).text)[1] insert.can_keywords = json.loads(requests.get(google_autocomplete_url+var+"+can", headers=headers).text)[1] insert.why_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=why+"+var, headers=headers).text)[1] insert.where_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=where+"+var, headers=headers).text)[1] insert.who_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=who+"+var, headers=headers).text)[1] insert.when_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=when+"+var, headers=headers).text)[1] insert.will_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=will+"+var, headers=headers).text)[1] insert.are_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=are+"+var, headers=headers).text)[1] insert.which_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=which+"+var, headers=headers).text)[1] insert.can_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=can+"+var, headers=headers).text)[1] insert.how_keywords … -
Django How to check id of ForeignKey?
I have models.py like this. which api_key in table UserKey is ForeignKey to api_key in table DeviceKey. class DeviceKey(models.Model): api_key=models.CharField(max_length=100,unique=True) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.api_key class UserKey(models.Model): api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE) def __str__(self): return self.username The data in table DeviceKey and Userkey show like this code. Table DeviceKey id api_key 1 abc1 2 abc2 Table Userkey id api_key_id 1 1 I want to check if api_key exists in table Userkey but I can't search with text beacause table UserKey keep api_key as id. So, I have to get id from table DeviceKey like this code key="abc2" if UserKey.objects.filter(username=username,api_key_id=DeviceKey.objects.get(api_key=key).values_list('id')).exists(): It show error like this. 'DeviceKey' object has no attribute 'values_list' How to fix it? -
How to skip http headers when receiving and writing file from POST request?
In my Django POST request, I am getting a json file and writing it locally in the server like this: up_file = request.FILES['file'] full_file_path = <my file path> destination = open(full_file_path, 'wb+') for chunk in up_file.chunks(): destination.write(chunk) destination.close() But the file is written like this: ------WebKitFormBoundary2df6tPQtB97uXIt6 Content-Disposition: form-data; name="myFile"; filename="input.json" Content-Type: application/json {"x": 1} ------WebKitFormBoundary2df6tPQtB97uXIt6-- as input.json. Obviously, this is invalid so I want the file to only contain: {"x": 1} How do I make this file writing skip the headers and footers and write only the actual content? -
AssertionError: Template was not a template used to render the response
I'm encountering an issue with my TestCase where it's asserting that the actual template used to render a response doesn't match the template I'm expecting. The error being raised is: AssertionError: False is not true : Template 'posts/question.html' was not a template used to render the response. Actual template(s) used: posts/ask.html, ..., ... Everything after posts/ask.html refers to built-in templates. Sequence of events involved: Click "Ask Question" -> post QuestionForm -> redirect to question page -> click edit -> post question edits -> redirect to question page I cannot pinpoint where or why Django is saying that posts/ask.html is being rendered. As far as I can tell I'm redirecting to the right URL where it's suppose to render posts/question.html. class TestPostEditQuestionPage(TestCase): '''Verify that a message is displayed to the user in the event that some aspect of the previous posted question was edited.''' @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user( username="OneAndOnly", password="passcoderule" ) profile = Profile.objects.create(user=cls.user) tag = Tag.objects.create(name="TagZ") question = Question.objects.create( title="This is Question Infinity", body="The is the content body for This is Question Infinity", profile=profile ) question.tags.add(tag) cls.data = { "title": "This is Question Zero", "body": "The is the content body for This is Question Infinity", "tags": ["TagZ", "TagA"] … -
Django Rest framework - I am trying to convert a property received in Response object to JSON object and iterate through it. But response is string
In views.py VENDOR_MAPPER is list of dictionary each dictionary has id, name, placeholder and autocommit key. I also tried sending json instead of Response object. resp_object = {} resp_object['supported_vendors'] = VENDOR_MAPPER resp_object['vendor_name'] = "" resp_object['create_vo_entry'] = False resp_object['generate_signature_flag'] = False resp_object['branch_flag'] = False resp_object['trunk_flag'] = False resp_object['branch_name'] = "" resp_object['advisory'] = "" data = {'data': resp_object} return Response(data) On home.html I am accessing the vendors_supported which is list and iterate through it, however instead of object i am getting string as type of variable. var supported_vendors = "{{data.supported_vendors|safe}}"; console.log(supported_vendors); console.log("Supported_vendors ", supported_vendors); console.log("Supported_vendors_type:", typeof(supported_vendors)); data.supported_vendors|safe (django template tagging) is used to remove the unwanted characters in the response i have also tried without safe, but still the type was string also tried converted as well as parse the response but type is shown as string var supported_vendors = "{{data.supported_vendors}}"; console.log(JSON.parse(supported_vendors)); console.log(JSON.stringify(supported_vendors)); Output generated, i have printed the response type and values i get, also converting using JSON.parse and JSON.stringify did not work and output every time was string [1]: https://i.stack.imgur.com/DuSMb.png I want to convert the property into javascript object and perform some computations -
Django CreateView Trying to register a client With a specific number that goes from 15 to 15
I am trying to make a small system in which I have to put a client number that goes from 15 to 15, but the truth is that I did not succeed to change a global variable. I am trying to learn how class based views work. I hope you can help me. What I'm looking for is to get the find the last record in the database and add 15 to it. thank you. models.py from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=50) customer_num = models.IntegerField(unique=True) def __str__(self): return self.name views.py from re import template from django.shortcuts import render from aplicacion.models import * from django.views.generic import * from django.http import HttpResponse # Create your views here. class CreateCustomer(CreateView): model = Customer template_name = 'createcustomer.html' fields = ['name'] success_url = "/admin/aplicacion/customer/" aa = Customer.objects.last().customer_num def form_valid(self, form): global aa while True: try: Customer = form.save(commit=False) Customer.customer_num = self.aa print(self.aa, "jjjj") """If the form is valid, save the associated model.""" #form.instance.customer_num = self.request.POST['name'] break aa = self.aa + 15 except: pass return super().form_valid(form) -
How to get total sum in multiple lists using python
[templatetag.py] def total_sum(value): value_list = value[:, 1:] return [sum(i) for i in zip(*value_list)] [html] {% load total_sum from templatetag %} <tr> <td>Monthly Total</td> <td>{{ monthly_enroll_list|total_sum }}</td> <!-- Total (Jan) --> <td>{{ monthly_enroll_list }}</td> <!-- Total (Feb) --> <td>{{ monthly_enroll_list }}</td> <!-- Total (Mar) --> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> </tr> The value of the "monthy_enroll_list" variable is as follows. [['A', 3, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8], ['B', 1, 8, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], ['C', 0, 1, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 2], ['D', 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]] If I remove the index at the beginning and the end of each list, I get the number of enrolls from January to December. I want to get the total sum per month. The values I want to get are: ['6', '10', '12', '6', '0', '0', '0', '0', '0', '0', '0', '0'] But i got the following error: list indices must be integers … -
Django debug tool bar not showing
enter image description here I want to show debug tool bar but it looks like above.. what's wrong? -
Dynamically change values based on user selected option django
I'm trying to change a value based on the exchange rate selected by the user within the <option> tag. I don't want to save the form result to the database. I just want it to dynamically change whenever the user changes the currency option. Say a user selects a currency from the below form with the options in the view: VIEW def view(request): currency_dict = {'EUR': 0.9154994049253867, 'JPY': 123.86706948640484, 'BGN': 1.7905337361530713, 'CZK': 22.375720955781375} cur = currency_dict.items() deposit = 10000 context = { 'currency_dict': currency_dict, 'cur': cur, 'deposit': deposit, } return render(request, 'coinprices/my-dashboard.html', context) HTML - FORM <div class="container"> <div> <span> <h1>My Dashboard</h1> </span> <span> <label>Choose Currency:</label> <input list="ex-currency"> <datalist id="ex-currency"> {% for k, v in cur %} <option value="{{ k }}"></option> {% endfor %} </datalist> </span> </div> </div> Then based on the users selection, multiply the {{ deposit }} value by the currency_dict[user_selected_currency] and change the bold text (see below): DESIRED OUTCOME <span> <div><b>Total Investment {{ user_selected_currency }}</b></div> <span class="text-xl">${{ deposit * currency_dict[user_selected_currency] }}</span> </span> Any ideas how this can be achieved? -
Remove update profile Image url field in django
Does anyone know how to remove the url link -
Connection error with Django and PostgreSQL in Ubuntu Server
I have a virtual machine running ubuntu server and I want to set a connection using Django in my pc and a postgre's database in ubuntu server. This is mi first time developing a database in server and I don't know if this is the correct way. I get this: connection = Database.connect(**conn_params) File "C:\Users\RSSpe\Desktop\ProyectoFinalDjango\entorno_virtual\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "192.168.1.3", port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? I have this in my postgresql.conf file: Connection Settings listen_addresses = "*" # what IP address(es) to listen on; # comma-separated list of addresses; # defaults to 'localhost'; use '*' for all # (change requires restart) port = 5432 # (change requires restart) max_connections = 100 # (change requires restart) This is my pg_hba.conf file: # Database administrative login by Unix domain socket local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all all md5 host all postgres all md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication … -
DJANGO JSON filtering nested value
I am trying to figure out how to filter out JSON in DJANGO when the structure looks like this: some random ID is like random generate id like pad1g12312-421df-2131 "data": { "steps":{ "some random ID":{ "name":"name1" } }, "process":{ "some random ID":{ "name":"PROCESS #1", } } I am trying to figure out how to get the name under execution and operation I tried follow with this post: Django JSONField filtering_ object.filter(data__steps__0__name='name1') object.filter(data__process__0__name='PROCESS #1') but it isn't working. I am assuming it's because the Random ID part doesn't work with the 0. Is there a way to do this? Also, I would like to combine the two in the same filtering, like object.filter(data__steps__0__name='name1' or data__process__0__name='PROCESS #1') Is it possible to do that? Thank you -
Add a FileField path to django
I have a map in my app and im trying to 'paint' some territories with kml files. I can get the outlined version if i hardcode the absolute path but since i have multiple kmls im trying to do it with a for loop with a field.kml.path (kml being the Filefield in my model) as per django instructions but it doesnt work . Any idea how to fix that ? view : def map(request): field_list = models.Field.objects.all() context = { "title": "Map", "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) My original map.html var polygon = omnivore.kml("{% static '../media/kml/Arnissa_cherry.kml' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); New version that doesnt work: {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name var polygon = omnivore.kml("{% static '{{field.kml.path}}' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); {% endfor %} -
Microservices framework for Django?
There are quite a few these frameworks for enterprise level players like Java (and Golang) It's a well known knowledge that many people use Django to implement each service within microservices architecture, but I am looking for something that sits on top of this, a framework of frameworks. Like cookiecutter type. Exposing data We all know to commonly expose a model over rest API is to use DRF, but setting it up is a chore, eg. manually creating ModelViewSet and setting up routers. In an non-public facing environment that assuming no auth needed, for the most basic setup, I just want to use decorator on the model, and it will do all the manual work behind the scene, eg. dynamically creating the viewset and register to urls, similar concept to viewflow's rest framework support. # in accounts app @soa_data_provider(...) class User(models.Model) .... which will default exposes the data in /api/accounts/models/user/ Consuming data Could potentially utilise django-rest-models like @soa_data_consumer(...) class User(models.Model): field = models.IntegerField() ... class Meta: # basic django meta Stuff verbose_name = 'Users' class APIMeta: pass Syncing data Referring to the @soa_data_provider decorator mentioned above, maybe using tools like rabbitmq to publish changes automatically over some convention naming/routes/etc etc, … -
Cannot alter tables after Django migration in posgres DB
I really need to know why in the world we cannot change the column types after we do the migrations to Postgres DB. I already created my models by python manage.py makemigrations then do migrate. Everything looks fine and tables are created on the postgres DB. class test_API(models.Model): IDnumber = models.IntegerField(unique = True, primary_key = True, null=False, editable = False, blank=True) State = models.CharField(max_length = 256, null = True) Exlcludmethod = models.CharField(max_length=256, null=True) class test_API_2(models.Model): Idnumber = models.Foreignkey(test_API, max_length = 256, blank=False, null = False) value = models.CharField(max_length=128, default="") last_updated = models.DateTimeField(auto_now=True) Lets say we want to make change to IDnumber column from Integerfield to Charfield. class test_API(models.Model): IDnumber = models.CharField(null=False, blank=False) State = models.CharField(max_length = 256, null = True) Exlcludmethod = models.CharField(max_length=256, null=True) and run the python manage.py makemigrations again return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "test_API" already exists How can we modify/change column types and do migrations. What is the proper way of doing this ? Using Django:Django==4.0.3 Python = 3.9.1 Posgresql = 2.9.3 Django migrations using RunPython to commit changes django 1.7 migrate gets error "table already exists" -
Duplicating a model while searching
I wrote simple query schare used ListView class: class HomeView(ListView): model = Person template_name = "phones/home_page.html" context_object_name = 'people' def get_queryset(self): query = self.request.GET.get('q') if query: object_list = self.model.objects.filter(Q(name__icontains=query) | Q(surname__icontains=query) | Q(phone__phone__icontains=query) | Q(mail__mail__icontains=query)) else: object_list = self.model.objects.all() return object_list I used 3 models one of them: class Phone(models.Model): person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE, related_name='phone') phone = models.CharField(max_length=50, blank=True) One of 'Q' is in ForeignKey. The problem is when I enter '1' for example, it duplicates the model. example I know why is happen but can I reduce the same model to 1 -
Twitter is not showing thumbnail for my page
I am trying to add a thumbnail when a user shares a page of my site. According to the documentation, it is necessary to define some parameters for the card i.e. image, title, description, etc. I am using the snippet on the page, however, when I share the card, my image does not show up. This is my current <head> <!-- Twitter open-graph tags --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:creator" content="@twitter_user"> <meta name="twitter:site" content="@twitter_user"> <meta name="twitter:image:alt" content="Site name"> <meta name="twitter:image" content="https://examplesite.com/static/landing/img/img.png" /> <meta name="twitter:title" content="{% trans 'Site Title' %} - Site" /> <meta name="twitter:description" content="{% trans 'Site description' %}" /> <meta name="twitter:url" content="https://www.examplesite.com{% url path %}"> I am using the absolute path, i.e.: https://examplesite.com/img/img.png (adding my domain to load the image), also using the HTTPS protocol, with an image in PNG format of 80kb and 1200x630px. When I want to validate my site with this tool, I get this result, in which the image is not visible and also, according to the log, not all the defined parameters are detected. -
Add a kml file into django
I have a map in my app and im trying to 'paint' some territories with kml files. I can get the outlined version if i hardcode the absolute path but since i have multiple kmls im trying to do it with a for loop with a field.kml.path (kml being the Filefield in my model) as per django instructions but it doesnt work . Any idea how to fix that ? view : def map(request): field_list = models.Field.objects.all() context = { "title": "Map", "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) My original map.html var polygon = omnivore.kml("{% static '../media/kml/Arnissa_cherry.kml' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); New version that doesnt work: {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name var polygon = omnivore.kml("{% static '{{field.kml.path}}' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 } } })); {% endfor %} -
Nginx 502 Bad Gateway error on EC2 Instance with dango
I'm using Nginx in my EC2 instance to attach my domain from route 53 with my Django app which is running in a docker container, it was working totally fine but as I move my database to the RDS and after moving it my application is not working there, Nginx is throwing me the error attached below: 2022/04/07 21:15:40 [error] 9#9: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 202.47.34.198, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://172.20.0.3:9000", host: "sub.domain.com", referrer: "http://sub.domain.com/" /etc/nginx/sites-available/default server { root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name sub.domain.com; location / { proxy_pass http://localhost:80; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 100M; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/sub.domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/sub.domain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = sub.domain.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 8080 default_server; listen [::]:8080 default_server; server_name sub.domain.com; return 404; # managed by Certbot } -
Function save() doesn't work in Django. Why?
I want to save my form in database, but save() doesn't work. When I do this, error wasn't been. views.py def comments(request): comments = Comment.objects.all() form = CommentForm() context = {"comments": comments, "form": form} if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.avtor = request.user comment.save() return HttpResponseRedirect(reverse('comment')) else: context["form"] = form return render(request, "home/comments.html", context) else: return render(request, "home/comments.html", context) And models. So, I think problem yet in views.py models.py class Comment(models.Model): Text = models.TextField(verbose_name='Text') date = models.DateTimeField(default=timezone.now, verbose_name='date') avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE) def __str__(self): return 'Comment {} at {}'.format(self.avtor, self.date) class Meta: ordering = ["-id"] forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ("Text",) -
I'm getting "social_core.exceptions.AuthForbidden: Your credentials aren't allowed" error in Django python-social-auth/social-auth-app-django
I am using social-auth library to authenticate user with OAuth2. I can authenticate user with accessToken and check infos included in this token. The token is valid. The problem appears in line: user = self.backend.do_auth(access_token=access_token) And I get: "social_core.exceptions.AuthForbidden: Your credentials aren't allowed" This is part of my settings file: SOCIAL_AUTH__OAUTH2_WHITELISTED_DOMAINS = ["localhost"] AUTHENTICATION_BACKENDS = ( "social_core.backends.facebook.FacebookAppOAuth2", "social_core.backends.facebook.FacebookOAuth2", "social_core.backends.google.GoogleOAuth2") I checked also secrets keys and they seem to be good, because I am able to validate token. Thank you in advance! -
Django for loop template tag made using CBV
I am trying to make a simple blog. One of my blog pages displays all of the blog posts on the website. I know I need to use a for loop but I do not know what to put in for the variables. All of the tutorials I have seen have used function-based views and I am using CBV. Help would be much appreciated. all_posts.html {% extends "base.html" %} {% block content %} <div class="container"> <h1>Blog Posts</h1> </div> <div class="container"> {% for in %} {% endfor %} </div> {% endblock %} Views.py from django.shortcuts import render from django.views import generic from . import models from django.contrib.auth import get_user_model User = get_user_model() from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class create_blog_post(generic.CreateView, LoginRequiredMixin): model = models.Blog_Post template_name = 'blog_app/creat_post.html' success_url = '/' fields = ('post_title', 'blog_content', 'files') class view_blog_post(generic.ListView): model = models.Blog_Post template_name = 'view_post.html' class delet_blog_post(generic.DeleteView, LoginRequiredMixin): model = models.Blog_Post template_name = 'delete_post.html' class all_blog_posts(generic.ListView): model = models.Blog_Post template_name = 'all_posts.html' modles.py from django.db import models # Create your models here. class Blog_Post(models.Model): slug = models.SlugField(max_length=1000, editable=False, null=True) post_title = models.CharField(max_length=100, editable=True, blank=False, null=True) blog_content = models.TextField(max_length=10000, blank=False, editable=True, null=True) files = models.FileField(blank=True, null=True, upload_to=True) … -
Custom labels - Django auth user model - ModelForm
I'm trying to set custom labels for a UserCreationForm in Django. I've tried to follow the docs and searched on here. Only the first label changes via the labels dictionary I created. org.label at the top has been tested just to see if changes are made by setting a label outside of the dictionary. from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ class SignUpForm(UserCreationForm): email = forms.EmailField(required=True) org = forms.CharField(required=True) org.label = 'test org label' class Meta: model = User fields = ["username", "email", "org", "password1", "password2"] labels = { "username":_("xx-Username"), "email":_("xx-Email"), "org": _("xx-Organisation"), "password1":_("xx-Password"), "password2":"xx-Confirm Password" } The output I get is linked as an image. https://i.stack.imgur.com/7kGUY.png Many thanks. -
Django test - global variable from another script is not defined
I've been trying to run a second script from within the main one called by django's manage.py test. However, I'm getting this error: File "<string>", line 254, in <module> File "<string>", line 61, in login NameError: name 'driver' is not defined First, the test.py that runs during the manage.py test: import sys from django.contrib.staticfiles.testing import StaticLiveServerTestCase #https://docs.djangoproject.com/en/3.1/topics/testing/tools/#testcase #LiveServerTestCase class TestReunioes(StaticLiveServerTestCase): fixtures = ['fix_core.json','users.json'] def testRun(self): exec(open("seleniumtest.py").read()) And the second script, seleniumtest.py: import traceback import sys from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys url = "http://localhost:3000" chrome_options = Options() chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--disable-gpu") driver = webdriver.Chrome(options=chrome_options) driver.get(url) driver.set_window_size(1700, 850) driver.implicitly_wait(20) def login(): user="teste" passwd="321" driver.find_element(By.NAME, "user").send_keys(user) #line 61 from the error driver.find_element(By.NAME, "passwd").send_keys(passwd) driver.find_element(By.NAME, "enter").click() # # Several other functions to test other parts # try: print("Starting test") login() #line 254 from the error except: traceback.print_exc() finally: driver.quit() It's confusing me because if I run the seleniumtest.py from the command line, it works fine. It also works fine when called from a python file that is literally just the exec(open("seleniumtest.py").read()) . The error is only happening when called from the django test. I know it's something … -
Hi guys! simple error with AUTH_USER_MODEL
I created a User model in apps.accounts.models, added it to installed_apps specified it as AUTH_USER_MODEL INSTALLED_APPS = [ 'apps.accounts' ] AUTH_USER_MODEL = 'accounts.User' and got an error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed this is probably due to the fact that accounts has not been registered, but When I write AUTH_USER_MODEL = 'apps.accounts.User' I get an error line 15, in make_model_tuple app_label, model_name = model.split(".") ValueError: Invalid model reference 'apps.accounts.User'. String model references must be of the form 'app_label.ModelName'. what should I do with this? if I enter from the app. then I get the error "split", if I don't drive apps. then I get the error "that has not been installed" any hint will be appreciated