Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Submit Button functionality not working properly in Django
Currently, I am working in a Django project and my case is that I have a html button which is used to run python script which is in my project folder. My scenario is that I am uploading a .pcap file and then I click on html button which is used to run python script and this python script is used to fetch the logs from .pcap file. But when I disable my html button it not run the script or you can say that it doesn't submit the request. I am sharing the details: views.py: def compliance_check(request): if request.method == 'POST': uploaded_file = request.FILES['doc'] print(uploaded_file.name) print(uploaded_file.size) fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) messages.info(request, 'your file ' + uploaded_file.name + " has been uploaded successfully") return render(request, 'enroll/compliance.html') This function is used to save the uploaded file in a folder. def results(request): user_id = request.session['user_id'] hash_id = compliance(user_id) request.session['hash_id'] = hash_id return redirect(tables_view) This function is used to run the python script. abc.html: <!-- use to upload the file --> <form method="post" enctype="multipart/form-data" name="myform"> {% csrf_token %} <input type="file" id="file" name="doc" onchange="document.myform.submit()"> <!-- <input type="submit" name = "doc" value="Start Analyze" class="btn btn-warning btn-sm" disabled /> --> </form> <!-- end of uploading … -
can not show the category name with number of articles django
I am trying to show number of articles in each category in my django project. But it shows category id instead of category_name. I want to display category_name and the corresponding number of articles. blog/views.py def searchView(request): statistics = Post.objects.values('cid').annotate(num_articles = Count('cid')).order_by() return render(request, 'blog/search.html', {'statistics': statistics}) blog/search.html -> here stat.cid shows the category id but I want to show category_name here. {% extends 'users/base.html' %} {% block content %} <div class="container"> <br> <div class="row text-center"> <div class="col-md-3"> </div> <div class="col-md-6"> <!-- <% if (statistics.length> 0){ %> --> <h4 class="p-2 mb-2 bg-secondary text-white">POPULAR CATEGORIES!!</h4> <table id="myTable" class="table table-bordered table-hover table-striped shadow-sm bg-white rounded"> <thead> <tr> <th>Category</th> <th>Articles Available</th> </tr> </thead> <tbody> {% for stat in statistics %} <tr> <td> {{ stat.cid }} </td> <td> {{ stat.num_articles }} </td> </tr> {% endfor %} </tbody> </table> <!-- <% } %> --> </div> </div> </div> {% endblock content %} blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) content = RichTextField() created … -
when I change admin URL, my project API URL not found. how can I solve it?
path("admin/", admin.site.urls), to path("", admin.site.urls), That much is fine. but API Not Found I need path("api/", include("config.api_router")), Note: when I use it path("admin/", admin.site.urls), API is worked -
how to add new foreign key in my old django models?
I have a model name Employee now i want to add a new fields in this model which will be a foreign key of Department model.I try to solve it the following way but i get error like django.db.utils.IntegrityError: The row in table 'employee_verification_employee' with primary key 'UP-0319001' has an invalid foreign key: employee_verification_employee.department_id contains a value '03' that does not have a corresponding value in employee_verification_department.id. class Department(models.Model): name = models.CharField(max_length=100) id = models.CharField(primary_key=True,max_length=10) class Employee(models.Model): name = models.CharField(max_length=100) department = models.CharField(max_length=100,choices = Departments) date_of_joining = models.DateField() employeed = models.BooleanField(default = True) email = models.EmailField(max_length = 254) blood_group = models.CharField(max_length=50) designation = models.CharField(max_length=100) image = models.ImageField(upload_to='employee_images',default = "") number = PhoneField(blank=True, help_text='Enter Contact Number') emergency_number = PhoneField(blank=True, help_text='Enter Contact Number') id = models.CharField(primary_key=True, max_length=200) department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True) def save(self, *args, **kwargs): if not self.id: nth_member = Employee.objects.filter(department = self.department).count()+1 self.id = "UP-" + self.department + self.date_of_joining.strftime("%y")+"{:03d}".format(nth_member) print(self.id) super(Employee, self).save(*args, **kwargs) def __str__(self): return self.name + "--"+ self.designation`` [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/xdRMd.png -
How to solve the errror"jinja2.exceptions.UndefinedError: 'get_count' is undefined"
I am working on small python application using flask app while clicking the local host link i am not getting internal server error and jinja2.exceptions error I don't know where i did mistake normal python my script is working and giving the result html page not able to read my id_count output how to solve this using python flask here is my script import numpy as np from flask import Flask, render_template, request app = Flask(__name__) x = np.array([0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27, 22, 26, 27, 26, 25, 24, 25, 26, 23, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11, 12, 11, 27, 19, 25, 26, 21, 23, 26, 13, 9, 22, 18, 23, 26, 26, 25, 10, 22, 27, 25, 19, 10, 15, 20, 21, 13, 16, 16, 15, 19, 17, 20, 24, 26, 20, 23, 23, ]) @app.route('/') def main(): return render_template('index.html') @app.route('/send', methods=['POST']) def get_count(id_count): sub_lists = np.split(x, np.where(np.diff(x) <0)[0] + 1) id_count=0 id_list = [] for unit in sub_lists: if min(unit) ==0 and max(unit)>20 and len(set(unit)) > 1: id_count += 1 id_list.append(unit) return id_count return render_template("index.html",get_count(x)) print("Number of counts: ",get_count(x)) if __name__=="__main__": app.run(debug=False, … -
Fetching another models data from a queryset in django
I have following models class Post(models.Model): title = models.CharField(max_length=150) content = RichTextField(blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class SavedPost(models.Model) saved_post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User,related_name="saved_posts", on_delete=models.CASCADE) I want to fetch the post details(title and content) of each saved post of individual users, I am able to get the queryset containing saved_posts of each user using following code user = User.objects.get(id=1) saved_post_qs = user.saved_posts.all() the above provides all post.ids in a queryset, but what I want is title, content of post returned from saved_post_qs. -
Django: Group dates by Year
im trying to create like a timeline from a model's created field but i can't find a clean way to do it. The idea is to return to the frontend ( DRF ) a list of years with their dates inside. So let's say that i have this model: class ProductModel(models.Model): name = models.CharField(max_length=200) created = models.DateField(default=datetime.date.today, blank=True) Let's say that 6 products have been created ( 3 of them from 2021 and 3 from 2022). So i would like to return something like this: "timeline": [ "2021": [ ..., "2021-12-1", "2021-11-1", "2021-10-1", ], "2022": [ ..., "2022-03-1", "2022-02-1", "2022-01-1", ], ] The idea it's only to return dates of created products and nothing else. But i don't now how to group the dates by years. I've tried with annotate and values but not the result that i need. I understand that on the serializer part i would have to use serializers.ListField() in order to be able to pass lists to it. Any suggestion im all ears. Thanks in advance :) -
Send email with DataTable query data
I need help to know how to send an email with the list shown by dataTable, I have put a custom buttom that when clicked I would like to send an email with the whole list. tblActividades = $ ('#tblActividades').DataTable ({ pageLength: 25, responsive: true, autoWidth: false, destroy: true, deferRender: true, ajax: { url: window.location.pathname, type: 'POST', data: { 'action': 'search_alumn', }, dataSrc: "" }, dom: 'Bfrtip', buttons: [ { extend: 'excelHtml5', text: '<i class="fas fa-file-excel"></i> Descargar Excel', titleAttr: 'Excel', className: 'btn btn-info btn-sm btnPrintExcell' }, { extend: 'pdfHtml5', text: '<i class="fas fa-file-pdf"></i> Descargar Pdf', titleAttr: 'PDF', className: 'btn btn-success btn-sm btnPrint', download: 'open', orientation: 'landscape', pageSize: 'LEGAL', customize: function (doc) { doc.styles = { header: { fontSize: 18, bold: true, alignment: 'center' }, subheader: { fontSize: 13, bold: true }, quote: { italics: true }, small: { fontSize: 8 }, tableHeader: { bold: true, fontSize: 11, color: 'white', fillColor: '#2873b6', alignment: 'center' } }; doc.content[1].table.widths = ['20%', '20%', '15%', '15%', '15%', '15%']; doc.content[1].margin = [0, 35, 0, 0]; doc.content[1].layout = {}; doc['footer'] = (function (page, pages) { return { columns: [ { alignment: 'left', text: ['Fecha de creación: ', {text: date_now}] }, { alignment: 'right', text: ['página ', {text: … -
Django haystack with AWS open search (elastic search compatible)
Im trying to use AWS open search with Django Haystacks, which is fully compatible (Amazon have suggested). However when I try launch "./manage.py rebuild_index" when pointing a connection at the platform I am met with the error Traceback (most recent call last): File "/data/app/myapp/./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/haystack/management/commands/rebuild_index.py", line 64, in handle call_command("clear_index", **clear_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 198, in call_command return command.execute(*args, **defaults) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/haystack/management/commands/clear_index.py", line 64, in handle backend.clear(commit=self.commit) File "/usr/local/lib/python3.10/site-packages/haystack/backends/elasticsearch7_backend.py", line 117, in clear self.conn.indices.delete(index=self.index_name, ignore=404) File "/usr/local/lib/python3.10/site-packages/elasticsearch/client/utils.py", line 347, in _wrapped return func(*args, params=params, headers=headers, **kwargs) File "/usr/local/lib/python3.10/site-packages/elasticsearch/client/indices.py", line 334, in delete return self.transport.perform_request( File "/usr/local/lib/python3.10/site-packages/elasticsearch/transport.py", line 421, in perform_request _ProductChecker.raise_error(self._verified_elasticsearch) File "/usr/local/lib/python3.10/site-packages/elasticsearch/transport.py", line 638, in raise_error raise UnsupportedProductError(message) elasticsearch.exceptions.UnsupportedProductError: The client noticed that the server is not a supported distribution of Elasticsearch when we've dug into this by looking in "site-packages/elasticsearch/transport.py" and the differences between the amazon headers and an elastic search header the only differences between the two is that … -
Django: a custom template tag to convert links inside of a TextField and change the hyperlink text
The scenario is that there are some dynamic texts on some templates, that will contain hyperlinks. For this, I have a SiteDataKeyValue model, in which the dynamic texts for different parts of the template are inputted. This is the model: class SiteDataKeyValue(models.Model): key = models.CharField( max_length=200, verbose_name="نام متن مورد نظر", unique=True ) value = models.TextField(verbose_name="متن") def __str__(self): return self.key A solution that I've found already, is Django urlize template tag. As mentioned in the docs, this tag converts texts like https://www.google.com to <a href="http://www.google.com" rel="nofollow">www.google.com</a>, which is nice but not what I'd like to achieve. I want to be able to change the hyperlink text, so the output would be something like: <a href="http://www.google.com" rel="nofollow">Click Here!</a>. I searched for a bit, came across modules like bleach, which is a fine module, but I couldn't find the answer I was looking for (I skimmed through the docs and there was nothing). Also I saw a comment somewhere telling that this could be achieved by writing a custom Django template tag, but although I tried to do this regarding the custom template filters docs, I didn't have a clue to how to achieve this. I'm not asking for the code, although it … -
Return custom response in websocket in Django
I wanted to return a response if the token is invalid. consumer.py some code... async def connect(self): try: self.userId = self.scope['url_route']['kwargs']['token'] try: UntypedToken(self.userId) except (InvalidToken, TokenError) as e: print(e) return {"response": False, "return_code": "invalid_token", "result": {}, "message": errors["token_not_valid"]} some code... in a browser, I'm not getting error details. I'm using WebSocket Test Client. and in postman, I'm getting this Error: connect ECONNREFUSED 127.0.0.1:8000 Handshake Details Request URL: http://127.0.0.1:8000/ws/users/eyJ0e.eyJ0b2In0.cbyYygG/chat/ Request Method: GET Request Headers Sec-WebSocket-Version: 13 Sec-WebSocket-Key: RpWsJRu+ziCUjwLtRjgNHg== Connection: Upgrade Upgrade: websocket Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Host: 127.0.0.1:8000 a result I'm expecting is. { "response": false, "return_code": "invalid_token", "result": {}, "message": "token error" } -
Getting response 200 instead of 302 in django test
I'm using django-pytest there's a signup/ route in urls which when accessed in browser, a signup form is rendered which expects the fields below ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] Here's the SignUpView and SignupForm import uuid from django import forms from django.contrib import messages from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.core.mail import send_mail from django.shortcuts import redirect from django.urls import reverse from django.views.generic import FormView class SignUpForm(UserCreationForm): first_name = forms.CharField( widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'First name'} ), label='', ) last_name = forms.CharField( widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Last name'} ), label='', ) username = forms.CharField( widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Username'} ), label='', ) email = forms.EmailField( widget=forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Email'} ), label='', ) password1 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'} ), label='', ) password2 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Confirm password'} ), label='', ) class SignUpView(FormView): template_name = 'center-form.html' form_class = SignUpForm def form_valid(self, form): if form.is_valid(): user = User.objects.create_user( first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password1'], is_active=False, ) activation_code = uuid.uuid4().hex Activation.objects.create(code=activation_code, user=user) activation_url = self.request.build_absolute_uri( reverse('activate', kwargs={'code': activation_code}) ) send_mail( 'Activate translation account', f'To activate your account, please follow the link below\n{activation_url}', 'Translation services', [form.cleaned_data['email']], fail_silently=False, ) messages.success( self.request, 'Please check your email for … -
MFA using auth0 in django
I need to enable authentication using Auth0 in my django app This are things i want to achieve with auth0 in my django app 1.MFA with OTP via email 2.2FA using google authentication/authy/etc 3.SSO using google, outlook. 4.existing accounts to move over to Auth0 signin 5.Attach google authentication to current account I have been looking but can't find proper documentation to integrate auth0 with django can anyone help me with this? -
google translator django moduleNotFoundError: No module named 'translate'
hi everybody i make a django quiz progect and i want to add advantge google translate to a page i download the pakge by pip install django-google-translate i add google-translate to my setting.py INSTALLED_APPS = [ 'google_translate', in template i wrote {% load google_translate %} i make that with the instructon of this page django-google-translate 1.1 in terminal i got the message ModuleNotFoundError: No module named 'translate' who can i solve this problem -
Django Like Button with AJAX Request
I'm trying to create an AJAX request in Django to update a Like Button. I'm getting an Error from the AJAX call. Not sure how to troubleshoot it. Can anybody point me in the right direction? .script $(".vote-form").submit(function(e) { e.preventDefault(); let poopfact_id = $(this).attr("id"); const voteCount = $(`.voteCount${poopfact_id}`).text(); let url = $(this).attr('action'); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'poopfact_id': poopfact_id, }, success: function(response) { document.getElementById("vote_count").innerHtml = response['total_votes'] console.log('success', response) }, error: function(response) { console.log('error', response), }, }); .views def vote(request, poopfact_id): if request.method=="POST": if user.is_authenticated: if "upvote" in request.POST: post.upvote.remove(request.user) total_votes = post.upvote.count() - post.downvote.count() data = {"total_votes": total_votes} return JsonResponse(data, safe=False) .html <form action="{% url 'vote' poopfact.id %}" style="display: inline-block" method="POST" class="vote-form" id="{{poopfact.id}}"> ... <div class="voteCount{{poopfact.id}}" id="vote_count">{{ poopfact.total_votes }}</div> <button type="submit" name="upvote" class="btn btn-primary"><i class="fa-solid fa-up-long"></i></i></button> ... -
How do i run django-channels + nginx + gunicorn + redis in docker?
I am trying run an django asgi app with nginx + gunicorn + redis in docker.so far my wsgi application is running by gunicorn smoothly but somehow my django channels consumers are not connecting. Docker-Compose version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=LiveSafer - POSTGRES_USER=postgres - POSTGRES_PASSWORD=demo1234 ports: - "5432:5432" web: build: . command: > bash -c " python manage.py makemigrations && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 LiveSafer.wsgi && daphne -b 0.0.0.0 -p 8001 LiveSafer.routing:application " volumes: - .:/app - static_files:/app/static expose: - 8000 ports: - 8001:8001 links: - redis depends_on: - db nginx: build: ./nginx/ ports: - 80:80 volumes: - ./nginx/conf.d/:/etc/nginx/conf.d/ - static_files:/home/app/static depends_on: - web # database controller adminer: image: adminer:latest restart: always environment: - ADMINER_DEFAULT_SERVER=db - ADMINER_DESIGN=flat - ADMINER_PLUGINS=tables-filter ports: - 8080:8080 redis: image: redis:latest command: ["redis-server", "--bind", "redis", "--port", "6379"] volumes: static_files: db: nginx upstream django{ server web:8000; } upstream channels-backend { server 127.0.0.1:8001; } server { listen 80; client_max_body_size 60M; location / { proxy_pass http://django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header HOST $host; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://127.0.0.1:8001; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; … -
/bin/sh: mysql_config: not found while making docker image in django app
Collecting mysqlclient==2.1.1 Downloading mysqlclient-2.1.1.tar.gz (88 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 88.1/88.1 kB 6.3 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] mysql_config --version /bin/sh: mysql_config: not found mariadb_config --version /bin/sh: mariadb_config: not found mysql_config --libs I just run docker build . -t docker-django-v0.0 and encountered above issue. -
Create page urlpatterns in admin panel Django
i am need help to django urlpatterns in urls.py. I am needs in create pages in admin panel need heelp pls in create page django in djanfo admin panel -
I am new to Vue Please help me to how I post file in vue. I am using django rest framework in backend. My response is ok
I am new to Vue Please help me to how I post file in vue. I am using django rest framework in backend. My response is ok. Here is my code I am new to Vue Please help me to how I post file in vue. I am using django rest framework in backend. My response is ok. Here is my code <template> <div class="tasks_container"> <div class="create_data"> <form @submit.prevent="createData" enctype="multipart/form-data"> <div class="form-group"> <label for="title">Name</label> <input type="text" class="form-control" id="name" v-model="name"> </div> <div class="form-group"> <label for="image">Image</label> <input type="file" ref="pic" class="form-control"> </div> <div class="form-group"> <button type="submit">Create Data</button> </div> </form> </div> </div> </template> <script type="text/javascript"> export default { data() { return { // student data students: [''], name: '', pic: '' } }, methods: { async createData(){ try { // Send a POST request to the API const response = await this.$http.post('http://localhost:8000/create/', { name: this.name, pic: this.pic, completed: false }); // Append the returned data to the tasks array this.students.push(response.data); // Reset the title and description field values. this.name = ''; this.pic = ''; } catch (error) { // Log the error console.log(error); } }, } </script> Please help me to resolve my problem. I am new to Vue Please help me to how … -
Why this error showing while created a form to upload image
Error raised is here enter code here This is the view to addpost and inherited from CreateView. views.py class PostAddView(CreateView): template_name="add_post.html" form_class=PostForm model=AddPost success_url=reverse_lazy("index") context_object_name="posts" models.py class AddPost(models.Model): post=models.ImageField(upload_to="postimages",null=True) caption=models.CharField(max_length=200) user=models.ForeignKey(MyUser,on_delete=models.CASCADE) created_date=models.DateTimeField(auto_now_add=True) Here MyUser is a abstract user forms.py class PostForm(forms.ModelForm): class Meta: model=AddPost fields=["post","caption"] widget={ "post":forms.FileInput(attrs={"class":"form-control"}), "caption":forms.Textarea(attrs={"class":"form-control","rows":3}) } template given to render the form. (add_post.html) <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container"> <div class="row"> <div class="col-2"></div> <div class="col-3"> <form action="" method="post" enctype="multipart/form-data"> {%csrf_token%} {{form.as_p}} <input type="submit" value="Post"> </form> </div> <div class="col-2"></div> </div> </div> </body> </html> -
Solutions to handle thousand or million socket connections
currently I have deployed a Django project on EC2 server which has a RAM of about 2GB using Gunicorn and Ngnix, I have also WebSocket's using Django channels on same server, so as of now we have around 200 active users. currently each user will have 5 active WebSocket connections/consumers (for chat, notification, etc.) open so currently around 1000 open connections are present at a time. As of now WebSocket's are working fine but in future we are expecting a growth in user so as the active WebSocket connections will grow, and at some point, due to excessive load, the server will start throwing issues regarding socket connections my question is how to solve this situation. is moving socket clients to another server a good solution? or should I increase my current servers RAM? basically i don't know what to do to solve this issue if this occurs in future -
Django test error: django.db.utils.ProgrammingError: relation "auth_group" does not exist
I have a django app which has not been tested lately. I have to run a custom command. I have written a test for it and run all migrations. I was able to successfully run all migrations. When I tried to run the test then the following error was thrown. python manage.py test Creating test database for alias 'default'... Got an error creating the test database: database "test_ILIDD_db" already exists Type 'yes' if you would like to try deleting the test database 'test_ILIDD_db', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_group" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 39, in <module> execute_from_command_line(sys.argv) File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv super().run_from_argv(argv) File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\test_without_migrations\management\commands\_base.py", line 78, in handle super(CommandMixin, self).handle(*test_labels, **options) File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\django\core\management\commands\test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "C:\Anaconda3\envs\nlp-ilidd-processor\lib\site-packages\django\test\runner.py", line 684, in … -
How to change google places autocomplete URL form data
I have configured the Google places autocomplete and after selecting search I am getting URL form data like so: http://127.0.0.1:8000/location/?term=1+York+Street%2C+Sydney+NSW%2C+Australia. I would like to get it configured so that it returns multiple name/value pairs like so: http://127.0.0.1:8000/location/?inputNumber=1&inputStreet=York+Street&inputCity=Sydney&inputState=NSW&inputZip=2000 This is required as I am using a Django and would like to use the name/value pairs to help with retrieving data from the model. This what I have configured in my script tags: <script> function initMap() { var input = document.getElementById('search_term'); const options = { types: ["address"], }; var autocomplete = new google.maps.places.Autocomplete(input); autocomplete.setComponentRestrictions({ country: ["au"], }); } </script> <script async src="https://maps.googleapis.com/maps/api/js?key=xxxxxx&libraries=places&callback=initMap"> </script> Any help would be appreciated? -
Creating a simple multiple user types in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and logout, it works, but then I when try to use the login form, it seems to me that its acting like the signup form. Because when I input the same user details of the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here. Here's what I have so far. models.py class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = ( ('admin', 'Admin'), ('developer', 'Developer'), ('project_manager', 'Project Manager') ) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES) login and signupviews class LoginView(View): def get(self, request): # Render the login form form = LoginForm() return render(request, 'users/login.html', {'form': form}) def post(self, request): # Get the form data from the request form = LoginForm(request.POST) # Validate the form data if form.is_valid(): # Get the username and password from the form username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Authenticate the user user = authenticate(request, username=username, password=password) # If the user is authenticated, log them in and redirect to the homepage if user is not None: login(request, user) … -
Creating relationship between Student and Class in Django
I am trying to create models where I can have relationship between Students and ClassName tables so that I can get all users using using ClassName.objects.get() and ClassName using Student.objects.get() method? I am completely stuck here. Should I add more fields to Student model? from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): pass class ClassName(models.Model): grade = models.IntegerField() section = models.CharField(max_length=1) def __str__(self): return f"{self.grade} - {self.section}" class Student(models.Model): first_name = models.CharField(max_length=124, null=False) middle_name = models.CharField(max_length=124, default='') last_name = models.CharField(max_length=124, null=False) name = models.CharField(max_length=124, default=f"{first_name} {middle_name} {last_name}") father_name = models.CharField(max_length=124, null=False) phone_number = models.CharField(max_length=20, null=False) date_of_birth = models.DateField() national_id= models.CharField(max_length=15, null=False) student_class = models.ForeignKey(ClassName, on_delete=models.DO_NOTHING) def __str__(self): return f"{self.first_name} {self.middle_name} {self.last_name}" I am trying to find a method to get all users using using ClassName.objects.get() and ClassName using Student.objects.get() method?