Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limit on Number of cart-products
I'd like to set a limit on the number of products that can be added on a cart. --Case scenario: Assuming delivery-resource scarcity, I don't want users to add more than 5 products at a time. (The quantity of same product can, however, be raised) cart-app/cart.py def add(self, product, quantity=1, override_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def __iter__(self): products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item I've tried slicing my queries but this doesn't work. Any ideas? -
How to know which group a user belongs to
I am developing an application that allows me to control the users that belong to a certain group, but I find a problem that I don't know how to do correctly, I currently have two groups that are day and night, but I have a problem, and that is that those groups They are validated to know which one they belong to and thus show only information from that group, but if I wanted to add more groups than I have, is there a way to know which group a user belongs to and so on to be able to validate the information that I show in templates, this is my model: class User(AbstractUser): def get_full_name(self): return f'{self.first_name} {self.last_name}' @receiver(post_save, sender=User) def group_user(sender, instance, *args, **kwargs): if instance.groups: if instance.groups == 'diurno': group = Group.objects.get(name='diurno') instance.groups.clear() instance.groups.add(group) else: group = Group.objects.get(name='nocturno') instance.groups.clear() instance.groups.add(group) This is my view: class CarListView(LoginRequiredMixin, ListView): login_url = 'users:login' template_name = 'index.html' paginate_by = 6 def get_queryset(self): group = self.request.user.groups.filter( name='diurno').exists() if group: return Car.objects.annotate(Count('partner')).order_by('-pk') else: user = User.objects.filter(pk=self.request.user.pk).first() return Car.objects.filter(user=user) -
Pycharm CE not hitting breakpoints in my Django project
I have my project properly configured to run manage.py in the right place, with the right settings. I also have debug breakpoints set in a method that I know with certainty is being executed. The breakpoints are not disabled or conditional: When I hit the "Run in debug mode" button, using the above run configuration (I'm sure it's the same one because it's the only one I've configured for this project), this is the console output I get: pydev debugger: process 38083 is connecting Connected to pydev debugger (build 192.5728.105) Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 23, 2020 - 19:22:22 Django version 3.1.4, using settings 'FEArena.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However, when I use a REST client to trigger the above method, the one with breakpoints in it, the breakpoints do not trigger and the debugger doesn't start. I get a 200 OK response in my REST client, but PyCharm does not stop and execute the debugger at any point. I looked at other answers that advised setting "Gevent compatible debugging" (which I don't have, because I'm using Community Edition), and I've tried … -
Django model store information for each user
I am building a competition website where challenges will be released weekly. For each user I want to track if they have completed a challenge but cannot see how this would be done. Currently the challenges are stored as a model and am using the ListView and DetailView to display them. from django.db import models from django.contrib.auth.models import User STATUS = ( (0, 'Draft'), (1, 'Publish'), ) class Challenge(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) release_date = models.DateTimeField() preamble = models.TextField() ciphertext = models.TextField() plaintext = models.TextField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-release_date'] def __str__(self): return self.title Thank you in advance to anyone who helps me with this. Oh and a solution will be submitted and then checked with this form. <div class='form'> {% if user.is_authenticated %} <textarea rows="10" name="plaintext" form="submitAnswer" wrap="soft" placeholder="Plaintext.."></textarea> <form method="post" id="submitAnswer"> {% csrf_token %} <input type="submit" value="Submit"> </form> {% else %} <p>Must be logged in to submit answer.</p> {% endif %} </div> -
Exception Value: libFreeCADApp.so: cannot open shared object file: No such file or directory
I can't figure out how to use external library as python module in production. Any help on this issue is much appreciated. I am importing FreeCAD as python module in my django app as follow. views.py import sys sys.path.append('freecad/lib') import FreeCAD import Part And Freecad bin and library files reside at root directory where manage.py file is as shown below. Everything works fine on my local sever. I can import FreeCad and do data processing on CAD files. But things start to break when I deploy app on google cloud engine. After deployment it threw this error. Exception Value: libFreeCADApp.so: cannot open shared object file: No such file or directory I also built docker image of this application to make sure consistent dependencies. But same result local sever finds Freecad library and runs fine, but docker throws this error. ModuleNotFoundError: No module named 'FreeCAD'. -
No Reverse Match in login view Django, html template parsing error
I have an issue with my django application. My base.html template can be parsed in certain views but not in all of them and returns an error code I do not have much experience with django but it seems to be that it can parse the template when the views aren't too far away from each other. I also have a very bad structure, but I have no clue how to properly structure a django website. login file (doesn't work): <!--hovedside/templates/registration/login.html--> {% extends "base.html" %} {% block body %} <h2>Login</h2> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Login"></input> </form> <a href="{% url dashboard %}">Back to dashboard</a> {% endblock body %} dashboard file (works): <!--hovedside/templates/users/dashboard.html--> {% extends "base.html" %} {% block body %} <div class="default-bodycontainer"> <h1>Hello, {{ user.username|default:'Guest' }}!</h1> </div> {% endblock body %} Filestructure for templates: templates/base html templates/registration/login html templates/users/dashboard html urls python file from django.urls import path from django.conf.urls import include, url from . import views app_name = "hovedside" urlpatterns =[ path("", views.index, name="index"), path("dashboard/", views.dashboard, name="dashboard"), #path("accounts/", include("django.contrib.auth.urls")), url(r"^accounts/", include("django.contrib.auth.urls")), ] problematic line from base.html: <link rel="icon" href="{% static 'hovedside/img/favicon.ico' %}"> This is just the first line with static in the html template. [Filestructure][1] Full code … -
My Django & React program crushes with Forbidden 403 Error
I am creating a project following the YouTube tutorial at this link: https://youtu.be/JD-age0BPVo?t=133 I recently did the 6th and 7th video, but accidentally, I started from the 7th and got back to the 6th video. I am currently getting the Forbidden errors when I try to click Create Room button: Forbidden: /api/create-room [23/Dec/2020 13:46:38] "POST /api/create-room HTTP/1.1" 403 58 Interestingly, I have no required login/permission/test. I can't understand what is forbidden. I read other Django 403 Error questions and they usually have authorization steps that gives that error but I don't have it. Since the first line of error has POST in it, I am copying my only pieces of code including POST in them. CreateRoomPage.js: handleRoomButtonPressed() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ votes_to_skip: this.state.votesToSkip, guest_can_pause: this.state.guestCanPause, }), }; fetch("/api/create-room", requestOptions) .then((response) => response.json()) .then((data) => this.props.history.push("/room/" + data.code)); } views.py: class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, … -
Django template custom filter does not change size of button
I have a Django template variable and custom filter inside a button stylized with bootstrap 4. <button type="submit" class="btn btn-outline-dark text-left mb-2" disabled> {{ my_variable | my_filter}} </button> If my_filterincreases the length of my_variable, I find that the size of the button is not automatically extended as I assume that its size is processed by Django before the filter is applied. Is there a way around this? -
Run a subprocess along with Django runserver
I am a novice at Django. I have a simple python script which I execute via a custom command using manage.py, which in turn sets up a subprocess that keeps running. I am using the subprocess to publish message to all channels connected to my server. Right now, the way my code works is that my server runs in one terminal tab while I use a second terminal to run my custom command. My question is, what do I need to do so that whenever I start my server, the subprocess automatically begins in background and keeps on running until server is stopped? I have tried adding the subprocess to ready method of my apps.py, but that does not work. I also tried using channels' background tasks, but that again require executing another command. My custom command handler file from django.core.management.base import BaseCommand from asgiref.sync import async_to_sync import subprocess from channels.layers import get_channel_layer channel_layer = get_channel_layer() class Command(BaseCommand): def handle(self, *args, **kwargs): with subprocess.Popen(['python3', '-u','script.py'],stdout=subprocess.PIPE, bufsize=0, universal_newlines=True) as p: for line in p.stdout: line = str(line.rstrip()) print(line) async_to_sync(channel_layer.group_send)('logwatcher', {'type': 'chat_message','message': line}) p.stdout.flush() Please help me as to what to use and how to use it. Just the link to relevant … -
attempt to write a readonly database
OperationalError at /users/ Request Method: POST Request URL: http://localhost:8000/users/ Django Version: 3.0.3 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: C:\Users\parul\anaconda\envs\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Users\parul\anaconda\envs\MyDjangoEnv\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\parul\Desktop\Djangoforms\ProTwo', 'C:\Users\parul\anaconda\envs\MyDjangoEnv\python38.zip', 'C:\Users\parul\anaconda\envs\MyDjangoEnv\DLLs', 'C:\Users\parul\anaconda\envs\MyDjangoEnv\lib', 'C:\Users\parul\anaconda\envs\MyDjangoEnv', 'C:\Users\parul\anaconda\envs\MyDjangoEnv\lib\site-packages'] Server time: Wed, 23 Dec 2020 16:14:46 +0000 Also, i checked the properties in db.sqlite3, all the permissions are checked...write permission also can anyone help using windows... i tried : cacls . /t /e /g everyone:f but still facing the same issue -
I am getting Integrity error in django rest framework
I am begginer in django. I would like to add some posts and comments but I am getting an Integrity error. Without comments model it was working before but it doesn´t work together. I already delete my database and makemigrations and migrate again. post models from django.db import models from django.conf import settings # from django.contrib.auth import get_user_model # User = get_user_model() # Create your models here. class Post(models.Model): user = models.ForeignKey( #to=User, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts', null=True ) content = models.CharField( max_length=150, blank=False ) created = models.DateTimeField( auto_now=True ) liked_by = models.ManyToManyField( #to=User, to=settings.AUTH_USER_MODEL, related_name='liked_posts', blank=True ) post serializer from rest_framework import serializers from .models import Post from ..comment.serializers import CommentSerializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post comments = CommentSerializer(source='comments.content') fields = [ 'id', 'user', 'content', 'comments', 'created', 'liked_by', ] comment.models from django.db import models from django.conf import settings from apps.post.models import Post # Create your models here. class Comment(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comment', null=True) post = models.ForeignKey(to=Post, on_delete=models.SET_NULL, related_name='comment', null=True) content = models.CharField(max_length=150) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Comment by: {self.user}' comment serializer from rest_framework import serializers from .models import Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'post', 'content', 'created'] -
Django filter data using field in another model connected via foreign key
I have two models; Sets and Cards. There are many cards in one set. I would like to get it so that I can filter the cards that are returned in my tables but the set code, which for the example below is khc. I have manage to get it to work to an extent by adding filter(set__code__exact="khc") to the Card.objects but this does not allow the user to change that filtering on the web page. I cannot seem to add a code filter to the CardFilter models.py class Set(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) code = models.CharField(max_length=64) ... class Card(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name='Card') views.py def cards_page(request): card_list = Card.objects.filter(set__code__exact="khc").order_by('name') card_filter = CardFilter(request.GET, queryset=card_list) card_list = card_filter.qs filters.py class SetFilter(django_filters.FilterSet): code = CharFilter(field_name='code', lookup_expr='iexact', label='', widget=TextInput(attrs={'placeholder': 'Set Code', 'class': 'page-input', 'style': 'width: 150px;'})) name = CharFilter(field_name='name', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Name', 'class': 'page-input', 'style': 'width: 150px;'})) type = CharFilter(field_name='type', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Type', 'class': 'page-input', 'style': 'width: 150px;'})) class Meta: model = Set fields = '' class CardFilter(django_filters.FilterSet): # doesnt work # code = CharFilter(field_name='set', lookup_expr='iexact', label='', widget=TextInput(attrs={'placeholder': 'Set Code', 'class': 'page-input', 'style': 'width: 150px;'})) name = CharFilter(field_name='name', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Name', 'class': … -
How to exclude model name and model field names from built-in error message or how translate custom error message in Django/DRF?
I have a User model with email as unique field class User(AbstractBaseUser): ... email = models.EmailField( max_length=50, unique=True, ) ... For serialization I use ModelSerializer: class UserRegisterSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=30, write_only=True ) class Meta: model = User fields = ['email', 'password'] When I attempt to create a new User instance with already taken email, I get such message in response: { "email": [ "user with this email already exists." ] } Seems like everything is ok, except the fact, that when I send request with Accept-Language in headers, I get only partially translated message, like: { "email": [ "email դաշտի այս արժեքով user արդեն գոյություն ունի" ] } As you can see there are untranslated words in message, which are email (model field) and user (model name). The question is : How to customize this message in order to exclude field name and model name and get only for example: { "email": [ "already exists." ] } If someone is going to suggest override UniqueValidator, I tell in advance: already tried that, like: class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email' 'password'] email = serializers.CharField( validators=[UniqueValidator( queryset=Meta.model.objects.all(), message="already exists" )] ) password = serializers.CharField( max_length=30, write_only=True ) … -
Django one-to-many relation: optimize code to reduce number of database queries executed
I have 2 models with a one-to-many relation on a MySQL DB: class Domains(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True, null=True) class Kpis(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True, null=True) domain_id = models.ForeignKey(Domains, on_delete=models.CASCADE, db_column='domain_id') In order to bring ALL the domains with all their kpis objects, i use this code with a for loop: final_list = [] domains_list = Domains.objects.all() for domain in domains_list: # For each domain, get all related KPIs domain_kpis = domain.kpis_set.values() final_list.append({domain:domains_kpis}) The total number of queries i run is: 1 + the number of total domains i have, which is quite a lot. I'm looking for a way to optimize this, preferably to execute it within only one query on the database. Is this possible? -
Data from dynamically created inputs table is not passing to backend
I am trying to pass multiple data from an input table (with row addable option) in the backend and for saving them in my database. Here I try to use Django and MongoDB. My frontend's JS & HTML code is: let i = 1; function rowTemplate(i) { return `<tr data-index=${i}> <td>${i}</td> <td><input type="text" name="name-${i}"></td> <td><input type="text" name="roll-${i}"></td> <td><input type="email" name="email-${i}"></td> <td><input type="text" name="password-${i}"></td> <td><input type="text" name="address-${i}"></td> <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;" onclick="removeRow(${i})"></i></td> </tr>` } for (i = 1; i <= 4; i ++) { $('.my_dynamic_table').append(rowTemplate(i)); } function removeRow(i) { $(".my_dynamic_table").find(`tr[data-index='${i}']`).remove(); } function addRow() { $('.my_dynamic_table').append(rowTemplate(i)); i++; } <div class="container my-5"> <h2>Welcome to dynamic input table with row adding option</h2> <form class="" method="POST"> {% csrf_token %} <table class="table table-hover my-5"> <thead class=""> <tr> <th>No</th> <th>Name</th> <th>Roll</th> <th>Email</th> <th>Password</th> <th>Address</th> <th>Remove?</th> </tr> </thead> <tbody class="my_dynamic_table"> </tbody> </table> <div class="row m-0"> <button class="btn btn-warning" onclick="addRow()">Add row</button> <button type="Submit" class="btn btn-primary ml-auto">Submit</button> </div> </form> </div> <head> <title></title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <!-- animated css link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/> <!-- font awsome css link --> <link rel="stylesheet" … -
Is there anything wrong with my Django urls.py code?
I have been developing a django app and the URL i want to go to says it's 404 Not Foundbecause there is a space in between the URL??? (see URL no. 10 below) Is there anything wrong with my code??? urls.py in meditatetimer app: from django.urls import path from .views import main, stop urlpatterns = [ path('', main), path('/stop', stop) ] urls.py in project: from django.contrib import admin from django.urls import path, include from django.urls.conf import include urlpatterns = [ path('admin/', admin.site.urls), path('', include('landing.urls')), path('roles/productivity/planner/', include('planner.urls')), path('roles/productivity/memo/', include('memo.urls')), path('roles/productivity/focus-timer/', include('focustimer.urls')), path('roles/meditation/meditate-timer/', include('meditatetimer.urls')), path('roles/meditation/diary/', include('diary.urls')), path('roles/meditation/qotd/', include('qotd.urls')), ] views.py in meditatetimer app: from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import TimeForm from .models import Event def main(request): time_form = TimeForm(request.POST or None) if request.method == "POST": #if time_form.is_valid(): time_form.save() return redirect('/roles/meditation/meditate-timer') else: time_form = TimeForm() timer = Event.objects.all() context = { 'timer': timer, 'time_form' : time_form, } return render(request, 'index.html', context) def stop(request): timer = Event.objects.all() timer.delete() return redirect ('/roles/meditation/meditate-timer') if I remove the slash in meditatetimer's url would only show the same thing, but now it's roles/meditation/meditate-timer/ stop (the space will still be there) Thank you in advance, I'd really appreciate any help. -
Django registration form in two steps depending on usertype
I'm quite new with Django but now I'm working on a project that needs a universal user registration and after that create a second form to save some other profile fields based on usertype. I have create this: model.py # Create your models here. class User(AbstractBaseUser, PermissionsMixin): USER_CHOICES = ( ('galerist', 'GALERISTA'), ('collector', 'COLLECTOR'), ('artist', 'ARTISTA'), ('curator', 'CURADOR'), ('general', 'GENERAL'), ('press', 'PRENSA') ) username = models.CharField(max_length=20, unique=True) usertype = models.CharField(max_length = 20, choices = USER_CHOICES, default = 'normal') image = models.ImageField(upload_to='media',blank=True, null=True) email = models.EmailField() nombre = models.CharField(max_length=30, blank=True) apellidos = models.CharField(max_length=30, blank=True) telefono = models.CharField(max_length=12, blank=True) empresa = models.CharField(max_length=30, blank=True) direccion = models.CharField(max_length=100, blank=True) ciudad = models.CharField(max_length=15, blank=True) pais = models.CharField(max_length=20, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = UserManager() def get_type(self): return self.usertype def get_full_name(self): return self.nombre + ' ' + self.apellidos def __str__(self): return self.username class CollectorProfile(models.Model): VISITA_CHOICES = ( ('1', '1'), ('2', '2'), ('3+', '3+'), ('Nunca', 'NUNCA') ) COMPRA_ARTE_CHOICES = ( ('1+', 'Más de una vez al año'), ('1-2', 'Cada 1 - 2 años'), ('3-5', 'Cada 3 – 5 años'), ('1era', 'Estoy buscando comprar mi primera obra') ) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=64) company … -
Facing Issue when giving restricted permissions to particular group in Django
I am trying to make a REST API using Django REST Framework. In the section of Authentication and Authorization I created 2 groups namely Manager (which has permissions to perform CRUD on database) and Staff (which has only view permission). Using serializers I am displaying the data in json format. But I am still able to perform CRUD operation using Staff account. How can I fix that? REST API View -
Override Django allauth SignupView to create ForeignKey object in custom user model
I have a custom User model with a FK : # users.models.py class User(AbstractUser): company = models.ForeignKey("Company", related_name="members", on_delete=models.PROTECT) # other fields I want a user to be able to send an invitation to someone else by mail with a custom link with a token in the url : # users.urls.py app_name = "users" urlpatterns = [ path("signup/", view=views.account_signup_view, name="account_signup"), path("signup/<uuid:token>", view=views.account_signup_view, name="account_signup_token"), So I write a view that inherit the SignupView of allauth # users.views.py class AccountSignupView(SignupView): def __init__(self,*args,**kwargs): super(SignupView, self).__init__(*args,**kwargs) def form_valid(self, form, *args, **kwargs): token_value = kwargs.get('token', '') self.user = form.save(self.request) if token_value: try: token = Token.objects.get(value=token_value) if token.expired: raise ObjectDoesNotExist else: self.user.company = token.company except ObjectDoesNotExist: return HttpResponse("Invitation expired or invalid") else: self.user.company = Company.objects.create() self.user.save() response = super(SignupView, self).form_valid(form) return response The line self.user = form.save(self.request) raises an IntegrityError since company is empty and SignupForm has no commit kwargs. Otherwise I could save(commit=False) I've tried to adapt the save method of allauth SignupForm but it gives me more and more problems since key is empty # users.forms.py class SignupFormCommit(SignupForm): def save(self, request, token=None): adapter = get_adapter(request) user = adapter.new_user(request) if commit: adapter.save_user(request, user, self) self.custom_signup(request, user) setup_user_email(request, user, []) else: adapter.save_user(request, user, self, commit=False) return … -
How do I use django_tables2 with a filter?
I'm displaying data on a webpage, and I would like to migrate this code to use the table I created in tables.py. I can't figure out how to do it without breaking the filter. views.py def PlatListView(request): queryset = Plat.objects.all().values('id', 'description','status', 'phase__number','phase','schedule_found').annotate(lot_count=Sum('phase__lot_count')).order_by('description') f = PlatFilter(request.GET, queryset=queryset) return render(request, 'blog/filtertable2.html', {'filter': f}) filters.py class PlatFilter(django_filters.FilterSet): community = ModelChoiceFilter(queryset=Community.objects.all()) tables.py import django_tables2 as tables class PlatTable(tables.Table): id = tables.Column() description = tables.Column() status = tables.Column() phase__number = tables.Column() lot_count = tables.Column() schedule_found = tables.Column() class Meta: ordering = 'description' #model = Plat -
Able to run Django server on PyCharm but not on command line?
I configured my virtual environment with virtualenvwrapper and I can run the server when I hit the run button on PyCharm. But when I type in manage.py runserver on my command line, I get this error message. raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I'm using the PyCharm .env plug-ins to export my variables. And my .env file is sitting on the root of my project folder. -
How to add chat feature in django web
I made A Django app which has sign Up/log in feature I want To Add "Chat feature in this app" which allows different user to connect and communicate with each other seprately after verifying their credentials. Could any one help me how to do this? -
pyjwt[crypto] 2.0.0 update incompatible with django-allauth
I have a project that uses django-allauth 0.44.0. Yesterday (12/22/20) pyjwt update your version to 2.0.0. When i try to install my dependencies running pip, return this error message, using docker-compose: Collecting pyjwt[crypto]>=1.7 ERROR: In --require-hashes mode, all requirements must have their versions pinned with ==. These do not: pyjwt[crypto]>=1.7 from https://files.pythonhosted.org/packages/91/5f/5cff1c3696e0d574f5741396550c9a308dde40704d17e39e94b89c07d789/PyJWT-2.0.0-py3-none-any.whl#sha256=5c.... (from django-allauth==0.44.0->-r requirements-dev.txt (line 125)) ERROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements-dev.txt' returned a non-zero code: 1 In Poetry.lock: [[package]] name = "django-allauth" version = "0.44.0" description = "Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication." category = "main" optional = false python-versions = "*" [package.dependencies] Django = ">=2.0" pyjwt = {version = ">=1.7", extras = ["crypto"]} python3-openid = ">=3.0.8" requests = "*" requests-oauthlib = ">=0.3.0" [[package]] name = "pyjwt" version = "1.7.1" description = "JSON Web Token implementation in Python" category = "main" optional = false python-versions = "*" Anybody do have the same issue? Thanks -
TemplateDoesNotExist at /. i dont know where i'm wrong
I don't know where i'm wrong, i'm fairly new to this so please tell me where i'm wrong. help me please, this is views.py from django.shortcuts import render def home(request): return render(request, 'home.html') urls.py """portfolio URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home) ] path manage.py db.sqlite3 views.py urls.py settings.py asgi.py wsgi.py __init__.py templates/home.html i'm using Django 3.0.10 -
How can I add image saved in the file system to the ImageField in the model?
I am trying to genera .svg QR code, save it to the file system and somehow map it with ImageField in the model. I do not really get what and how I should put into the model, so it would be "linked" with the image file. Please help me find the way. :) models.py class PinModel(models.Model): pin = models.CharField(max_length=6, unique=True) user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) qr = models.ImageField(upload_to='qr/', blank=True, null=True) views.py class PinView(viewsets.ModelViewSet): queryset = PinModel.objects.all() serializer_class = PinSerializer def create(self, request, *args, **kwargs): pin = "123456" img = qrcode.make(pin, image_factory=qrcode.image.svg.SvgImage) # img is my SvgImage object img.save("qr/qrcode.svg") # now I just drop it here pin_post = PinModel.objects.create(pin=pin, user=user) # I've tried to add (qr=img) here serializer = PinSerializer(pin_post) return Response(serializer.data, status=status.HTTP_200_OK) So at this point, I have qrcode.svg in qr folder, but my PinModel is being created with Null values. I have tried to just save img, but that did not help me much. Later I am planning to generate word document with PinModel details and these svg images. How can I add image saved in the file system to the ImageField in the model? Thanks everyone!