Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Can't login into admin site with user create directly from admit site
So, i have created a Customer user model using AbstractUser Model.py class Department(models.Model): department_name = models.CharField(max_length=20) def __str__(self): return self.department_name class Role(models.Model): role_name = models.CharField(max_length=120) def __str__(self): return self.role_name class Task(models.Model): task_desp = models.TextField(max_length=100) in_progress = models.BooleanField() def __str__(self): return self.task_desp class Employee(AbstractUser): username = None email = models.EmailField(max_length=100,unique=True) phone_number = models.CharField(max_length=14) department = models.ForeignKey(Department,on_delete=models.CASCADE,null=True,blank=True) role = models.ForeignKey(Role,on_delete=models.CASCADE,null=True,blank=True) address = models.TextField(max_length=200) task_assigned = models.ForeignKey(Task,on_delete=models.CASCADE,null=True,blank=True) USERNAME_FIELD= 'email' REQUIRED_FIELDS = ['phone_number'] objects= UserManager() def __str__(self): return self.email manager.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def create_user(self,email,password=None,**extra_fields): if not email: raise ValueError("Please provide email") email = self.normalize_email(email) user = self.model(email=email,**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,password,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) if extra_fields.get('is_staff') is not True: raise ValueError("super user must have staff user") return self.create_user(email,password,**extra_fields) Added the model in setting AUTH_USER_MODEL = 'emp.Employee' So,I have made 3 user via python manage.py createsuperuser and was able to login into admit site, but when I made a 4th user directly from admin site, gave it all staff and superuser permission I am not able to login I get this error Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. I create this Elon user ( … -
Why Django auto adds permissions to group?
Currently I'm making some groups for my backend and I noticed through the admin panel that the groups have some extra permissions I did not add. What is the cause of this behavior? models.py: produccion_group, created = Group.objects.get_or_create(name="Produccion y cuentas") produccion_group.permissions.add( Permission.objects.get(codename='add_brand'), Permission.objects.get(codename='change_brand'), Permission.objects.get(codename='view_brand'), Permission.objects.get(codename='add_expense'), Permission.objects.get(codename='change_expense'), Permission.objects.get(codename='view_expense'), ) produccion_group.save() Admin panel: -
Wrap Django template content in a React layout
I'm used to building Single Page Apps. But for the current project I have a complex application serving almost everything from django templates. It's out of scope to rebuild all the django based content into the SPA with API access. This project is only to replace the header and add a sidebar which slides out of the way when the "hamburger" icon is clicked, or when the media size gets small enough. It's a typical responsive, mobile first, application menu layout with the sidebar to the left of the content on large viewports. In development, the layout works as intended. But there's no server rendered content being put in the "main" content area. This is how I would construct the layout in HTML if I wasn't using react. It doesn't currently work this way because if I render the components individually, they don't share a context for responding to changing viewport and events. <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="header"><!-- React --></div> <div> <div id="sidebar"><!-- React --></div> <div id="main">{{ Django Content Here }}</div> </div> <div id="footer">{{ Django Footer Here }}</div> </body> If I follow the standard convention, the layout works because the App.js pulls various … -
Class based views does not render HTML in template-Is context missing?
I started to work with class based views, but the codes that I've written initially does not render in the template when I use class based views. The data that is in note.title (see template) simply does not show up when I use class based views. When I change back to function based views and refresh the page, the HTML code in the template shows up without any problems. Could someone explain what causes this error? I've read something about context not been found by the template but I don't really understand what it means and how context resolves the issue. Thanks in advance! views.py from multiprocessing import context from django.shortcuts import render import notes from .models import Notes from django.http import Http404 from django.views.generic import ListView, DetailView, CreateView # Create your views here. class NotesCreateView(CreateView): models = Notes fields = ["title", "text"] succes_url = "/smart/notes" class NotesListView(ListView): model = Notes context_objects_name = "note" template_name = "notes/notes_list.html" class NotesDetailView(DetailView): model = Notes context_object_name = "note" # def list(request): # all_notes = Notes.objects.all() # context = {'notes': all_notes} # return render(request, 'notes/notes_list.html', context) # def detail(request, pk): # try: # note = Notes.objects.get(pk=pk) # except Notes.DoesNotExist: # raise Http404("This note doesn't … -
ModuleNotFoundError: No module named 'fcntl' on windows 11
I am using Django==4.1.1 and django-crontab==0.7.1 this error occurs when I use crontab on my project. How can I fix this error? -
save() method in Django model receiving string instead of date object
Currently we're migrating Django from version 1.11.29 to version 3.2.15 and one thing that we noticed is that the DateFields in the save() method in models is now a string instead of a Date object as it used to be. this is one of the fields that now is a string service_date_starts = models.DateField(blank=True, null=True,) is this expected? or is there a way the DateFields in save() still be an object without parsing? -
Installer for local webapp for stock management using django
I am looking to build a webapp for stock management, since it does not need to be hosted on the internet( only admin and sellers can access it ), with it's database on the local computer, I need to find a way for making it easier for the sellers to use the webapp without running a server and all that stuff since they are not tech-savvy -
Handle Django server errors (5XX) in production to prevent showing sensitve information
I'm developing an API using Django Rest Framework. In the codes, there might be a lot of exceptional situations that we may not think of and cause 5XX errors. One approach to handle these errors is to put a try-exception in the whole function (Or places you guess an unknown error might occur). I want to show the details of the error in the API response (Not just in the logging server) when the debug mode is on in Django. Also, I want to hide these details in production mode (when debug is false) and just pass the error code with no body when the error is 5XX. Is there any official (and efficient) way to do that? I was thinking of creating a middleware to handle that, but in this case, I should check all responses before passing the response to the user, and this is not efficient at all. I thought there might be a built-in function to handle this stuff, and I can override that to hide the body of the 5XX errors. -
How to authenticate with encrypted email as username?
In my Django web-app, I would like the user to authenticate itself with an encrypted email address that would simply be the username. Due to the existing GDPR regulations in my country, I have to encrypt e-mail addresses and by doing it with the help of Python Cryptography and Fernet functions, each string is different after encryption, even if two strings are encrypted with one and the same key. Is it possible to authenticate the user without errors in such a situation? If this is possible, where can I read a little more about it? -
How to use Tablesorter for Select?
I'm trying to use tablesorter.js to sort a column by a select box. I can't seem to make it work and I've tried most of the stuff written either here or in the docs. Was wondering if someone could help me out with this. I'm using Django which shouldn't matter I think, but here is the HTML and JS: HTML: <tr> <th></th> <th></th> <th></th> {% if perms.directors.director %} <th></th> {% endif %} <td class=""> <select class="" > <option value=""></option> <option value="Incomplete">Incomplete</option> <option value="Submitted">Submitted</option> <option value="OnHold">OnHold</option> <option value="Qualified">Qualified</option> <option value="Denied">Denied</option> </select> </td> </tr> </thead> <tbody> {% for org in object_list %} <tr class="{{ forloop.counter|divisibleby:2|yesno:"even,odd" }}"> <td><a href="{{ org.get_absolute_url }}">{{ org.name }}</a></td> <td>{{ org.submission_date | date:"Y/m/d" }}</td> <td>{{ org.updated_date | date:"Y/m/d" }}</td> {% if perms.directors.director %} <td>{{ org.review_note_date | date:"Y/m/d" }}</td> {% endif %} <td> <span class="label {{ org.bootstrap_color_state }}"> {{ org.pretty_state }}</span> </td> <td> </td> </tr> {% endfor %} </tbody> JS: $('.table').each(function () { var $table; $table = $(this); $table.find('a').not('.btn').closest('td, th').css({ 'padding': 0 }); $table.find('.amount').addClass('text-right'); // Adds tablesorter plugin to .table, so to sort on <th>s $table.tablesorter().addClass('tablesorter'); // Add up/down arrows to indicate which order column data is displayed $table.bind('sortEnd', function (event, table) { $(table).find('.glyphicon').remove(); $(table).find('.tablesorter-headerAsc > div').append('<span class="glyphicon glyphicon-chevron-up" />'); … -
Django models ManyToManyField always adding item to list
I'implemented two models, Card and Dish. I used many-to-many relationship because Dish can be in many cards. Not sure if I did that right because any Dish that I add is automatically added to every Card. Here is the code: class Dish(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1000) price = models.DecimalField(max_digits=5, decimal_places=2) preparation_time = models.IntegerField() date_added = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) vegan = models.BooleanField(default=False) def __str__(self): return self.name class Card(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1000) date_added = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) dishes = models.ManyToManyField(Dish, blank=True) def __str__(self): return self.name An the problem in admin panel looks like this: When I create a dish it is alway added to every card. Any help please I'm just begining to learn sql and django ORM -
Djnago rest framework html/url to docx
I am creating a Django API that converts any URL or HTML file into pdf and Docx. The implemented code below already renders in pdf format using pdfkit package. I'm using python-docx to generate in Docx, but I don't know how to handle it. I would like to have any support, please. I don't have deep knowledge and any help will be appreciated. Here is my convert.py file: import io from pydoc import doc from tempfile import NamedTemporaryFile from typing import IO from urllib.parse import urlparse import pdfkit from docx import Document class ConvertingError(Exception): """ This exception represents an error during converting. In example, when Host of a url is unreachable. In other words, this is a wrapper for wkhtmltopdf errors. """ pass def url_to_pdf(url: str) -> IO: """Fetch HTML from url and convert the page to pdf,""" with NamedTemporaryFile('w+b') as tmpf: try: pdfkit.from_url(url, tmpf.name) except OSError as e: raise ConvertingError from e pdf = io.BytesIO(tmpf.read()) return pdf def html_to_pdf(html: str) -> IO: """Convert HTML string to pdf.""" with NamedTemporaryFile('w+b') as tmpf: try: pdfkit.from_string(html, tmpf.name) except OSError as e: raise ConvertingError from e pdf = io.BytesIO(tmpf.read()) return pdf def filename_from_url(url: str) -> str: """ Generate pdf filename using a hostname … -
Update function creating new object instead of updating existing in django?
i am creating a comment update function using django and ajax, and i am trying to update the comment without refreshing the page, now when i click on the edit button, the exisiting comment get filled in the input box ready for edit, when i edit the text (comment) instead of saving the new edit to the old one; it goes ahead an create a new comment all together, how do i prevent that. view.py ## edit comment @csrf_exempt def edit_comment(request): if request.method == "POST": id = request.POST.get("cid") comment = Comment.objects.get(pk=id) comment_data = {"id": comment.id, "comment": comment.comment, "video": comment.video.id} return JsonResponse(comment_data) ## Create comment def ajaxComment(request): if request.method == "POST": pk = request.POST.get("id") video = Video.objects.get(id=pk) user = request.user comment = request.POST.get("comment") new_comment = Comment(user=user, video=video, comment=comment) new_comment.save() print(id) print(user) print(comment) print(video) response = "Comment Posted" return HttpResponse(response) ajax code // Edit $('.comment-wrapper').on("click", ".btn-edit", function(){ console.log("Edit Button Cliked"); let id = $(this).attr("data-cid"); console.log(id); mydata = {cid:id} $.ajax({ url: "{% url 'edit-comment' %}", method:"POST", data:mydata, success: function(data){ console.log(data); $("#id").val(data.id) $("#id").val(data.video) $("#comment").val(data.comment) // $(".new_comment").val(data.video) console.log(data.id); }, }) }) $(document).on("submit", "#comment_form", function(e){ e.preventDefault(); let _comment = $("#comment").val() console.log("send button clicked") $.ajax({ type: "POST", url: "{% url 'save-comment' %}", data:{ id: $("#id").val(), comment: _comment, … -
In Django, I have added my app to INSTALLED_APPS but still can't use makemigrations command
I have added my app to INSTALLED_APPS This is my class created for the app And here, I have registered my app to the admin panel -
uploaded video not showing up
So I have uploaded videos for a class model for an educational website but that video is not being rendered. What can I do to render it? My models.py: class Class(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='class/class_videos',null=True, validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) def __str__(self): return self.title class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) students = models.ManyToManyField(User, related_name='courses_joined', blank=True) classes = models.ForeignKey(Class, on_delete=models.CASCADE, null=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title My views.py: class CourseDetailView(LoginRequiredMixin, DetailView): model = Course template_name = 'class/course.html' My html file : {% extends "class/base.html" %} {% load crispy_forms_tags %} {% block content %} <h1>{{ object.title }}</h1> {{ object.classes.video }} {% endblock content %} The output is the title of the class and the <name>.mp4 filename where name is the name of the video file I uploaded. But I want the video to be rendered. Can anyone help me ? Thanks in advance! -
How to know what serializer_class is used
I define a serializer class in the get_serializer_class function. In my update function, how can I know which serializer class is selected? What is the best practice for this? Simple code: class SomeViewSet(ModelViewSet): model = SomeModel def get_serializer_class(self): # here I define my serializer class, let's say between FirstSerializerClass and SecondSerializerClass def update(): if serializer_class == FirstSerializerClass: # I checked this way, but it didn't work for me -
django rest framwork filter by year or month
How can i filter date by year or by month in django rest framework my model class DailyJues(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.IntegerField() date = models.DateField(default=timezone.now) my views class DailyJuesViews(APIView): def get(self, request): daily_jues = DailyJues.objects.all() serializer = DailyJuesSerializers(daily_jues, many=True) return Response(serializer.data) def post(self, request): serializer = DailyJuesSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django-admin startproject foo : Access denied
I am trying to install django and create a project I am not able to get any success I have looked on internet but could not find solution for this. I am also running my cmd with admin. I have also check permission of folder. I also tried running in virtual env but same error. -
How to use group by, max of a column and also getting other columns of the model from a Django queryset?
I have a model that looks like this class Documents(models.Model): id = models.AutoField(primary_key=True, editable=False) uid = models.CharField(max_length=64) version = models.IntegerField() reviewed_dtm = models.DateTimeField(null=True) timestamp = models.DateTimeField(auto_add_now=True) document = models.FileField() I want the average time difference between the timestamps for the maximum version and the minimum number for every uid. I basically want to know the average time it takes for a document to be reviewed by a user since its creation. Being reviewed is optional, if a user finds the document to be good then marks it as reviewed, or else sends it for the new version. Then another record is made for the uid with an updated version. -
Return many to many field queryset as json
I am trying to return all the results of a many to many query (all the customers linked to a store i.e. a customer can be linked to many stores). I have the following models and serializers class Customer(models.Model): stores = models.ManyToManyField(Store) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) ... class Store(models.Model): store_name = models.CharField(max_length=30, unique=True, null=True) ... class CustomerSerializer(serializers.ModelSerializer): stores = serializers.PrimaryKeyRelatedField(queryset=Store.objects.all(), write_only=True, many=True) class Meta: model = Customer fields = ['stores', 'first_name', 'last_name', ...] In my views, I want to get all the customers in a store and return them like this: def return_customers(request, *args): ... store = Store.objects.get(account__email=user) customers = Customer.objects.filter(stores__id=store['id']) print(customers) json_customers = CustomerSerializer(customers).data print(json_customers) context = { 'customers': json_customers, } return Response(context, status=HTTP_200_OK) This returns an empty object {} print(customers) gives: <QuerySet [<Customer: Michael>, <Customer: Naomi>, <Customer: Blessing>, <Customer: John>, <Customer: Cena>]> print(json_customers) gives: {} If I try to return customers instead of json_customers, I get error message (Type Error): Object of type Customer is not JSON serializable If I try json_customers = CustomerSerializer(customers[0]).data I get only the first customer (I want all of them): "customers": { "id": 7, "first_name": "Michael", "last_name": "", ... }, I have tried this with other models that don't … -
Should I use Many-to-one relationship or a Many-to-many?
Basically I am creating a website using django where I have created a class called courses and a separate class Class. I'm now confused which relationship I should use. My code: class Class(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='class/class_videos',null=True, validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) def __str__(self): return self.name class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) students = models.ManyToManyField(User, related_name='courses_joined', blank=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title Thanks in advance! -
How to hide an HTML generated link that should only be called by javascript addeventListener?
I have a Django app, and want to have an image appear on a webpage only when someone clicks a specific element/image 30 times as such: var count = 0; document.addEventListener('DOMContentLoaded', function(){ document.querySelector("#PDDO").onclick = function(){ if(count > 30){ document.querySelector("#PDDO").src = document.querySelector("#PDDO").dataset.over }else{ count++; } }}) When this code is executed, the original image is replaced with the hidden image, which is hardcoded in the URL as such: <img src="{% static 'database/images/original_image.png' %}" width="200", height="200", class="revolve" id="PDDO" data-over="{% static 'database/images/new_image.png' %}"> </div> However, people can easily find the source of this image simply by inspecting the page source code, and I can't seem to hide it: #Page source: <img src="/static/database/images/original_image.png" ,="" class="revolve" id="PDDO" data-over="/static/database/images/new_image.png" width="200" height="200"> I tried to implement js solutions such as below, but to no avail. $("a[data-label='document.querySelector("#PDDO").dataset.over']").hide() What is the best way to hide the image url from the page source? -
Is this way to reset password fine?
I wrote a code to resetting user password. I just want to ask if it is a good and secure way to do this? Can I make any improvements here? I use send_password_resetting_message function to send an email with a link to reset password and when I go on this page I use there set_new_password to set new password using uidb64, token and new password. I am using DRF. views.py from .utils import password_reset_token @api_view(['POST']) def send_password_resetting_message(request): try: email = request.data['email'] if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) email_subject = "..." email_body = render_to_string('password_resetting/index.html', { 'user': user, 'domain': settings.FRONTEND_APP_ADDRESS, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': password_reset_token.make_token(user) }) email=EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[email]) email.content_subtype='html' email.send() return Response(status=status.HTTP_200_OK) except: return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['POST']) def set_new_password(request, uidb64, token): try: uid = force_text(urlsafe_b64decode(uidb64)) user = User.object.get(pk=uid) except Exception as e: user=None if user and password_reset_token.check_token(user, token): user.set_password(request.data['password']) user.save() return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_403_FORBIDDEN) utils.py class PasswordResetTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.password)) password_reset_token = PasswordResetTokenGenerator() -
Django - doesn`t make the migrations
In Django, after I created a model, in cmd I runned: "python manage.py makemigrations" and returned that: Migrations for 'hello': hello\migrations\0001_initial.py - Create model Article hello is the name of app. And after I runned: "python manage.py migrate" returned: Operations to perform: Apply all migrations: admin, auth, contenttypes, hello, sessions Running migrations: No migrations to apply. And when I try to introduce a field in that model appear: OperationalError at /admin/hello/article/add/ no such table: hello_article I tried to delete all migrations and I created again the model and the result was the same. How fix this? -
count all objects within a values_list Django
This is a follow up question to this Django object has no attribute in a _set.filter @property def mathe2(self): return self.lehrertabelle_set.count() @property def mathe3(self): return self.lehrertabelle_set.values_list('Stundenanteil_bei_WE', flat=True)[0] + self.mathe2 I got so far that I can calculate that but I need everything within values_list counted together, pls tell me how, I have no clue