Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connect via a secure websocket WSS from Django project to Redis/Daphne
I am trying to connect a secure websocket WSS with Redis/Daphne from my Django-Project: new WebSocket('wss://myproject.com:9002/ws/myChat/') But it is not possible to connect. In the Browser-Console I always get the following error: myCode.js:36 WebSocket connection to 'wss://myproject.com:9002/ws/myChat/' failed This is the only error I see, e.g. Nginx (sudo tail -F /var/log/nginx/error.log) shows no related error. The Daphne and Redis-Services seem to work: Redis Status: redis-server.service - Advanced key-value store Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2022-04-07 08:44:07 CEST; 55min ago Docs: http://redis.io/documentation, man:redis-server(1) Process: 281 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf (code=exited, status=0/SUCCESS) Main PID: 381 (redis-server) Tasks: 4 (limit: 60) Memory: 4.1M CGroup: /system.slice/redis-server.service └─381 /usr/bin/redis-server 127.0.0.1:6379 Daphne-Service Config: [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/django_user/appdir/myProject ExecStart=/home/django_user/appdir/env/bin/python3 /home/django_user/appdir/env/bin/daphne -e ssl:9002:privateKey=/etc/letsencrypt/live/myproject.com/privkey.pem:certKey=/etc/letsencrypt/myproject.com/fullchain.pem myproject.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target Daphne-Service Status: daphne_myproject.service - WebSocket Daphne Service Loaded: loaded (/etc/systemd/system/daphne_myproject.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2022-04-07 08:44:04 CEST; 50min ago Main PID: 277 (python3) Tasks: 1 (limit: 60) Memory: 74.8M CGroup: /system.slice/daphne_myproject.service └─277 /home/django_user/appdir/env/bin/python3 /home/django_user/appdir/env/bin/daphne -e ssl:9002:privateKey=/etc/letsencrypt/live/myproject.com/privkey.pem:certKey=/etc/letsencrypt/live/myproject.com/fullchain.pem myproject.asgi:application Nginx-Config: upstream websocket{ server 127.0.0.1:6379; } server { server_name myproject.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django_user/appdir/myProject; } location / { include … -
How I can open page when click on user name in user list and his/her name show in page
I did the list page and user information page but how I can when click on user name in list it open page has name of that user and I can add user email and phone number information and save it in db so when open it again i can see the added information in the page. -
How to show MQTT data on Django webpage?
I am relatively new to Django and I am trying to figure out how I can display some mqtt data in realtime on a django webpage as the client. I have created a python generator that sends data to self created mqtt broker and all of that seems to be working. In my django project I have the following: import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): client.subscribe("TEST/#") def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) pass client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set("broker", password="pass") client.connect("127.0.0.1", 1883, 60) Here you can see me printing the payload that comes through but I can't seem to figure out a way to get this showing on the a webpage in realtime. Any help will be appreciated. Thank you! -
Django - List Filtering using a ForeignKey within a ForeignKey
I can filter the list of Bookings from "housing" using the "Housing" ForeignKey But I need to do it based on the h_type which uses the "HousingType" ForeignKey I am not sure of the correct terminology here but I think I am trying to use a ForeignKey within a ForeignKey, not sure how to accomplish this within the view. models.py class HousingType(models.Model): name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) class Housing(models.Model): h_type = models.ForeignKey('HousingType', null=True, blank=True, on_delete=models.SET_NULL) class Booking(models.Model): housing = models.ForeignKey('Housing', null=True, blank=True, on_delete=models.SET_NULL) views.py def view_bookings(request): housing = Housing.objects.all() bookings = Booking.objects.all() if request.GET: if 'housing_type' in request.GET: h_types = request.GET['housing_type'].split(',') bookings = bookings.filter(housing_type__name__in=h_types) h_types = HousingType.objects.filter(name__in=h_types) html template <a href="{% url 'view_bookings' %}?housing_type=apartments">Apartments</a> -
Show file contents to html page in django
I am running one shell script from django views.py. below is code def result(request): if request.method=="POST": process=subprcoess.Popen(cmd, shell=True, stdout=subprcoess.PIPE, stderr=subprcoess.PIPE, universal_newlies=True) while process.poll() is None: print(process.communicate()[0]) continue return render(request, 'result.html') Now here can able to get logs on file, instead directly need to redirect to html page. Could anyone please help here? Thank You. -
Django: add only permissions of specific application
I´m using django for my backend and this backend is managing multiple applications. For example i have app_a and app_b. for app_a i created a lot of custom permissions and groups. Now i want to give another user the permission to access the admin panel, but i wan`t that he can only add permissions and groups to users that belongs to app_a. I tried to use add_group or add_permission, but this is assigned to all apps. Thank you for support! -
How to modify timestamp field format in Django Rest Framework
I have this model: class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField('User', null=True, blank=True, related_name='liked_posts') savers = models.ManyToManyField('User', null=True, blank=True, related_name='saved_posts') likes = models.IntegerField(default=0) I want to return the timestamp field in json as: timestamp.strftime('%b %d %Y, %I:%M %p') I've been suggested to write this code in the model's serializer: class PostSerializer(serializers.ModelSerializer): str_timestamp = serializers.SerializerMethodField( method_name="get_str_timestamp" ) class Meta: model = Post fields = '__all__' def get_str_timestamp(self, obj: Post): return obj.timestamp.strftime('%b %d %Y, %I:%M %p') But it doesn't work and it still has its raw format. -
Django BaseManager and DefaultManager clarification
I am using Django 3.2. I am reading a section on Custom managers, and came across this text in the documentation: By default, Django uses an instance of the Model._base_manager manager class when accessing related objects (i.e. choice.question), not the _default_manager on the related object. This is because Django needs to be able to retrieve the related object, even if it would otherwise be filtered out (and hence be inaccessible) by the default manager. If the normal base manager class (django.db.models.Manager) isn’t appropriate for your circumstances, you can tell Django which class to use by setting Meta.base_manager_name. Base managers aren’t used when querying on related models, or when accessing a one-to-many or many-to-many relationship. For example, if the Question model from the tutorial had a deleted field and a base manager that filters out instances with deleted=True, a queryset like Choice.objects.filter(question__name__startswith='What') would include choices related to deleted questions. The section text seems a bit convoluted. Is it possible to explain what is being said in the above text, by using the models below? class Foo(models.Model): name = models.CharField(max_length=64) deleted = models.Boolean(default=False) # ... class FooBar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='foos') start_date = models.DateTimeField(default=now, db_index=True) end_date = models.DatetTimeField(default=now+timeddelta(days=200), db_index=True) # ... -
How to grant access to download files from AWS S3 bucket?
I'm totally new to AWS and don't have much idea about it. When I try to download an image file from S3 it opens the file instead of downloading it. Here's my s3 bucket policy and the URL Django URL pattern: { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my_bucket_name/*" } ] } <a href="{{products.files.url}}" download="{{products.files.url}}">Download</a> -
How to gracefully handle DoesNotExist exception when admin user is not found?
I have a created_by field in my model which defaults to the admin user upon object creation. I am fetching the admin user using this piece of code, admin_user_name = settings.ADMIN_USER_NAME admin = User.objects.get(username=admin_user_name) Now if I have to handle the object.DoesNotExist exception like try: admin_user_name = settings.ADMIN_USER_NAME admin = User.objects.get(username=admin_user_name) except User.DoesNotExist: # handle the exception gracefully How do I handle the exception without throwing an error in such a case? -
fcm_django.FCMDevice.user: (fields.E301) Field defines a relation with the model 'auth.User' with CustomUser model
In this project, I've used fcm-django package for push notifications in the flutter app. And I have got the following error though I've set up appropriately. Please help me what I wrote wrong! fcm_django.FCMDevice.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. Here is my fcm-settings: # FIREBASE_APP = firebase_admin.initialize_app() FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "django_fcm", # Your firebase API KEY "FCM_SERVER_KEY": "AAAAGhkzsi8:APA91bGCGga9FZnwASRy8NtLpp7jpINJcWbUiz9EHOFIxJjla8yVlpGtdqL7QB5rII0vKKExkpUw9PuRHt6khrpgcqDxcbzQvCWzgsBmT4SRRfoCirpGFXETIdIetgxBvktKJYSdjf_O", # true if you want to have only one active device per registered user at a time # default: False "ONE_DEVICE_PER_USER": False, # devices to which notifications cannot be sent, # are deleted upon receiving error response from FCM # default: False "DELETE_INACTIVE_DEVICES": True, } DEFAULT_AUTO_FIELD = 'FcmDjangoConfig.default_auto_field' And, I also imported the following lines: from fcm_django.apps import FcmDjangoConfig firebase_admin.initialize_app() os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './push_notification/serviceAccountKey.json' -
How I validate if user belongs and if not he is not allowed in Django
I have a view that I want to pass all the requests that belongs to a hospital. And, the user which belongs to a hospital, can't see others hospital requests. How can I return a HttpResponseNotAllowed ? It is a M:1 model, Hospital has many users, and a User has only 1 hospital. The requests belongs to the hospital and the user. I have this code in my view, but it doesnt work. Only shows me the requests that belongs to the hospital. But still I can change the Url to another Hospital ID and see others. View def Get_UserRequest(request, Hospital_id): # if not request.user.is_authenticated: # return redirect('login') if request.user.is_authenticated and request.method == "GET": user_sector = int(request.user.FKLab_User.id) if user_sector != Hospital_id: HttpResponseNotAllowed() requests = RequestHepatoPredict.objects.filter(Hospital_id=Hospital_id) return render(request, 'user_profile/requests.html', {'requests': requests}) -
Django migrations: base data with tests
I am adding some base data to database with Django's database migrations. Base data consists of predefined values of types which are accessible to all users. There is also possibility to create custom types by users. Problem is that when running tests with --keepdb option, tables will be flushed and also base data will be removed. Without --keepdb option tests are considerably slower. Is there a way to create base data so that it would be available to tests with --keepdb option? Or is there a way to run tests so that base data would be accessible without doing all migrations again? Migrations I have created look like this: def set_default_values(apps, schema_editor): Type = apps.get_model('app1', 'Type') Type(name='name1', user=None).save() Type(name='name2', user=None).save() Type(name='name3', user=None).save() class Migration(migrations.Migration): # ... operations = [ migrations.RunPython(set_default_values, elidable=True) ] -
I'm having an issue displaying the card rate according to the selected card category
Please, I need help with my Django project. I'm having an issue displaying the card rate according to the selected card category. I have been having this Issue for a while now please I need help. Here is my my view: @login_required(login_url='/Authentication/login') def giftcard(request): giftcards = Giftcard.objects.filter(publish=True) context = { 'giftcards': giftcards, 'categories': categories, } return render(request, 'dashboard/giftcard.html', context) Here is my models and I link them using ForeignKey: class Giftcard(models.Model): name = models.CharField(max_length=100, unique=True) card_image = models.ImageField(upload_to='Giftcard/', blank=False) date = models.DateTimeField(auto_now_add=True) publish = models.BooleanField(default=False) class Category(models.Model): category = models.CharField(max_length=250) card = models.ForeignKey(Giftcard, on_delete=models.CASCADE) class CardRate(models.Model): rate = models.IntegerField() card_category = models.ForeignKey(Category, on_delete=models.CASCADE) Here is my template, i think am writing the wrong code here: {% for giftcard in giftcards %} <!-- Card --> <div class="container d-flex align-items-center justify-content-center"> <div class="gift__card-modal-container py-5"> <div class="card__container"> <div class="gift__card-overlay"></div> <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid gift__card-img" style="width: 40rem;" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <select id="category" class="form-select py-2" aria-label="Default select example"> {% for spec in giftcard.category_set.all %} <option value="{{ spec.category }}">{{ … -
Django Timezone Aware Input Form Setting DateTime In Wrong Timezone
I have a model called Order, which has an DateTimeField. In forms, I use a DateTimeInput widget to allow the user to select a DateTime. I also followed the Django documentation for allowing a user to select their local timezone, for the purpose of submitting DateTimes. These are stored in UTC, but rendered to the user in their local timezone. The problem is, when an order is created with a DateTime, it's interpreted as being in UTC instead of the local timezone. So for example, if the user is in the New York timezone, and creates a new Order at 12:00 AM April 6th New York time, it will actually be stored as 12:00 AM April 6th UTC. Thus, when it's rendered back to the user, the Order has a DateTime of 8:00 PM April 5th New York time. This is incorrect. I want the Order to be stored as 4:00 AM April 6th UTC, so that it's rendered back to the user as being created at 12:00 AM New York time. I've combed the web for days now, but I can't seem to find a solution for this issue. I've posted some of my code below: Order Model class … -
Couldn't setup Django
Django was working before, but when I reinstall Django, I enter py manage.py startapp myapp command, an error occurred: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I tried to find the problem, but still not fix. Python and Django keep up to date, and I really sure system variable is available(Path: C:\Users\YYJ\AppData\Local\Programs\Python\Python310\ and Scripts) -
templates inside application in django
I am working on a django project. I am getting TemplateDoesNotExist error in my browser window. I think django unable to find templates inside application in django project. I am unable to figure it out what is wrong in my code. project structure is something like that - schoolproject | |______ course | |______ fees | |______ schoolproject | |______ manage.py schoolproject/schoolproject/urls.py course application folder - course | |___ templates | | | |____ allcourse.html | | | |____ course.html | |___ admin.py | |___ apps.py | |___ models.py | |___ tests.py | |___ urls.py | |___ views.py schoolproject/course/views.py def course(request): return render(request, 'allcourse.html') def course_python(request): return render(request, 'course.html') schoolproject/course/urls.py from . import views urlpatterns = [ path('', views.course), path('course-python/', views.course_python) ] schoolproject/schoolproject/urls.py import course import fees urlpatterns = [ path('admin/', admin.site.urls), path('course/', include('course.urls')), path('fees/', include('fees.urls')), ] On hitting :- 127.0.0.1:8000/course/ And on hitting:- 127.0.0.1:8000/course/course-python/ -
Best way to implement view count logic in Django
I've been building my personal blog using Django and I must say that I'm learning a great deal. One of those things being the fact that the implementing the view count logic is not as simple as doing view_count += 1. So far, I've done some research and narrowed my options to Using Django's F-expression Using django-hitcount module Learn more about how sessions work and see if I can make it work with Django's sessions. The reason I ask this is that I want to implement a more Youtube like logic for my posts. Users must view the article for a certain length (time or word wise). What do you think is the best way to go about this? Any references to helpful articles are greatly appreciated. Thanks! -
Is request.data mutable by default in Django REST Framework 3.13.1?
I am using a DRF view function (with an @api_view(["POST"]) decorator) to use user posted data to create a new database record for a model Product. I have in my model definition Meta unique_together = ["user", "name"]. I would like to ensure that this unique together constraint is checked in a serializer validation itself, so as to avoid raising an integrity error at the time of saving. So what I used to try earlier was request.data["user"] = request.user.id, before passing request.data to the model serializer, then calling serializer.is_valid(), and finally serializer.save(). However, this used to raise some error to the effect that request.data was not modifiable when I was using some DRF 3.12.x (and Django 3.2). This was a minor inconvenience as I had to create a copy of request.data to modify the posted data. This kind of thing is described in multiple places, for e.g., here on SO and elsewhere. But I have since upgraded to DRF 3.13.1 and I noticed that now I am able to modify request.data in ways that I was not able to earlier (both, to add a new key-value pair and to edit the value for an existing key). I am testing using Postman: … -
Bootstrap Studio with Django
I recently learned Django and I wanted to make also a simple frontend. Is there a tool to convert the HTML to Django html? I tried BSS tools BSS but they seem not to work -
how do I get foreighkey of foreighkey without a loop in django?
It is a Django project, I am trying to create a wishlist (many-to-many will not help because I need DateTime of getting that wished item in the wishlist). class Client(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField() class WishItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) client = models.ForeignKey(Client, related_name="wishlist", on_delete=models.CASCADE) added_at = models.DateTimeField(auto_now_add=True) What I could do is only this: wishlist = Client.objects.wishlist.select_related('product').all() wish_products = [item.product for item in wishlist] But I need something like this, without a loop but with a single SQL query and single line wishlist = Client.objects.wishlist.product.all() When I try to run this code I get an error AttributeError: 'RelatedManager' object has no attribute 'product' -
How to replace django template variable from another file?
I have a django template as: Templates/example.html: <html> {{ variable_1 }} {{ variable_2 }} {{ variable_3 }} </html> And I want to fill these variables from another python file and then use this html file (with filled variables) somewhere. Something like: from Templates import example.html as t t.variable_1 = "abc" t.variable_2 = "xyz" t.variable_3 = "pqr" And then use t somewhere. I haven't worked with Django templates before, and therefore, has no idea how to proceed with this. It would be great if someone could help. Thanks. -
heroku logs --tail - Django application
I always take this msg ERR when I try to deploy my django app : Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail this the result of heroku logs --tail : 2022-04-07T06:27:04.000000+00:00 app[api]: Build succeeded 2022-04-07T06:28:21.017217+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=app-gvt.herokuapp.com request_id=aa717d10- c1e0-4410-91b9-46f19155ce48 fwd="105.129.236.200" dyno= connect= service= status=503 bytes= protocol=https 2022-04-07T06:28:21.636539+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=app-gvt.herokuapp.com request_i d=ec7fc31b-4163-4054-b729-4b214e46a869 fwd="105.129.236.200" dyno= connect= service= status=503 bytes= protocol=https -
Need to populate the Project manager field based on the project select on the Timelog Model using django rest framework
models.py class User(AbstractBaseUser, PermissionsMixin): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) username = models.CharField(max_length=30, unique=True,default=None) email = models.EmailField(max_length=250, unique=True) first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) dob=models.DateField(max_length=8,default=None,null=True, blank=True) pancard=models.CharField(max_length=25,default=None,null=True, blank=True) aadhar=models.CharField(max_length=20,default=None,null=True, blank=True) personal_email_id=models.EmailField(max_length=254,default=None,null=True, blank=True) phone = PhoneNumberField(default=None,null=True, blank=True) emergency_contact_no=models.IntegerField(default=None,null=True, blank=True) emergency_contact_name=models.CharField(max_length=100,null=True, blank=True) relation=models.CharField(max_length=25,default=None,null=True, blank=True) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True,blank=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designations",default=None,null=True, blank=True) billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable',null=True, blank=True) joining_date=models.DateField(max_length=15,null=True, blank=True) relieving_date=models.DateField(max_length=15,null=True, blank=True) is_manager=models.BooleanField(default=False) reporting_manager = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', ] class Project(models.Model): project_code = models.CharField(primary_key=False, max_length=10,default=None,null=True,unique=True) project_name = models.CharField(max_length=50,unique=True,default=None) client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) user=models.ManyToManyField(User,related_name='users',default=None) project_manager = models.ForeignKey(User,on_delete=models.PROTECT,related_name="project_manager",default=None,limit_choices_to = {'is_manager': True},null=True,blank=True) description=models.TextField() type=models.TextField() #dropdown start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) technical_contact_name = models.CharField(max_length=30) email=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) delivery_head_contact_name=models.CharField(max_length=30) class Meta: db_table ='Project' def __str__(self): if self.client is not None: return f'{self.client.client_code }{self.project_code}-{self.project_name}' else: return self.project_code class Timelog(models.Model): STATUS_CHOICES = [ ('created','Created'), ('submitted', 'Submitted'), ('approved', 'Approved'), ] project = models.ForeignKey(Project,on_delete=CASCADE,related_name='project2',default=None) user= models.ForeignKey(User,on_delete=CASCADE,related_name='user2',default=None,blank=True,null=True) project_manager = models.ForeignKey(Project,on_delete=CASCADE,related_name='project_manager2',default=None,blank=True,null=True) job=ChainedForeignKey(Job,chained_field="project", chained_model_field="project",show_all=False, auto_choose=True, sort=True) date= models.DateField(default = datetime.date.today) hours=models.DurationField(default=datetime.timedelta(),null=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES,null=False, default='Created') def save(self, *args, **kwargs): if not self.project_manager: self.project_manager = self.project.project_manager return super().save(*args, **kwargs) class Meta: db_table ='Timelog' def __str__(self): return '{}'.format(self.date) As per … -
Why does the script connect every other time?
Please tell me, what could be the problem of not connecting the script? the cache is disabled. ... </div> {% endblock content %} {% block scripts %} <script src="{% static 'js/sorting_columns.js' %}"></script> {% endblock scripts %} </body> </html> When the page is updated, then it is connected, then it is not connected. If you update 2-3 times to connect.