Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Any suggestions on the methodology, languages and frameworks I should use to build a library managing robot?
I have a project to build an automated library robot.It will receive order of book from users by a website on library server and bring it.The robot and the webserver need to be connected to exchange data.Upon getting the necessary data from the webserver, the robot will search for the book using computer vision and bring the book to the user's table. -
Django FileField should only accept video files
here is my django model; class HomeVideo(models.Model): home = models.ForeignKey(Home, on_delete=models.CASCADE, related_name="home_videos") home_video = models.FileField( blank=True, null=True, upload_to="home_videos", ) def __str__(self): return str(self.home) According to this stackoverflow link: Only accept a certain file type in FileField, server-side(which is the closest I was able to find to what I want), I have to specify the file type that I want my application to support. But my problem is, I want my application to accept all video file format, without having to specify all the long list of video file formats; which of course won't scale, because new video file format would emerge from time to time. So is they any way I could solve this problem? -
Django or Flask. Aspiring software developer
I hope you are well. I am novice software developer and the next step on my learning journey is to learn how to use Django or Flask. Which framework would you recommend for someone who is just starting in this field? I look forward to hearing your thoughts. Thanks a lot in advance, Matías -
How to integrate screens with django, screen integration, screens designed to be joined with frontend?
How to integrate screens with django, screen integration, screens designed to be joined with frontend using visual studio -
DRF: A theoretical approach on the proper use of Serializers and ViewSets
I love Python and Django, and I've been learning Django REST Framework for the past weeks, because there is no escape to REST today in 2020. In my hobbie project (which is a Python forum, ridicously called Pyrty because it is a Python Party), I decided to make a CRUD for the comments app. I did it (except by update), but I don't get what is the difference between putting the code in the Serializer and/or in the ViewSet. My create and list are in the Serializer, while delete is in the ViewSet. All of them are working as expected, but I don't want to code dirty and I wish to understand the important points and differences of putting something in one part or the other. comments.models.py: class Comment(PyrtyModel): # the inheritance class just adds creation and modification dates, and sorting stuff user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=False) post = models.ForeignKey('posts.Post', on_delete=models.CASCADE, null=False) content = models.TextField(max_length=1000, null=False, blank=False) positive_votes = models.ManyToManyField('users.User', related_name='c_positive_vote_set') negative_votes = models.ManyToManyField('users.User', related_name='c_negative_vote_set') score = 0 def __init__(self, *args, **kwargs): # init with the score (positive votes - negative votes) if the comment is persisted super(Comment, self).__init__(*args, **kwargs) if self.id is not None: self.score = ( self.positive_votes.all().count() - … -
Django "temporary" User Accounts
I have a django application that handles online orders. I want to make it such that end users can use the app without making an account. My solution to this, to avoid changing the code as much as posisble, is that users who don't have an account will give their email which will be used to make a "temporary" account or whatever the proper term is. Said account ideally would be later "activated" and the user could choose their password or whatever. The package django-lazysignup seems to be a good solution to this but I was wondering if there were any other recommendations or ideas? What would the best or usual practice with something like this be? -
How do we use Bootstrap 4 login forms with default login auth? Can we just grab the value from context?
I have the following in my project setting urls: path('accounts/', include('django.contrib.auth.urls')), Which gives me out of the box support for login, logout, registration and more. Without using crispy forms, etc, is there a way I can grab the values from bootstrap template below: <form method="post"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="username" class="form-control" id="username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password"> <small id="passwordHelp" class="form-text text-muted">Password must be at least 6 characters.</small> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form> Or would I have to create my own log in function and do something like: username = request.POST.get("username") Classes are pretty complicating, and I am not sure how to go about this. Guidance would be appreciated. The tutorials I've seen all create their own forms in forms.py, but is there an easier way? -
ImportError: cannot import name 'Scheme'
when i type pip i get error File "/home/ubuntu/myproject/myprojectenv/bin/pip", line 6, in from pip._internal.cli.main import main File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/main.py", line 10, in from pip._internal.cli.autocompletion import autocomplete File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/autocompletion.py", line 9, in from pip._internal.cli.main_parser import create_main_parser File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/main_parser.py", line 7, in from pip._internal.cli import cmdoptions File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/cmdoptions.py", line 24, in from pip._internal.cli.progress_bars import BAR_TYPES File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/progress_bars.py", line 12, in from pip._internal.utils.logging import get_indentation File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/utils/logging.py", line 18, in from pip._internal.utils.misc import ensure_dir File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/utils/misc.py", line 31, in from pip._internal.locations import ( File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/locations.py", line 18, in from pip._internal.models.scheme import Scheme ImportError: cannot import name 'Scheme' -
Overriding Serializer's update() Function Fails
I have a view that calls patch() class ValidateResetPasswordView(views.APIView): def patch(self, request, token): serializer = ValidateResetPasswordRequestSerializer(instance=request.user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() . . . etc My serializer overrides update() to encrypt the password as class ValidateResetPasswordRequestSerializer(serializers.Serializer): password = serializers.CharField(max_length=128, required=True, allow_blank=False, allow_null=False, write_only=True) def update(self, instance, validated_data): instance.set_password(validated_data.get("password")) instance.save() return instance My serializer doesn't catch empty requests. For example, if a client sends out an empty json, my patch() gets processed successfully given no key was provided. { } I expect to get an error that says password is required, or the like. To prevent this issue, I had to manually validate whether a key exists or not within update() function as follows. class ValidateResetPasswordRequestSerializer(serializers.Serializer): password = serializers.CharField(max_length=128, required=True, allow_blank=False, allow_null=False, write_only=True) def update(self, instance, validated_data): if len(validated_data) == 0: # force validation raise serializers.ValidationError( 'Password is required') validated_data.get("password") instance.set_password(validated_data.get("password")) instance.save() return instance Am I violating any coding standards in here. Is there a better, correct, way to validate against empty requests? -
Querying total data by months in django
I have an issue getting the lists of all months and the totals of corresponding data sorted according to the months. I have tried a method which only return a dictionary of the current month as well as the total of all data irrespectively of whether it falls on that month or not. This is the query i have written for it po = { 'sales_sum': Sum('po_amount'), } queryset2 = PurchaseOrder.objects.values('created_on__month').annotate(**po).order_by('created_on__month') This method return the queryset below <QuerySet [{'created_on__month': 9, 'sales_sum': Decimal('429670')}]> But i wanted a key value pair like ("jan":50000, "feb":60000,"mar":70000) for all months and totals This is my model class PurchaseOrder(models.Model): created_on = models.DateTimeField(auto_now_add=True) po_amount = models.DecimalField(max_digits=10, decimal_places=2) I hope i can get a solution to this Thanks Oyero -
Django quiz application with different types of questions
I am building Django quiz application that will contain questions of 3 types of answers: Single option answer; Multiple option answer; Text answer; I am not sure how should I design django models for such pattern. At the moment my models look like this: class Question(CoreModel, models.Model): TYPES = ( (1, 'radio'), (2, 'checkbox'), (3, 'text'), ) type = models.CharField(max_length=8, choices=TYPES, default='radio') text = models.CharField(max_length=2048, null=False, blank=False) class Choice(CoreModel, models.Model): question = models.ForeignKey(Question, on_delete=models.DO_NOTHING) text = models.CharField(max_length=2048, null=False, blank=False) correct = models.BooleanField(default=False) class Answer(CoreModel, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) question = models.ForeignKey(Question, on_delete=models.DO_NOTHING) choice = models.ForeignKey(Choice, on_delete=models.DO_NOTHING) text = models.CharField(max_length=2048, null=False, blank=False) created = models.DateTimeField(auto_now_add=True) But it looks like it will not work as expected. I really don't like 'choice' and 'text' fields at the same time in my Answer model but that’s all I could think of. Any ideas or suggestions? Maybe I need some more other models for further logic? -
using CKEditor with Django and an inlineformset_factory with empty_form
When I render the empty form it is not attaching any media to it. i.e. the CKEditor is not displayed. The element looks like it is missing the css/js - it's like it doesn't get set up properly. Note : the other sections are displayed correctly. Where to start? Problem with Django's Empty Form method? Problem with CKEditor? Me :) <div class="container"> <button type ="button" class="btn-info btn-lg" id="add_section">Add Section</button> {{form.media }} {{form|crispy }} {{sections.media}} <div> {{sections.empty_form}} </div> <div id = 'section_management'> {{ sections.management_form }} </div> {% for section in sections %} {{ section|crispy }} {% endfor %} <button class="btn btn-info ml-2" type="submit">Update</button> <a href="{{ view.get_success_url }}" class="btn btn-secondary">Cancel</a> </div> Here's my Forms class SectionForm(forms.ModelForm): content = RichTextFormField() class Meta: model = Section fields = ('content',) empty_permitted=True def __init__(self, *args, **kwargs): print('section form called') super().__init__(*args, **kwargs) class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('title','category','span') def __init__(self, *args, **kwargs): self.is_superuser = kwargs.pop('is_superuser', None) super().__init__(*args, **kwargs) if self.is_superuser == False: self.fields.pop("span") -
I cannot solve django.urls.exceptions.NoReverseMatch: 'XXX' is not a registered namespace with Django3
I cannot solve "django.urls.exceptions.NoReverseMatch: 'XXX' is not a registered namespace" problem with Django3.1.1. I have seen similar issues on many websites, I cannot solve mine. The error message on browser is NoReverseMatch at / 'shiharaisaisokumoushitatesho' is not a registered namespace The error message on terminal is django.urls.exceptions.NoReverseMatch: 'shiharaisaisokumoushitatesho' is not a registered namespace I just want to show index.html on "http://127.0.0.1:8000/" page. ./conf/settings.py """ Django settings for conf project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'index.apps.IndexConfig', 'shiharaisaisokumoushitatesho.apps.ShiharaisaisokumoushitateshoConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'conf.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { … -
Django requires to restart the application server for each update - is there any way to do that with no restart?
I have a Django application deployed on the production server that is Windows in EC2. I am using Apache as a web server application. Everything is good except I have to restart Apache manually in each update. Is there any way to update my changes without restarting the web application server? -
CSS best practices while using Django
I've been working in a project for about 6 months, and I've been adding more urls each time. Right now, I'm coming into the problem that when I'm using extend 'base.html' into another pages, the CSS overlap, and I'm getting a mess. My question is: Which are the best practices when using extend for CSS files? Should every html file I create have it's own css? Or should I have one css that is called in the base.html file and from there all of the other html files take their styling from? This is what my base.html looks like: <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> </script> </head> <style> * { margin: 0; box-sizing: border-box; } html { font-size: 10px; font-family: sans-serif; } a { text-decoration: none; color: #ea0a8e; font-size: 18px; } header { width: 100%; height: auto; background: #121212; background-size: cover; position: relative; overflow: hidden; } .container { max-width: 120rem; width: 90%; margin: 0 auto; } .menu-toggle { position: fixed; top: 2.5rem; right: 2.5rem; color: #eeeeee; font-size: 3rem; cursor: pointer; z-index: 1000; display: none; } nav { padding-top: … -
using pandoc to generate pdf for Heroku
On my Django site I have a button that will create a word document and covert it into pdf file to show it to the user in a new window. Now this is done by reading a word document using docx and then docx2pdf to make the conversation. My problem is that when I launch it on Heroku to make it live, because heroku runs on linux this means that my document wont be created because im trying to generate it with docx. I think it may be possible to use pandoc. However I am have trouble implementing it. below is the word document generation and pdf generation without trying to implement pandoc. how can I implement pandoc with the code below: import docx def making_a_doc_function(request): doc = docx.Document() doc.add_heading("hello") doc.save('thisisdoc.docx') convert("thisisdoc.docx", "output.pdf") pdf = open('output.pdf', 'rb') response = FileResponse(pdf) return response pandoc documentation: https://pypi.org/project/pyandoc/ -
Django form wizard: Method to munipulate request before validating
I have been reading the Form Wizard docs trying to look for a method that can change the request.POST before validating the form. It seems like there are only methods for dealing with data after is_valid() is called -
Django retreive time when the post whas liked
I need to make a report showing analytics(time and user) of post likes and un-likes. model.py class Post(models.Model): user = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) likes = models.ManyToManyField(User, related_name="post_like") def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def total_likes(self): return self.likes.count() views.py ... def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get("post_id")) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse("posts:single", args=[str(post.user), str(pk)])) ... How can I get this data? -
How to iterate by query results and send it to template
I want to get random words from the database and create flashcards with them. For this moment I get a record from the database, send it to the template, and check if user's answer is correct. Look at the below code. In the end result, I want to rand 10 words and send it to the template (maybe in for loop) and after answer send information if it was correct (after each word). But I don't know how can I do it with store information in the learn() function about correct and wrong answers. learn.html {% block content %} {% if not result %} <form method="POST"> {% csrf_token %} <div class="row h-100 justify-content-center align-items-center"> <div class="card w-75 bg-light mb-3"> <div class="card-body"> <h5 class="d-flex flex-row-reverse">English - vocabulery</h5> <p class="d-flex flex-row-reverse">more information</p> <div class="form-group"> <label class="font-weight-bold" for="exampleFormControlInput1">{{word}}</label> <input class="form-control" name="wordAnswer" id="wordInput"translation placeholder="word translation"> </div> <div class="form-group"> <label class="font-weight-bold" for="exampleFormControlInput1">{{example}}</label> <input class="form-control" name="exampleAnswer" id="wordInput"translation placeholder="example translation"> </div> <button type="submit" class="btn btn-success" value="POST">Check</button> </div> </div> </div> </form> {% else %} Not correct answer {% endif %} {% endblock %} views.py def learn(request): words = Word.objects.get(id=1) if request.method == "POST": answer = request.POST['wordAnswer'] if answer == words.translation: return render(request, 'learn.html', { 'result': True, }) return … -
Make Django User model accessible as API endpoint
I'm running into the issue of my 'manager not having a get_by_natural_key()'error when I try logging in now to my site. I changed the default manager on my User model so I could get access to all the fields in my API, but now when I attempt to login (I'm using Djoser + Vue on the frontend for Auth), I think the the User manager and Djoser are in conflict. I'm pretty sure that the natural_key is tied to the fields I have on my login page, but I'm not 100% confident, can someone confirm? My question is: can I expose the User model as an endpoint and navigate around the get_by_natural_key error? Models.py class User(AbstractUser): user = models.Manager() GROUP_CHOICES = ( ('general','GENERAL'), ('director', 'DIRECTOR'), ) user_groups = models.CharField(max_length=10, choices=GROUP_CHOICES, default='GENERAL', null=False) Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: exclude = ["id"] model = User Views.py class UserViewSet(viewsets.ModelViewSet): model = User User = get_user_model() queryset = User.user.all() serializer_class = UserSerializer login.vue local: { endpoints: { login: { url: '/auth/token/login/', method: 'post', propertyName: 'auth_token' }, -
Django put values from database record into an array
I'd like to put my db record's values into my array (dates) which is defined outside my method, like this: dates = [] Code: dates_queryset = Profile.objects.all().filter(user=request.user) num = 1 for qr in dates_queryset: dates.append(qr.date) num += 1 -
New to Django - get list of users with the most posts
First post and new to python and django. I am trying to add context to a ListView so that I can display a list of top 5 most commented posts and also a list of top 5 most active users (users with most posts). I have got the first list working however can't work out the second list. Using the values method (i think it's a method) i've managed to query the database and get back a dictionary of user_id and posts count. My problem is that I want to display the username rather than the user_id. For some reason this query results in a dictionary rather than the full object. I've posted the code from views.py below. class PostListView(ListView): queryset = Article.objects.filter(published=True) template_name = 'articles/index.html' #address of non default template context_object_name = 'articles' #variable name passed to template ordering = ['-pub_date'] #get query results for popular posts and most active users side bar def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['most_commented'] = Article.objects.annotate(comment_count=Count('comments')).order_by('-comment_count')[:5] context['most_active'] = Article.objects.all().values('author').annotate(active=Count('author')).order_by('-active')[:5] return context Thank you for your help! Nick -
How to get user object using username in django template
I am trying to get user's profile picture in a template using their username. What I have tried: templatetags/users_extras.py: from django import template from django.contrib.auth.models import User register = template.Library() @register.filter(name="get_user", is_safe=True) def get_user(username): return User.objects.filter(username=username).first() My template: {% load users_extras %} <img src="{{ username|get_user.profile.image.url }}"> My Profile view: class Profile(ListView): model = Post template_name = "users/profile.html" context_object_name = 'posts' ordering = ['-datePosted'] def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-datePosted') def get_context_data(self, **kwargs): context = super(Profile, self).get_context_data(**kwargs) context['username'] = self.kwargs['username'] return context The url for profile page is like path('profile/<str:username>/', Profile.as_view(), name='profile') But that gives error Could not parse the remainder: '.profile.image.url' from 'username|get_user.profile.image.url' How can I fix this error or how can I get user object using username in django template? -
Javascript recommendations on creating PSD files from a set of images in browser
I'm working with a web app that is built with Reactjs and Django, and I was wondering what recommendations other devs have for creating a psd file from a set of images? I see that there are few libraries to parse psd files, but I'm not seeing any that will create a psd file from a set of images on the client-side. Didn't know if anyone had stumbled across a library or if I was going crazy. -
Celery -> Attribute Error -> DatabaseScheduler
I am trying to use docker - celery pair in one of my projects. The problem that I have is when I run (venv) C:\Users\yusuf\PycharmProjects\proje>docker-compose up I get error depicted below. Bu when I import DatabaseScheduler from django console, it can import. What may be the problem? How can I solve that? My project is on hold due to that error. Any help will be appreciated. Thanks.