Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Django JSON field with additional API information
I want to implement a custom json field that would take in the id and put it in json together with other API information. Let's say you receive an id of 2, so you want to put it together in the database like this: { "id": 2, "API": "path-to-api", "additional-info": ... } The additional info, API and other keys added to the json are known at the field declaration time, and they are always the same for the given column. I used Django's get_prep_value to change the value inserted into the DB. I am also using django rest framework ModelSerializer and generics for the views. When I create a new entry, the POST response doesn't have the correct JSON, just the id I sent it. However, if I look into the database, I can see that the value is saved in the correct way and if I list the values using the default generics ListCreateAPIView, I receive the correct JSON. So the question is: Can I do this kind of functionality somehow on the field level? -
Filter queryset based on related object's field value
I have two models: class PartUse(models.Model): ... imported = models.BooleanField() class PartReturn(models.Model): partuse = models.ForeignKey(PartUse) ... imported = models.BooleanField() class PartUseListView(ListView): model = PartUse def get_queryset(self): if self.request.GET.get('show_imported', None): qs = self.model.objects.all() else: qs = self.model.objects.filter(imported=False) // including related return qs I want to filter QuerySet for PartUse to return all PartUse instances that have imported == False for either model. What's the best way to achieve that? -
LookupError: No installed app with label '—'
I'm trying to deploy my django project by following this link however i have done everything that blog specified and im getting error in its last step. While restarting supervisorctl (venv) ubuntu@ip-:~/UNIQUETRADE$ sudo supervisorctl restart django-demo django-demo: stopped django-demo: ERROR (spawn error) While running manage.py runserver I'm not getting any error. But when running python manage.py check — deploy I'm getting below error. (venv) ubuntu@ip-:~/UNIQUETRADE$ python manage.py check — deploy Traceback (most recent call last): File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/apps/registry.py", line 158, in get_app_config return self.app_configs[app_label] KeyError: '—' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/UNIQUETRADE/manage.py", line 22, in <module> main() File "/home/ubuntu/UNIQUETRADE/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/commands/check.py", line 56, in handle app_configs = [apps.get_app_config(app_label) for app_label in app_labels] File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/commands/check.py", line 56, in <listcomp> app_configs = [apps.get_app_config(app_label) for app_label in app_labels] File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/apps/registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label '—'. Here is my error log recorded from /var/log/gunicorn_supervisor.log: [2023-03-13 17:40:58 +0000] [7464] [INFO] Starting … -
How can i deploy Django app in a local network
I have a local network with 10 computers. How can i run a django app locally, so that each of the 10 computers can access the app? -
Apache2 + Django permission
Yea i know, another same problem. But no, every solutions does end work. I take old laptop, and install on it Ubuntu Server 22.04. Next i install Apache2, run server and it works on local IP and public. I setup a DNS SSL and everything works fine. But i want something more then html. So i try to add Django to my server, and make an cool website. Again: physical laptop, no virtual machine I found tutorials on Google and start to make a Django. Everything looks cool, but at the end i every time have error to connect to website with Django. Only Django on virtual env and local net works. Ony i have problem when i 'connect' it do Apache2 Every time i have errors "The server encountered an internal error or misconfiguration and was unable to complete your request." or "You don't have permission to access this resource." On local and public IP I try to find answer to my errors, i move all project to /opt, i try to edit 000-default.conf, apache2.conf, (try to) make permission with 'chmod', 'chmod o+x', i remove and replace index.html. Nothing works. Same erros. Help me :( -
Django does not create a multi-language sitemap
According to the documentation I made a site map, the site is multilingual, but instead of a normal map it displays a list of url without spaces. And it does not create a version of the page for each language. sitemap.py from django.contrib.sitemaps import Sitemap from movies.models import Movies class DynamicViewSitemap(Sitemap): changefreq = 'weekly' i18n = True languages = ["en", "ru", "de", "es","pt", "fr"] alternates = True x_default = True def items(self): return Movies.objects.all() def location(self, item): return f'/movies/{item.slug}/' urls.py sitemaps = { 'dynamic': DynamicViewSitemap } urlpatterns = [ path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), Result: https://wherefilmed.org/sitemap.xml -
django administration : TabularInline as list
I looking for a simple way or a package for making my tabularinline works as a list with pagination, number of item per page, filter, research and multiple selection (for delete action). I have a model DiscountCode and DiscountCodeUsage and is possible that i have more than 1000 object DiscountCodeUsage for one DiscountCode and the standard tabularinline can't work for me. -
How to use URL patterns in a HTML file using Django?
I am creating a web application in Django, and I need to link to a webpage that creates a model and then redirects you back. I have already created this webpage, but I need to create a link to it. This is the URL pattern for it (yes, it is long and ugly): path('add_to_trip/<int:id>/<str:name>/<str:addr>/<str:rating>', add_to_trip, name="add_to_trip"), I am trying to use this link to redirect to it, but Django can't understand it. <a class="btn btn-primary" href="{% url 'add_to_trip/{{trip_id}}/{{place_results_name}}/{{place_results_addr}}/{{place_results_rating}}' %}" style="margin-top: 10px;">Add to trip</a> This is the error I am getting: NoReverseMatch at /plan/3/ Reverse for 'add_to_trip/{{trip_id}}/{{place_results_name}}/{{place_results_addr}}/{{place_results_rating}}' not found. 'add_to_trip/{{trip_id}}/{{place_results_name}}/{{place_results_addr}}/{{place_results_rating}}' is not a valid view function or pattern name. I don't know why Django isn't using the URl pattern I provided. -
In django, how do I pass in context to a view for a specific entry in my database?
I'm quite new to django and python so please bear with me. I'm trying to create a view inside my django project that will display one entry inside my database. I have a specific template for how I want the data in the entry to be displayed. I have an app inside my project called card_catalog. Inside this app I have a function based view. Here is the code from the views.py file. def flashcard_view(request): sentence = Flashcard.objects.values_list('sentence',flat=True) word_dict_form = Flashcard.objects.only('word_dict_form') ipa = Flashcard.objects.only('ipa') pos = Flashcard.objects.only('pos') word_trans = Flashcard.objects.only('word_trans') sent_trans = Flashcard.objects.only('sent_trans') context = { 'sentence':sentence, 'word_dict_form':word_dict_form, 'ipa':ipa, 'pos':pos, 'word_trans':word_trans, 'sent_trans':sent_trans } return render(request,'card_catalog/flashcard_view.html',context=context) Here is the code for the flashcard model in the models.py file: class Flashcard(models.Model): #Main fields sentence = models.CharField(max_length=250,null=True,blank=True) word_dict_form = models.CharField(max_length=50,null=True,blank=True) word_inflected_form = models.CharField(max_length=50,null=True,blank=True) ipa = models.CharField(max_length=50,null=True,blank=True) pos = models.CharField(max_length=50,null=True,blank=True) word_trans = models.CharField(max_length=50,null=True,blank=True) sent_trans = models.CharField(max_length=250,null=True,blank=True) # sound_word = # sound_sentence = # notes_visible # notes_not_visible # Card Activation fields activate_nw_card = models.BooleanField(default=True) activate_pic_word_card = models.BooleanField(default=True) activate_word_sent_card = models.BooleanField(default=True) activate_lr_card = models.BooleanField(default=False) activate_inflected_form_card = models.BooleanField(default=False) activate_pron_card = models.BooleanField(default=False) activate_spell_card = models.BooleanField(default=False) activate_trans_word_card = models.BooleanField(default=False) activate_sent_trans_card = models.BooleanField(default=False) # Image Links image_1_url = models.URLField(max_length=500,null=True,blank=True) image_1_overlay = models.URLField(max_length=500, null=True, blank=True) image_2_url = models.URLField(max_length=500, null=True, blank=True) image_2_overlay … -
I have Problem with GenericForeignKey in admin
I have photo model with GenericForeignKey filed for 3 other model(movie, show, episode) when i want to create a photo in admin i choose the content type but i can't use raw_id_fields on object_id class Photo(models.Model): def get_photo_filename(instance, filename): content_type_name = instance.content_type.model return f"{content_type_name.lower()}s/{instance.content_object.name}/photo/{filename}" title = models.CharField(max_length=30) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={"model__in": ('show', 'movie', 'episode')}) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to=get_photo_filename) Is there any module that fix my problem? -
How do I change a function written in for loop into a single query set?
I have some django query as bellow. There is a monthly_date column in Building model, and I have my custom function get_start_date to calculate the date from monthly_date. This code with for loop works well. target = [] for building in Building.objects.filter( contract_date=view.base_date, ): if building.payments.filter(scheduled_date__lte=get_start_date(building.monthly_date)): target.append(building) I'm trying to remove for loop to make it only one query. Building.objects.filter( contract_date=view.base_date, payments__scheduled_date__lte=get_start_date(F('monthly_date')) ) I tried with F but I got RecursionError . There is some while loop in get_start_date but it works well with for loop so I don't know why this error occur. date_map = {datetime.date(2023, 2, 19): datetime.date(2022, 11, 18)} Building.objects.filter( contract_date=view.base_date, payments__scheduled_date__lte=date_map[F('monthly_date')] ) I tried like this after calculated date_map first from monthly_date, but KeyError: F(monthly_date) occur this time. What should I do to make it one query? -
python error : from django.core.management import execute_from_command_line
This is my first question in Stack Overflow. And yes, I am quite of a beginner in coding. I have developed a web app with Django / Wagtail. I wanted to work from home and work. I bought a mac mini M2. At my other computer, everything works fine. No issues on the application running on local mode. However, when I installed my new computer with all packages, I came across the following error: Traceback (most recent call last): File "/Users/marcmini/Library/Mobile Documents/com~apple~CloudDocs/Documents/GitHub/Ellipsis-Web/manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' I have these versions: pyenv versions system 3.9.2 (set by /Users/marcmini/.pyenv/version) 3.10.10 3.11.2 And the Django version 4.1.7 ( I run inside my project PIP LIST and all packages appear - I won't list all because I suppose that's not a problem ) My files are in iCloud, so I am not sure if it is a path issue. marcmini@Mac-mini-de-Marc ellipsis-web % pip install django Requirement already satisfied: django in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (4.1.7) Requirement already satisfied: asgiref<4,>=3.5.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from django) (3.6.0) Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from django) (0.4.3) I have checked this solution but it doesn't work the one that gets 288 or … -
How to pass today date in requests params Django
I have celery function which sending every 5 mins request to api and get some json data I want to know how to pass today date in params to this request for example: Full data will be 15k lines but if i pass today date to param ill get only 1k lines tasks.py def create_presence_info(): payload = {'today_date': today} # this is an example idk what i should write there url = config('PRESENCE_INFO') response = requests.get(url, auth=UNICA_AUTH) -
sending emails from a gmail account using django
I have been trying to send an email using my Gmail account but the receiver is not getting anything, why that? views.py from django.shortcuts import render from django.core.mail import send_mail def index(request): if request.method == "POST": receiver = request.POST.get("receiver") from_email = "myemailaddress" recipient_list = [receiver] subject = "Just sending message" message = "If you are seeing this then this possibly worked" send_mail(subject, message, from_email, recipient_list, fail_silently=False) return render(request, 'index.html') settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemailaddress' EMAIL_HOST_PASSWORD = 'myemailpassword' How do i tackle this problem -
Django Admin - Show ManyToOne data on a model in admin
I have 2 models Patient and History. I would like to show all History of a Patient inside the Patient model in django admin as table. I was thinking to use ManyToOne field as one patient can have more than 1 history and 1 history is only owned by 1 patient. In the Patient model admin I would like to also be able to add a new history. I have tried to use ManyToMany field but doesn't looks like the solution. Can anyone please help me on how to solve this? Below is the code: class Patient(models.Model): name = models.CharField(max_length=100) class History(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) diagnosis = models.TextField() Thanks in advance. -
How to keep some variables of a template after post request in Django
I’ve been using Django for some time and I have a kind of question about how I code after I’ve been on forums. My heaviest page requires generating several objects that I send in the context of my view. I organized my view this way: def myFunction(request): if request.method == 'POST' and "some_Button" in request.POST : #when click on a button #update object_2 elif request.method == 'POST' and "another_Button" in request.POST : #when click on another button #update object_1 else: #part executed at first load myFunction.object_1 = #some code myFunction.object_2 = #some code myFunction.object_3 = #some code context = {'object_1' : myFunction.object_1, 'object_2' : myFunction.object_2, 'object_3' : myFunction.object_3} return render(request, 'index.html', context) I had found the practice of writing my context's variables like MyFunction.myVariable in order not to have to regenerate them all when I just want to change an object. Like here when I click on one of the buttons I don’t have to regenerate the other variables. However, I am aware that this is not a good practice and I would like to change that. Except that all the examples I find need to regenerate all the variables each time. I thought about using the cache to temporarily … -
AWS instance accessible by IP only and but not with domain name in Route53
I really don't know what I am doing wrong and I have searched for solution and all to no avail. My configurations are all okay. Scenario I have deployed my django app on EC2 ubuntu and I am able to access deployed application either http://ip-address/en/ or http://ip-address:8000/en/ but not on http://domain/en/ nor http://domain:8000/en/ I get ERR_CONNECTION_REFUSED error when I access with the domain name. In Route53, an A record exist which was set 3 days ago. When I ping the ip address it returns this PING ip-address (ip-address) 56(84) bytes of data. 64 bytes from ip-address: icmp_seq=1 ttl=63 time=0.434 ms 64 bytes from ip-address: icmp_seq=2 ttl=63 time=0.425 ms 64 bytes from ip-address: icmp_seq=3 ttl=63 time=0.357 ms 64 bytes from ip-address: icmp_seq=4 ttl=63 time=0.464 ms 64 bytes from ip-address: icmp_seq=5 ttl=63 time=0.440 ms 64 bytes from ip-address: icmp_seq=6 ttl=63 time=0.422 ms 64 bytes from ip-address: icmp_seq=7 ttl=63 time=0.420 ms 64 bytes from ip-address: icmp_seq=8 ttl=63 time=0.498 ms When I ping the domain PING domain.com (ip-address) 56(84) bytes of data. 64 bytes from ec2-ip-address.compute-1.amazonaws.com (ip-address): icmp_seq=1 ttl=63 time=4.53 ms 64 bytes from ec2-ip-address.compute-1.amazonaws.com (ip-address): icmp_seq=2 ttl=63 time=0.483 ms 64 bytes from ec2-ip-address.compute-1.amazonaws.com (ip-address): icmp_seq=3 ttl=63 time=0.385 ms 64 bytes from ec2-ip-address.compute-1.amazonaws.com (ip-address): … -
Django select2 modify standard text
I use django select2, the standard text of no results is "no results found", i want to change that. In my template i have: $('.django-select2').djangoSelect2({ language: { noResults: function() {return "Geen resultaten"; } }, }); This is working fine, however i want to do this in django directly in my form This is the important part of my form: person = forms.ModelChoiceField( queryset=User.objects.all(), required=True, widget=PersonWidget())---> this is the custom widget, see below and the custom widget: class PersonWidget(s2forms.ModelSelect2Widget): def build_attrs(self, *args, **kwargs): attrs = super().build_attrs(*args, **kwargs) attrs['data-placeholder'] = "Zoeken" attrs['data-minimum-input-length'] = 0 return attrs search_fields = [ "first_name__icontains", "last_name__icontains", "email__icontains" ] -
How to create new log file for every user by logging Django
I have logger for every user if he`s log in and log out How am i suppose to say logger create every time new file for each user with his nickname. I dont need all info about all users in one log file i want to split it by different files settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'log_in_out_format': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, }, 'handlers': { 'log_in_out_file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'loggers/log_in_out/log.log', 'formatter': 'log_in_out_format', }, }, 'loggers': { 'authentication': { 'handlers': ['log_in_out_file'], 'level': 'INFO', 'propagate': False, } }, } in views.py i have something like that: login(request, user) logger.info(f'{request.user.email} logged in ') logger.warning(f'{request.user.email} logged out') logout(request) -
Django Rest Serializer: How to get hyperlink when read, use id when create or update?
models.py class User(models.Model): name = models.CharField(max_length=300) class Booking(models.Model): time = models.DateTimeField() user_id = models.ForeignKey(User, related_name='booking', on_delete=models.CASCADE) serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = '__all__' class BookingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Booking fields = '__all__' With the above code, I would get an error user_id ":["Incorrect type. Expected URL string, received int."] during creating booking process. I believe this because HyperlinkedModelSerializer expect a URL for the foreign key field. However, passing an ID during creating or updating is way more convenient. How can I edit this so that it can use id when create or update and return hyperlink only when read? -
Nginx and guncorn active and running but the website is not loading
I am new to the nginx and gunicorn setup I am trying to setup my django project in production server with the help of nginx and gunicorn but facing some issues any kind of help will be appreciated. This is my gunicorn status sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon for EPC Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2023-03-13 18:09:20 IST; 13min ago TriggeredBy: ● gunicorn.socket Main PID: 797016 (gunicorn) Tasks: 4 (limit: 28757) Memory: 91.8M CGroup: /system.slice/gunicorn.service ├─797016 /usr/bin/python3 /home/web/.local/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8001 EPC.wsgi:application ├─797018 /usr/bin/python3 /home/web/.local/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8001 EPC.wsgi:application ├─797019 /usr/bin/python3 /home/web/.local/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8001 EPC.wsgi:application └─797020 /usr/bin/python3 /home/web/.local/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8001 EPC.wsgi:application Mar 13 18:09:20 EHTP-DB-WEB systemd[1]: Started gunicorn daemon for EPC. Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797016]: [2023-03-13 18:09:20 +0530] [797016] [INFO] Starting gunicorn 20.1.0 Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797016]: [2023-03-13 18:09:20 +0530] [797016] [INFO] Listening at: unix:/run/gunicorn.sock (797016) Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797016]: [2023-03-13 18:09:20 +0530] [797016] [INFO] Using worker: sync Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797018]: [2023-03-13 18:09:20 +0530] [797018] [INFO] Booting worker with pid: 797018 Mar 13 18:09:20 EHTP-DB-WEB gunicorn[797019]: [2023-03-13 18:09:20 +0530] [797019] … -
Getting django model entries with a more complex query (joining with no direct relationship)
I am trying to get the model entry for a certain query where I'm joining with columns that are not the ForeignKey of the table. My tables (models) look like this (simplified with necessary columns): class PE(models.Model): # table p_e p_e_id = models.AutoField(primary_key=True) p_o = models.ForeignKey('PO', models.DO_NOTHING) p_r = models.ForeignKey('PR', models.DO_NOTHING) s_o = models.ForeignKey('SO', models.DO_NOTHING) item = models.ForeignKey(Items, models.DO_NOTHING, related_name='pe_item') p_e_is_possible = models.BooleanField() class EIH(models.Model): # table e_i_h e_i_h_id = models.AutoField(primary_key=True) target_item = models.ForeignKey('Items', models.DO_NOTHING,related_name='target_item') component_item = models.ForeignKey('Items', models.DO_NOTHING,related_name='component_item') p_o = models.ForeignKey('PO', models.DO_NOTHING) p_r = models.ForeignKey('PR', models.DO_NOTHING) class Items(models.Model): item_id = models.AutoField(primary_key=True) The Query I am currently using without models looks like this: SELECT * FROM p_e INNER JOIN e_i_h ON e_i_h.target_item_id = p_e.item_id AND e_i_h.component_item_id = -1 AND (e_i_h.p_o_id = p_e.p_o_id OR (p_e.p_e_is_possible = True AND p_e.s_o_id != -1) ) Is it possible to get the same queryset result as the Query only using models? The result is one entry from the table EIH with the query. I tried to filter the EIH objects with joining over the items table: pe_queryset = PE.objects.filter(item_id=15) for pe in pe_queryset: erp = EIH.objects.get(Q(p_o_id= pe.p_o.p_o_id) | Q(pe.p_e_is_possible=True), item_id=pe.item.item_id, component_item_id=-1) I also tried lookup: erp = EIH.objects.get(Q(p_o_id= pe.p_o.p_o_id) | Q(target_item__p_e__p_e_is_possible=True), item_id=pe.item.item_id, component_item_id=-1) The problem … -
Meta.ordering is deprecated option, what is the alternativeoption
I have updated my Django project from version 2 on version 3.2, and I have found in documentation that Meta.ordering option is deprecated. Actually this is in documentation: 'Meta.ordering will be ignored in such queries staring in Django 3.2'. I would like to if there is some another attribute in Meta class or in my main class in order to have same order impact. Project is really big, so I can not use order_by() with every filter. Database is PostgreSQL. Thanks in advance... -
Django channels, UserWarning: async_to_sync was passed a non-async-marked callable
I am using Django channels for the notification system,i want to send a notification to the associated store when an order is created, i create Notification model to save all previous notifications and in my post_save order signal i create notification instance. I'm using WebsocketConsumer customer type, without any authentication 'for know'. notification_models.py from django.db import models class Notification(models.Model): user = models.ForeignKey('connect.User', on_delete=models.CASCADE) store = models.ForeignKey('stores.Store', on_delete=models.CASCADE) message = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_at'] indexes = [ models.Index(fields=['user']), models.Index(fields=['store']), ] def __str__(self): return f'{self.store.name}: {self.message}' url.py from rest_framework.urlpatterns import format_suffix_patterns from .consumers import StoreConsumer from django.urls import path websocket_urlpatterns = [ # wscat -c ws://localhost:8083/ws/store/yani/notifications path('ws/store/<store_slug>/notifications/', StoreConsumer.as_asgi()), ] consumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class StoreConsumer(WebsocketConsumer): def connect(self): self.store_slug = self.scope['url_route']['kwargs']['store_slug'] self.store_group_name = f'store_{self.store_slug}' async_to_sync(self.channel_layer.group_add)( self.store_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): pass def send_notification(self, event): message = event['message'] self.send(text_data=message) notification_signals.py from django.dispatch import receiver from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from stores.models import Notification from django.db.models.signals import post_save @receiver(post_save, sender=Notification) def send_notification(sender, instance, **kwargs): channel_layer = get_channel_layer() print('channel_layer > > ',channel_layer) async_to_sync(channel_layer.group_send)( f'store_{instance.store.id}', { 'type': 'store_notification', 'message': instance.message } ) asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import … -
Django project guidance required
This is a small project given to me. I need help. If possible, give me the code files in Django: Create a REST api to be consumed by a mobile app which tell you if a number is spam, or allow you to find a person’s name by searching for their phone number. Each registered user of the app can have zero or more personal “contacts”. The “global database” is basically the combination of all the registered users and their personal contacts (who may or may not be registered users). The UI will be built by someone else - you are simply making the REST API endpoints to be consumed by the front end. Data to be stored for each user: Name, Phone Number, Email Address. Registration and Profile: A user has to register with at least name and phone number, along with a password, before using. He can optionally add an email address. Only one user can register on the app with a particular phone number. A user needs to be logged in to do anything; there is no public access to anything. You can assume that the user’s phone contacts will be automatically imported into the app’s database …