Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with real time chat in django project
I have django project with rooms, and i want to create real time chat for rooms with channels library, this chat works with data from url kinda example.com/room_name/person_name, but i have rooms that have static url(example below),how to adjust that for my project. I want to show request.user.username instead of person_name in url, and i want to use room_detail url instead of room_name that i should type every time views.py class RoomDetail(DetailView): model = Room template_name = 'rooms/room_detail.html' context_object_name = 'room_detail' slug_field = 'invite_url' slug_url_kwarg = 'url' consumers.py class Consumer(WebsocketConsumer): def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name self.person_name=self.scope['url_route']['kwargs']['person_name'] async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.person_name+" Joined Chat" } ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.person_name+" Left Chat" } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json=json.loads(text_data) message=text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':self.user+" : "+message } ) def chat_message(self,event): message=event['message'] self.send(text_data=json.dumps({ 'message':message })) urls.py path('rooms/<url>/', RoomDetail.as_view(), name='room_detail'), -
Django - Trying to call a model function from list_display in modeladmin
I'm following along with Mozilla's Django tutorial, currently on this page: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Admin_site I am trying to get the ModelAdmin for the Book model to call a function of the Book model in the list_display of the ModelAdmin. This is to provide a list of genres in the list display. I have the following code in the admin.py file: class BookAdmin(admin.ModelAdmin): list_display('title', 'author', 'display_genre') And in the models.py file: class Book(models.Model): ... def display_genre(self): return ', '.join(genre.name for genre in self.genre.all()[:3]) display_genre.short_description = 'Genre' I believe this was exactly what the tutorial asked me to add to each of these files. Here's is what django tells me when I try to makemigrations: SystemCheckError: System check identified some issues: ERRORS: : (admin.E108) The value of 'list_display[2]' refers to 'display_genre', which is not a callable, an attribute of 'BookAdmin', or an attribute or method on 'catalog.Book'. I'm not sure what I've done wrong Running python 3.6.9 on Ubuntu 18.04.4 -
django | importing two models' stored data in a single html page
I have two views in my views.py as following: def table1(request): template_name = 'tables.html' queryset = one.objects.all() context = { "table1_list": queryset } return render(request, template_name, context) def table2(request): template_name = 'tables.html' queryset = two.objects.all() context = { "table2_list": queryset } return render(request, template_name, context) and the following models in models.py: class one(models.Model): title = models.CharField(max_length=100) explanation = models.CharField(max_length=1000, blank=True, null=True) class two(models.Model): title = models.CharField(max_length=100) explanation = models.CharField(max_length=1000, blank=True, null=True) In my tables.html I want to show the contents from both of these models. I have: <p>Table one content</p> <ul> {% for obj in table1_list %} {{ obj.title }}, {{ obj.explanation }} {% endfor %} </ul> <p>Table two content</p> <ul> {% for obj in table1_list %} {{ obj.title }}, {{ obj.explanation }} {% endfor %} </ul> But since I can just return one view from views.py in urls.py, I cannot return both of the tables. In urls.py I have to write either of the following: urlpatterns = [ url(r'^$', home), url(r'^tables/$', table1), ] or urlpatterns = [ url(r'^$', home), url(r'^tables/$', table2), ] I tried adding both of the tables from the query in views.py as: def table1(request): template_name = 'tables.html' queryset_one = one.objects.all() queryset_two = two.objects.all() context = { … -
How to filter the class to which the model is related in a ManyToManyField relation in Django?
I would like to filter the class Location to which the model House is related. The idea is to limit the choices of Location based on the value of the field country in the admin pannel. Is it something possible and if so, how can I do that? class House(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='country' ) city = models.ManyToManyField( Location, related_name='city' ) Basically I would like someting like that but Django throw an error saying django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. city = models.ManyToManyField( Location.objects.filter(country=country, related_name='city' ) -
JQuery Ajax call refused by Django server in google compute engine. net::ERR_CONNECTION_REFUSED
I have a Django web server with REST API. Front end Ajax is implemented with JQuery. All works in local Mac and Ubuntu. When deployed in google computer engine, web page showed up and subsequence Ajax call failed with error: net::ERR_CONNECTION_REFUSED This application does not have cross domain API calls. It's simply web page ajax call to the same web server. I have firewall rule allow TCP:8000 Ingress http-server IP ranges: 0.0.0.0/0 tcp:8000 Allow 1000 default I also confirmed that Ajax call never reached the server side. It's like refused by google compute engine. What GCP configuration is missing? -
Django : SystemCheckError: System check identified some issues
I have created Django projects before. However this time,I do django-admin startproject myproject and run server python3 manage.py runserver. First I see include() error in urls.py, I removed the include() from admin urlpattern. It then looks like : path(r'^admin/', include(admin.site.urls)). Second, I see another security check problems. Exact message is this : django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. I followed another Stack question with similar problem like me but different Django/Python versions : Django E.408, E.409 and E.410 errors on runserver From reading these, I understood the problem has risen because of incompatible versions of Django/Python. However I still have questions like : I ran the runserver on default settings (settings generated by startproject). Why Django cannot recognize it's own settings ? . In the Stack question above, I tried changing MIDDLEWARE_CLASSES to MIDDLEWARE then it solves this issue and raises another issue of django.core.exceptions.ImproperlyConfigured: WSGI application 'portfolio.wsgi.application' could not be loaded; Error importing module. I … -
Is there a way to renew an existing csrf_token in Django?
Currently I have the following registration form in my django app and I am having problems when I try to reload the registration page, that is, whenever the user types an invalid username, email or password then he/she receives a message about the error but then if he/she types a valid username, email and password, I encounter a 403 Forbidden CSRF verification failed. Request aborted. I believe this happens because a pre-session token is created when the user incorrectly types invalid registration credentials and when new credentials are typed in then there's a mismatch between the new data and what's inside of the csrf_token, so I am thinking I need to destroy the previous created csrf_token and create a new one (please, correct me if I am wrong since most of this stuff is relatively new to me). views.py from django.shortcuts import render, redirect, render_to_response from .forms import UserRegisterForm from django.contrib import messages def register(request): form = UserRegisterForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account {username} has been successfully created!') return redirect('login') else: # display the errors when trying to submit your request return render_to_response('accounts/register.html', {'form':form}) elif request.method == 'GET': form = UserRegisterForm() return … -
How to let user select currency in Django using Django-money?
I am currently working on an online store. I want a user to be able to change their currency option in the header and convert the whole site to the currency choice. I have found app called django-money, which seams to have that functionality, but I cannot find any implementation examples. I want it to work like localize work in django. Having a form that will redirect to URL and saving choice in session and in cookie. This is the example of the language selection code. /template.html <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language" onchange="this.form.submit()"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.code|upper}} </option> {% endfor %} </select> </form> And then whenever I need something to be translated I will use this inside html: {% trans "Some text to translate" %} So is there something similar for currency? What would be the action for the form? Please can somebody help if you have ready solution! I will really appreciate. -
Bootstrap-4: Grid in dropdown
I have a project with django. For the HTML I use Bootstrap 4 and I have the following code: <div class="dropdown-menu dropdown-menu-right scrollable-menu" aria-labelledby="navbarDropdown"> {% for notification in user.notification_set.all %} <a class="dropdown-item px-2" href="{{ notification.url_to_redirect }}"> <div class="row"> <div class="col m-0 p-0"><img src={% static 'open-iconic/svg/badge.svg' %} alt="thumb-up" title=Badge style="width: 16px; height: 16px;"></div> <div class="col m-0 p-0"> {{ notification.text }} {{ notification.created_at }} </div> </div> </a> {% endfor %} </div> This code give me the expected result: But sometimes the sentence of {{ notification.text }} is too long and I obtain this: I would like the following result: I tried to use float or table but I didn't get there. Someone could help me ? -
display '0' in html if QuerySet = []
I am building a view a Django to render how many rows in a field have values greater than 0. So, the view that I am making needs to count the values greater than 0. Django Query to find number of rows with a certain value greater than zero, grouped by user has been extremely helpful, however I am stuck with the result. I can't find a way to tell my view to display '0' on my html page when the querySet = [], and the count when the QuerySet has something in it. class HomeView(View): def get(self, request, *args, **kwargs): count_orders = Item.objects.filter(en_cours_de_reception__gt=0).values('en_cours_de_reception').annotate(count_orders=Count('en_cours_de_reception')) if count_orders == 0: count_orders = '0' return render(request, 'dashboard/index.html', {'count_orders' : count_orders How can I get that done in a Django view? }) -
Django Field 'id' expected but got queryset
I'm facing a problem with a django query. My models: class Mandant(models.Model): Mandant_id = models.AutoField('ID', primary_key= True) Mandant_accn= models.CharField('Kundennummer', max_length=10) Mandant_name = models.CharField('Bezeichnung', max_length=200) def __str__(self): return str(self.Mandant_id) class Meta: app_label ="meas" class Meas_User(AbstractUser): Mandant = models.ForeignKey(Mandant, on_delete=models.CASCADE, null = True) def __str__(self): return self.username I want to select the Mandant object of a specific user. I've tried this: user = Meas_User.objects.get(username=user_name) mandant = Mandant.objects.get(pk=user.Mandant) The second statement leads to this TypeError: TypeError: Field 'Mandant_id' expected a number but got <Mandant: 1>. Why do I get a queryset by using a get method? And how do I select my mandant object? -
dropdown box empty in django when trying to populate values from database
I am new to Django and I was unable to find a fix for this. I am trying to populate a dropdown box with the database values. Here are my files models.py file from django.db import models # Create your models here. class Page(models.Model): title = models.CharField(max_length=60) permalink = models.CharField(max_length=12, unique=True) update_date = models.DateTimeField('Last Updated') bodytext = models.TextField('Page Content', blank=True) def __str__(self): return self.title class Item(models.Model): itemId = models.AutoField(primary_key=True) itemName = models.CharField(max_length = 100, unique=True) itemPrice = models.IntegerField() def __str__(self): return self.itemName forms.py file from django import forms from .models import Item class OrderListForm(forms.Form): itemNames = forms.queryset = Item.objects.all().order_by('itemName') urls.py file from django.urls import path from . import views urlpatterns =[ path('',views.OrderListView.as_view(),name ='hello'), ] views.py file from django.views.generic.edit import FormView from .forms import OrderListForm # Create your views here. class OrderListView(FormView): template_name = "myapp/orderlist.html" form_class = OrderListForm context_object_name = 'itemNames' orderlist.html file <form action="" method = "post"> {% csrf_token %} <label for="Items">Choose an Item:</label> <select id = items > {% for item in itemNames %} <option value = "">{{item.itemName}}</option> {% endfor %} </form> -
Adding a user object to a manytomany field
I'm writing a simple game using Django. My Game model has a many-ti-many field players: class Game(models.Model): ... players = models.ManyToManyField(User, related_name='playing_games', blank=True, null=True, default=None) My current code to add a player to a game: def add_player(self, player) if not player in self.players.all(): self.players.add(player) causes the following ValueError: Cannot add "<User: xyz>": instance is on database "None", value is on database "default" What am I doing wrong? -
Why does objects.create() fail silently?
When I create an object via [model].objects.create() and I set one of the field variables incorrectly, the create will fail. However it even with debug=True it does not produce an exception. E.g. the following fails silently: Email(models.Model): email = models.EmailField() details = {'email': '1234'} # Fails because it is not a valid EmailField Email.objects.create(**details) Why is this, and when I have a large model with lots of fields how can I debug which field is failing? -
Django signals default data working for one child but not for many
I have a signals file that I would like to be run every time a child is created. For some reason, it has created the default information for one child but if another one is added, it does not create the default information. Does not work for other users either, it has for some reason only worked for my account. signals.py file: from django.db.models.signals import post_save from django.dispatch import receiver from children.models import Children from .models import Timeline @receiver(post_save, sender=Children) def init_new_child(instance, created, raw, **kwargs): # raw is set when model is created from loaddata. if created and not raw: Timeline.objects.create(header = "Financial Support", age = "0-4",children=instance) Timeline.objects.create(header = "Financial Support", age = "4-11",children=instance) Timeline.objects.create(header = "Financial Support", age = "11-18",children=instance) Timeline.objects.create(header = "Financial Support", age = "18-25",children=instance) Timeline.objects.create(header = "Educational Support", age = "0-4",children=instance) Timeline.objects.create(header = "Educational Support", age = "4-11",children=instance) Timeline.objects.create(header = "Educational Support", age = "11-18",children=instance) Timeline.objects.create(header = "Educational Support", age = "18-25",children=instance) Timeline.objects.create(header = "Governmental Support", age = "0-4",children=instance) Timeline.objects.create(header = "Governmental Support", age = "4-11",children=instance) Timeline.objects.create(header = "Governmental Support", age = "11-18",children=instance) Timeline.objects.create(header = "Governmental Support", age = "18-25",children=instance) Timeline.objects.create(header = "Charity Support Groups", age = "0-4",children=instance) Timeline.objects.create(header = "Charity Support Groups", age = "4-11",children=instance) … -
Should I need separate virtual environments for every separate Django project
Does every Django project needs a separate virtual environment? Can't I use one of my exciting virtual env ? If I can't, then what's the problem? -
How to store compressed complex data and be able to decompress in Django?
I need to store nested data that consists of dicts, lists and numpy arrays, but it would be really good if after the decompression I could still have the numpy arrays, as opposed to what happens when I use json as a serializer. Is that possible at all? Thanks in advance! -
Need way to know when my Django Model instances are queried
I am trying to add a Framework to my Django Models that will allow for my model instances to Expire. I will have a timed task that will walk through the expirable Models and delete the expired instances. I have different types of expirations that I want to do. The first one is a basic TimeDeltaExpiry which will expire the instances after a timedelta from the time the instance was last Saved. The expiry gets updated when the instance is saved. def save(self, *args, **kwargs): self.expiry = self.expiry.datetime + timedelta(minutes=2) super(TimeDeltaExpiry, self).save() The second one is a RefreshableTimeDeltaExpiry that should have the expiry updated every time the instance gets queried. Not sure if this is even possible, but I was looking for a method or feature that would allow me to capture when the instance is referenced. There also is the concern that when my purging task runs, that it would also be referencing the instance and update the expiry, which I of course would not want to have happen. Is there a technique that might allow me to do what I want? Here is my untested code so far class ExpiryManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( expired=ExpressionWrapper(Q(expiry__lt=Now()), output_field=BooleanField()) ) class … -
Django throws an error: class UserinLine(admin.StackedInLine) AttributeError 'User' object has no attribute 'StackedInLine when copying to production
I have it working on pyhcarm, running django 2.2.10. Once I moved it /var/www folder. And run via apache2, I am getting that error Django throws an error. Why its happening on production? Not when I run it via pycharm, did sthg happen when copying the folders? My Python version is 3.6.9 -
Accessing foreign key viewflows
im attempting to access a foreign key within flows.py but am facing an error : 'NoneType' object has no attribute 'approved' Here is the relevant parts of my code: flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess #process starts here start = flow.Start( CreateProcessView, fields=["payment_code", "bPBankAccount"], task_title="New payment voucher" ).Permission( auto_create=True ).Next(this.preparer) preparer = flow.View( PreparerSignature ).Next(this.check_preparer) check_preparer = flow.If( cond=lambda act: act.process.approved_preparer.approved ).Then(this.verifier).Else(this.end) #there is more to the code but i am leaving it out as it is not relevant models.py class PaymentVoucherProcess(Process): payment_code = models.CharField(max_length=250,default='100-200-121') bPBankAccount = models.ForeignKey('BPBankAccount', on_delete=models.CASCADE) approved_preparer = models.ForeignKey('PreparerSignatureModel' , on_delete=models.CASCADE , null=True) drop_status = models.CharField( null=True, max_length=3, default=None, choices=(('SCF', 'Successful'), ('ERR', 'Unsuccessful')) ) remarks = models.TextField(null=True) class PreparerSignatureModel(JSignatureFieldsMixin): name = models.ForeignKey(User,on_delete=models.CASCADE) approved = models.BooleanField(default=False) As seen from the error code , it seems that i am unable to access the foreignkey using : act.process.approved_preparer.approved Is there a way i can access a foreignkey within flows.py? -
Client doesn't receive data in Django Channels
I created a Django channels consumer that, once the connection is open, should establish a connection to an external service, retrieve some data from this service and send the data to my frontend. Here is what i tried: import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer, AsyncJsonWebsocketConsumer from binance.client import Client import json from binance.websockets import BinanceSocketManager import time import asyncio client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', self.process_message) bm.start() def process_message(self, message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] self.send(Rate) print(Rate) When the connection is started, the consumer starts receiving data and the print statement works, meaning that i see the data appearing on my console, but the data doesn't arrive to my frontend, which means that self.send(Rate) doesn't work. Here is the only thing that i see when i open my frontend: MessageEvent {isTrusted: true, data: ""test"", origin: "ws://127.0.0.1:8000", lastEventId: "", source: null, …} Can someone help me fix this issue? Why is the data appearing on my django command line but it doesn't arrive to the frontend? -
django doesn't display form errors in template
When I try to test my form with an field is not alpha doesn't display form errors in template. my form validation: def clean_eta(self): eta = self.cleaned_data['eta'] if not eta.isalpha(): raise forms.ValidationError( 'Questo campo può contenere solo lettere') return eta my views: def pubblica_annunci(request): if request.method == "POST": form = AnnunciForm(request.POST, request.FILES) if form.is_valid(): annunci = form.save(commit=False) annunci.eta = form.cleaned_data['eta'] print(annunci.eta) annunci.user = request.user annunci.save() messages.success(request, 'Ottimo, Abbiamo ricevuto il tuo annuncio, questo sarà esaminato dallo staff e ' 'pubblicato nel minor tempo possibile.', extra_tags='alert alert-success alert-dismissible fade show') return redirect('pubblica_annunci') else: messages.error(request, 'La preghiamo di compilare tutti i campi correttamente e riprovare.', extra_tags='alert alert-danger alert-dismissible fade show') return redirect('pubblica_annunci') else: form = AnnunciForm() context = {'form': form} return render(request, 'annunci/pubblica_annunci.html', context) template: {{ form.eta.errors }} -
Integrity error when creating a user in django
I want my admin to be able to login and create users on my Django app, but each time I try to create a user I get this error message IntegrityError at /backoffice/add-exco/ (1062, "Duplicate entry '1' for key 'user_id'") The approach I used was to extend the User model using a one-to-one link. I also saw a post on stackoverflow suggesting how to solve this by doing the following Change your OneToOneField to a ForeignKey In your form validation make sure that a record does not exist When creating the form check if an entry already exists and then allow the user to edit it. I do not know how to go abt 2, 3 is there a better approach? Below is my code on models.py class AdditionalProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) mobile1 = models.CharField(max_length=15) mobile2 = models.CharField(max_length=15, blank=True, null=True) occupation = models.CharField(max_length=5, choices=OCCUPATION_FIELD, default=CHOOSE) job_cader = models.CharField(max_length=5, choices=JOB_CADER, default=CHOOSE_JOB) profile = models.ImageField(blank=True, null=True, upload_to='backend/') def __str__(self): return self.user.username on forms.py class RegisterForm(UserCreationForm): class Meta(): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return … -
Automatically create a token for admin in Django
I am looking for a method to create, automatically, a token with rest_framework.authtoken.models.Token when admin logins into admin panel. I can set-up it manually by adding the Token, but I would prefer to have it automatically created at login and destroyed at logout. -
django rest framework token authorization
I'm doing tutorial and I have a problem with access to data with authorization token. I changed in my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), I generate users and tokens for them, if I try GET, response is {"detail":"Authentication credentials were not provided."}curl: (6) Could not resolve host: Token curl: (6) Could not resolve host: e7e9047a515b141209ace33597b53771ef8f5483' i used commad: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' from https://riptutorial.com/django-rest-framework/example/28222/using-curl of course with my token and address If I change 'rest_framework.permissions.IsAuthenticated' to 'rest_framework.permissions.AllowAny' and use curl -X GET http://127.0.0.1:8000/api/v1/friends/there are no problems, I'm getting json form database. I don't know what i'm doing wrong :(