Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UNIQUE constraint failed: user_profile.StudentID error
I am getting this error(IntegrityError at /register/) every time I try to create a new user. In user creation form I am creating both User and profile. here is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) StudentID = models.CharField(max_length=8,unique=True) Branch = models.CharField(max_length=255,choices=Departments,default="CSE") YearOfStudy = models.IntegerField(default=1) ContactNumber = PhoneField(help_text='Contact phone number') image = models.ImageField(default='default.jpeg' , upload_to='profile_pics') parentsContactNumber = PhoneField(help_text="Parent's phone number") def __str__(self): return f'{self.user.username} Profile' here is forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['username','email','first_name','last_name','password1','password2'] class ProfileCreationForm(forms.ModelForm): class Meta: model = Profile fields = ['StudentID','Branch','YearOfStudy','ContactNumber'] here is views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) form1 = ProfileCreationForm(request.POST) if form.is_valid() and form1.is_valid(): form.save() form1.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() form1 = ProfileCreationForm() context = { 'form': form, 'form1': form1 } return render(request, 'user/register.html', context) here is register.html {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">JOIN TODAY</legend> {{ form|crispy }} {{ form1|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> </div> {% endblock content %} please help me … -
i am trying to add functionality like/dislike without page refresh in django
i am trying to add functionality like/dislike without page refresh but i can not set the logic here is my models.py file code from django.db import models # Create your models here. class EmployeeDetail(models.Model): emp_fname = models.CharField(max_length=50, default="") emp_lname = models.CharField(max_length=50, default="") emp_uname = models.CharField(max_length=100, default="") emp_email = models.EmailField(max_length=254, default="") emp_password = models.CharField(max_length=100, default="") emp_dob = models.DateField(max_length=50, default="") emp_doj = models.DateField(max_length=50, default="") emp_designation = models.CharField(max_length=100, default="") emp_salary = models.IntegerField() emp_leaves = models.IntegerField() emp_contact = models.CharField(max_length=12, default="") emp_photo = models.ImageField(upload_to="employee/images", default="") def __str__(self): return self.emp_fname class Post(models.Model): emp_id = models.ForeignKey(EmployeeDetail, on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.CharField(max_length=150) content = models.TextField() author = models.CharField(max_length=15) timeStamp = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) dislikes = models.IntegerField(default=0) def __str__(self): return self.title + ' by ' + self.author class Preference(models.Model): user_id = models.ForeignKey(EmployeeDetail, on_delete=models.CASCADE) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.IntegerField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user_id) + ':' + str(self.post_id) + ':' + str(self.value) and my urls.py code blow here from django.urls import path from .import views urlpatterns = [ path('', views.login, name='Login'), path('logout', views.logout, name='Logout'), path('employee/home/', views.home, name='Home'), path('employee/manageuser/', views.manageuser, name='manageuser'), path('employee/blank/', views.blank, name='blank'), path('employee/font_awesome/', views.font_awesome, name='fontawesome'), path('employee/map_google/', views.map_google, name='map google'), path('employee/not_found/', views.not_found, name='map google'), path('employee/register/', views.register, name='Registration'), path('employee/employee_profile/<int:id>', views.employee_profile, name='Employee Profile'), path('employee/delete_employee/<int:id>', views.delete_employee, … -
upload_to attribute is being overwritten by unknown source
upload_to attribute is being overwritten and I have no idea what's causing this, instead of uploading a file I'm getting a SuspiciousFileOperation exception. The base path component stated in the exception is correct but joined path is not correct as it should be just 'img/posts'. models.py thumbnail = models.FileField(upload_to='img/posts') Exception value The joined path (/media/tb1.jpg) is located outside of the base path component (/home/user/Documents/project/project/media) -
how can I host my django app on Godaddy dedicated server (delux)?
I Have no idea how to set things up on this fresh centOS 7 server, how to host my django app with postgre db in this server? -
Django REST Framework - Serializer don't see field
I want create User, which hold Foreign Key to his Country. Obviously I want to make it required field. But when I send POST request without 'country' field, DRF Serializer doesn't throw an error. Nowhere in the code have I allowed the field to be empty, it's the same as the rest. I took a step further, and in the create() method of my ModelViewSet I decided to print serializer.validated_data class UserViewSet(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() permission_classes = [] def create(self, request, format=None): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): print(serializer.data) I send following POST request: And my serializer.validated_data value was: OrderedDict([('password', 'test1231112'), ('first_name', 'Jarosław'), ('last_name', 'Psikuta'), ('phone', '2999111331'), ('email', 'rweww@gmail.css'), ('description', 'fajny uzytkownik'), ('address', 'Mieszka 3/4'), ('date_of_birth', datetime.date(1997, 10, 13))]) I realised that serializer just don't see my country field. I already write some code to check if my country field exist: country_code = request.data.get('country', None) if not country_code: return Response({'country': 'This field is required'}, status=status.HTTP_400_BAD_REQUEST) but I know that's wrong approach. It's additional code, and actually serializer should do that work for me. Here You have rest of my code: serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' read_only_fields = ('id', 'last_login', 'is_superuser', 'is_staff', 'is_active','date_joined', … -
view doesn't show list
separate index from list and create, but now When I create a product it doesn't list and doesn't show the edit and update buttons. the create extends view of index. this is index.html <!DOCTYPE html> <html><head> <title>Mis Productos</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head><body> <div class="container text-center pt-5"> <h1>Hola</h1> <p>Inventario de productos</p> <div class='jumbotron'> <center> <div class="text-left" style="max-width:500px"> <form action="{% url 'index' %}" method="post"> {% csrf_token %} {% for field in register_form %} <div class='form-group'> <label for="{{ field.name }}">{{ field.label }}</label> {{ field }} </div> {% endfor %} <br> <center><a href="{% url 'create' %}" class="btn btn-success btn-lg">Registrar producto</a></center> </form> </div> {% block content %} </center> <br> <table class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th>#</th> <th>Nombre</th> <th>Telefono</th> <th>Fecha de nacimiento</th> <th>Email</th> </tr> </thead><tbody> {% for producto in productos %} <tr> <td>{{ producto.id }}</td> <td>{{ producto.nombre }}</td> <td>{{ producto.precio }}</td> <td>{{ producto.fecha_de_vencimiento }}</td> <td>{{ producto.codigo_barras }}</td> <td><a href="update/{{producto.id}}" class="btn btn-info" id = '{{producto.id}}'>edit</a></td> <td><a href="delete/{{producto.id}}" class="btn btn-danger" id = '{{producto.id}}'>delete</a</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div><script src="https://code.jquery.com/jquery- 3.3.1.slim.min.js" integrity="sha384 -q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jiz o" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/um d/popper.min.js" integrity="sha384- ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/boot strap.min.js" integrity="sha384- ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULT y" crossorigin="anonymous"></script> {% endblock %} </body> </html> this is create.html {% extends 'producto/inicio.html' %} {% … -
django - adding an if-statement to a method
I hope you are well! I am trying to create my first Django app, however, I am having issues. Please see my code below: from django.db import models # Create your models here. class Topic(models.Model): ###A topic the user is learning about### text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): ###Return a string representation of the model### return self.text class Entry(models.Model): ###Something specific learned about a topic### topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural ='entries' def __str__(self): ###Return a string representation of the model.### return f"{self.text[:50]}..." The last method: 'def__str__(self):' adds an ellipsis to all entries. I am being asked to add an 'if-statement' which would only add an ellipsis to entries longer than 50 characters and all entries which are shorter than 50 characters should be without an ellipsis. Please help - thanks in advance! -
Django reverse db lookup for multiple objects
Let's say I have a model called TicketSection and TicketSubmission the models look like this: (simplified) class TicketSection(models.Model): title = models.CharField(max_length="35") weight = models.IntegerField() class TicketSubmission(models.Model): ticket_section = models.ForeignKey('myapp.TicketSection') cost = models.IntegerField() submiter = models.ForeignKey('myapp.User') submiting_account = models.ForeignKey('myapp.Account') Now I want to filter TicketSections with it's TicketSubmissions. So I do: ticket_sections = TicketSection.objects.filter(weight__gte=50).annotate(some_additional_logic) I know you can select reverse objects by ticket_sections[0].ticketsubmission_set.filter(again_some_logic).annotate(logic) But how do I do it for all ticket sections and how do I use it in template? Should I do: for ticket_sec in ticket_sections: ticket_sec.submissions = ticket_sec.ticketsubmission_set.filter(again_some_logic).annotate(logic) and then in template {% for ticket_sec in ticket_section %} {% for submission in ticket_sec.submissions %} {{ submission.cost }} ^ But that doesn't seem like the right way for me. So how should I reverse lookup for multiple objects to minimalize database hits? I'm using Django 2.2.5 with MySQL database. -
Django telling me template doesn´t exist
Can anybody tell me why django is telling me that template does not exist? I would like to go from the film_detail.html to film_report.html, when clicking on the "report"-button... views.py class FilmReport(LoginRequiredMixin, UpdateView): model = Report fields = ["comment", "reporter", "reports"] # def __str__(self): # return self.title def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) urls.py app_name = 'watchlist' urlpatterns = [ path("", views.films_view, name="board-home"), path("film/add", FilmAddView.as_view(), name="film-add"), path("film/<int:pk>/", FilmDetailView.as_view(), name="film-detail"), path("film/<int:pk>/report", FilmReport.as_view(), name="film-report") ] film_detail.html {% extends "board/base.html" %} {% block content %} <article class="media content-section"> <img class="rounded-circle film-img" src="/media/{{object.poster}}"> <!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. --> <a href=" {% url 'watchlist:film-add' %}" class="waves-effect waves-light green btn"><i class="material-icons right">rate_review</i>add review</a> <a href=" {% url 'watchlist:film-report' film.id%}" class="waves-effect waves-light red darken-4 btn"><i class="material-icons right">report</i>report</a> <div class="media-body"> <h2 class="film-title">{{ object.title }}</h2> <p class="film-plot">{{ object.plot }}</p> </div> </article> {% endblock content %} film_report.html {% extends "board/base.html" %} {% block content %} <h2>Film report</h2> <!-- <article class="media content-section"> <img class="rounded-circle film-img" src="/media/{{object.poster}}"> <div class="media-body"> <h2 class="film-title">{{ object.title }}</h2> </div> </article> --> {% endblock content %} -
Django: Filter queryset by property of Element
I have two models, Chat and DeletedChat. Now i want to get all chats of a user, removing those which from_date-fields, in DeletedChat, are bigger then the last_updated ones of the chat itself. How do i do that? class Chat(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) last_updated = models.DateTimeField(auto_now=True) class DeletedChat(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) from_date = models.DateTimeField(default=timezone.now) And in my views.py I tried: chat_ids = request.user.deletedchat_set.exclude(from_date__lt='chat__last_updated').values_list('chat', flat=True) which gives me the following error: ['“chat__message__set__last” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Thanks for your Help! -
Why does field.errors display duplicate error messages from clean() method in Django form?
Whether I use clean() or clean_initial_ph() I get duplicate error messages. Also if I iterate over form fields: {% for field in form %} {{ field|as_crispy_field }} {% if form.errors %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif%} {% endfor %} or list the fields and errors manually: ... {{ form.initial_ph|as_crispy_field }} {{ form.initial_ph.errors }} ... I still get the duplicate error messages (albeit different styling for the larger one). I followed the validation guidelines. For example in clean_initial_ph() my validation looks like this: def clean_initial_ph(self): initial_ph = self.cleaned_data['initial_ph'] if initial_ph: if initial_ph < 0: raise forms.ValidationError(_("PH must be above 0."), code = 'negative_intial_ph') return initial_ph I have another validation on some time fields in clean() which does not display duplicate error messages: # Assuming clean_initial_ph is commented out def clean(self): cleaned_data = super().clean() pump_time = cleaned_data.get("pump_time") disposal_time = cleaned_data.get("disposal_time") incorptime = cleaned_data.get("incorptime") initial_ph = cleaned_data.get("initial_ph") disposal_ph = cleaned_data.get("disposal_ph") if pump_time and disposal_time: # DOES NOT DISPLAY DUPLICATE ERROR MESSAGES if pump_time >= disposal_time: self.add_error('pump_time','Pump time must be prior to disposal time.') self.add_error('disposal_time','Disposal time must be after to pump time.') if incorptime: if incorptime <= disposal_time: self.add_error('incorptime','Incorp time must … -
Python multiprocessing pool.close and pool.join TypeError: 'NoneType' object is not callable
I'm getting the error TypeError: 'NoneType' object is not callable in self.pool.join called by the __del__ method of a module containing the following code. In particular, the error occurs when running database migrations or the test suite in a Django application. I've tried implementing import atexit and registering the methods inside __init__ via: atexit.register(self.pool.close) atexit.register(self.pool.join) ...but this hasn't worked. Why is this TypeError occuring in the code below's __del__ method, and how can I avoid it? import datetime import json import mimetypes from multiprocessing.pool import ThreadPool import os import re import tempfile # python 2 and python 3 compatibility library import six from six.moves.urllib.parse import quote from paapi5_python_sdk.configuration import Configuration import paapi5_python_sdk from paapi5_python_sdk import rest from paapi5_python_sdk.auth.sig_v4 import AWSV4Auth class ApiClient(object): PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types NATIVE_TYPES_MAPPING = { 'int': int, 'long': int if six.PY3 else long, # noqa: F821 'float': float, 'str': str, 'bool': bool, 'date': datetime.date, 'datetime': datetime.datetime, 'object': object, } def __init__(self, access_key, secret_key, host, region, configuration=None, header_name=None, header_value=None, cookie=None): if configuration is None: configuration = Configuration() self.configuration = configuration self.pool = ThreadPool() self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default … -
i am getting one of my program accessed by every IDE of python
i want to work with visual studio for django. but whenever i try to open a terminal and start any command it always run one of my program that i created on spyder. even in cmd prompt i am getting same thing. how can i disconnect that program to run. i am not able to work on any IDE of python . below id the input command i used in that program to have input from uses. mkvirtualenv denvx Enter a sentence you like: -
Django ORM: filter by multiple properties of related object
I have the following objects: class Image: user models.ForeignKey(User) corrupted = models.BooleanField() final = models.BooleanField() class ImageRevision: image = models.ForeignKey(Image, related_name="revisions") corrupted = models.BooleanField() final = models.BooleanField() In English: images can have many revisions images might become corrupted, as well as revisions only one object will be final, i.e. either the image or one of its revisions (an image without revision counts as final) I would like to get all images from a user that are corrupted. An image counts as corrupted if any of the following is true: the image itself is corrupted and final the revision marked as final is corrupted In the following cases, the image does not count as corrupted: the image is final and is not corrupted the image has a final revision that is not corrupted Can this be queried using Django ORM? -
Django Template - Cannot iterate throught this list and get menu item
i have one project andromeda where is 2 apps. 1 is blog and seccond one is blogmenu but when I want to get information from the blog app there is no problem and i can get all information. but when I want to get a menu item from blogmenu I'm getting now error but there is empty navigation bar. blogmenu urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('', include('blogmenu.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blogmenu views.py from django.shortcuts import render def Blog_Menu(request): Menu_items = Menu.objects.all() template_name = 'front/index.html' return render(request, template_name, {"Menu_items":Menu_items}) blogmenu models.py from django.db import models class Menu(models.Model): Menu_name = models.CharField(max_length=100,blank=True) Menu_slug = models.SlugField(name="სლაგი",blank=True) Menu_image = models.ImageField(upload_to="menuimages") Menu_url = models.CharField(name="url",max_length=100,blank=True,null=True) class Meta: verbose_name = "მენიუ" def __str__(self): return self.Menu_name sample html template code {% for menu in Menu_items %} <li class="main-menu-item"> <a href="#" class="main-menu-item-link">just text</a> </li> {% endfor %} -
How to create registration page for users on own website?
I am currently working on a GST portal for software project. I am learning and implementing Django for backend. Currently, I know that the users in django are for the admin page. How to I create my own separate users for my website. To be specific, I have 2 types of users- Taxpayer and tax-official who can register on my website. How do I do that? Desperate help needed. -
Django :Aafter submitiing form, browse button disappear
I am working on pdf data extraction project.there i am browse pdf file using django-forms filefield and then displaying extracted data on same page.everything works fine but the problem is after submitting browsed file, extracted data appear on same page but browse button get disappear. forms.py class browse(forms.Form): file = forms.FileField() views.py def index(request): if request.method == 'POST': user = browse(request.POST, request.FILES) if user.is_valid(): handle_uploaded_file(request.FILES['file'])#store file in upload folder path = "pdfextractor/static/upload/"+ str(request.FILES['file'])#path of selected file result = extract_data(path)#extract data from file context = {'result':result} return (render(request,'pdfextractor/index.html',context)) else: user = browse() return render(request,"pdfextractor/index.html",{'form':user}) index.html <body> <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="Submit" name="submit" value="Submit"/> </form> {% for key, value in result.items %} <h1>{{key}} : {{value}}</h1> {% endfor %} </body> output here you can see browse button disappear.now here i want that browse button so that user can browse new file directly from here -
Best way to handle a centralized MySQL database that connect multiple microservices (NoSQL/MySQL)
I have a core service that connects to many other microservices. This core service have several tablse that can have an "FK" with these microservices, and they can be either SQL or NoSQL, example: CREATE TABLE `users_usergameinfo` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nameOnGame` varchar(255) COLLATE utf8mb4_bin NOT NULL, `idOnGame` int(11), PRIMARY KEY (`id`), ) ENGINE=InnoDB AUTO_INCREMENT=25103 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; The idOnGame field point to the microservice database, and, as far it was connected to SQL databases, was ok to use an integer value. We also have other tables that do JOIN between each other. Now we will start to connect with NoSQL (mongodb) databases, and we are trying to figure out how to handle the ObjectID without creating new fields. Converting it to VarChar(32) or Binary(16), what is the best (and optimized) way to do this? -
Django NoReverseMatch at /classes/1/1 Error
I am linking trying to retrieve the URL to the Html page using {% for lesson in playlist.lesson_set.all %} <a href="{% url 'lessons' classes.id list.id lesson.id %}">World1</a> {% endfor %} but when I am running the webpage I am getting the error NoReverseMatch at /classes/1/1 Reverse for 'lessons' with arguments '('', '', 1)' not found. 1 pattern(s) tried: ['classes/(?P<classes_id>[0-9]+)/(?P<list_id>[0-9]+)/(?P<lesson_id>[0-9]+)$'] From where this error?? How to solve this Error?? MY CODE: Views.py from django.shortcuts import render, get_object_or_404 from .models import Class, Material, Lesson, Playlist def home(request): Classes= Class.objects return render(request, 'classes/index.html', {"class":Classes}) def classes(request): Classes= Class.objects return render(request, 'classes/Classes.html', {"class":Classes}) def materials(request, classes_id): theclass= get_object_or_404(Class, pk=classes_id) Materials = Material.objects.all() context = { 'classes': theclass, 'material': Materials } return render(request, 'classes/Materials.html', context) def playlist(request, classes_id, list_id): theMaterial=get_object_or_404(Material, pk=list_id) classid=get_object_or_404(Class, pk=classes_id) theList=Playlist.objects.all() context={ 'Material': theMaterial, 'playlist':theList, 'class':classid } return render(request, 'classes/list.html', context) def lesson(request, classes_id, list_id, lesson_id): thePlaylist=get_object_or_404(Playlist, pk=lesson_id) theMaterial=get_object_or_404(Material, pk=list_id) theClass=get_object_or_404(Class, pk=classes_id) lesson=Lesson.objects.all() context={ 'material':theMaterial, 'list':thePlaylist, 'class':theClass, 'lesson':lesson } return render(request, 'classes/lesson.html', context) URLs.py: from django.contrib import admin from django.urls import path import classrooms.views import users.views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', classrooms.views.home), path('classes', classrooms.views.classes), path('classes/<int:classes_id>', classrooms.views.materials, name="material"), path('signup', users.views.signup, name="signup"), path('login', users.views.login, name="login"), … -
So i'm using Django and React and in the build/static folder django wont run json data or display the images on the browser
the images and json data does not appear on browser this is my django setting.py this here is django on port http://127.0.0.1:8000/ but everything works fine in react Please i dont know what i am doing wrong. please help -
Django - Confirmation popup
I'm trying to write a code for deleting an item. But before deleting it i want to popup a message to the user like "are you sure you want to delete?". I want to delete the item by its ID. I wrote this code, but i pretty sure its not how it should be. Please guide me what to do. HTML FILE <div id="film_box"> {% if films %} {% for film in films %} <div class="card" style="width: 18rem;"> {% if film.image%} <img src="{{ film.image.url }}" class="card-img-top" alt="..."> {% endif %} <div class="card-body"> <h5 class="card-title">{{ film.title}}</h5> <p class="card-text">{{ film.category_name }}</p> <p class="card-text">{{ film.country_name }}</p> <p class="card-text">{{ film.director }}</p> <p class="card-text">{{ film.release_date }}</p> </div> <div class="card-body"> {% if request.user.is_superuser %} <ul style="list-style:none;"> <li><a href="{% url 'update_director' film.director_id %}" class="card-link">Modify the director</a> </li> <li><a href="{% url 'update_film' film.id %}" class="card-link">Modify the film</a></li> <li><button onclick="document.getElementById('btn_delete').style.display='block'" name="{{ film.id }}" class="btn btn-danger">DELETE</button></li> </ul> {% endif %} <!--popup message--> <div id="btn_delete" class="modal"> <span onclick="document.getElementById('btn_delete').style.display='none'" class="close" title="Close Modal">×</span> <form class="modal-content" action="/delete/{{film.id}}"> <div class="container"> <h1>Delete film</h1> <p>Are you sure you want to delete the film?</p> <div class="clearfix"> <button type="button" onclick="document.getElementById('btn_delete').style.display='none'" class="cancelbtn">Cancel</button> <button href="{% url 'delete_film' film.id %}" onclick="document.getElementById('btn_delete').style.display='none'" class="deletebtn">Delete</button> </div> </div> </form> </div> {% endfor%} {% endif %} JAVASCRIPT … -
How to make search more accurate in Django?
so on the way of learning process, I am making my first side-project on django. I want to make my search more accurate, for example: when post body contains text with 3 words "I love stackoverflow" and someone searches for "I stackoverflow" (without word LOVE), result is not shown on the search page. What could be the best approach in this case to get the result, even if the post body does not contain words in that order as a search query? views.py def search(request): posts = Post.objects.all().order_by('title') query = request.GET.get('q') print(query) if query: posts = Post.objects.filter( Q(title__icontains=query)| Q(body__icontains=query) ) context = { "posts": posts, } return render(request, "search.html", context) -
How do I create a Friend model with accept field?
I want to create a social networking app, where we can add friends and see their posts. In this I want to create a friend model like this: class Friend(models.Model): from = models.ForeignKey(User) to = models.ForeignKey(User) accepted = models.NullBooleanField(null=True) class Meta: unique_together = ('from', 'to') I am just confused about reverse relation between from and to. For example, if A is friend of B, then B is also friend of A. I am having problem in getting all friends of a user, because the user can exist in from as well as in to. -
How to only allow logged in users connect to websocket in Django Channels?
I have a chat app and I want only users that are logged in to be able to connect to the websocket. How can you achieve that? Is there something like the @login_required decorator for Django channels? I know from the documentation that that's how you can access the user: class ChatConsumer(WebsocketConsumer): def connect(self, event): self.user = self.scope["user"] But how do you deny the connection if the user isn't logged in? -
Chart.js first row bar not showing in django
my chart work properly but as first starting point 1st bar not showing here is the code: $(function () { var $populationChart = $("#population-chart"); var res = ['20','20','30'] $.ajax({ url: $populationChart.data("url"), success: function (data) { var ctx = $populationChart[0].getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.label, datasets: [{ label: 'Price', backgroundColor: 'blue', data: res, }] }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Rating Analysis' } } }); } }); }); Screenshot: Is there any way to show minimum value first bar properly?