Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filters just returns all objects
So I have model like this class Research(models.Model): CATEGORIES = (...) name = models.CharField(max_length=80) date = models.DateField() category = models.CharField(max_length=10, choices=CATEGORIES) public_use = models.CharField(max_length=17, choices=PUBLIC_USE_CHOICES) This filter: class ResarchFilter(filters.FilterSet): year = filters.DateFilter(field_name='date', lookup_expr='year') category = filters.CharFilter(field_name='category', lookup_expr='iexact') class Meta: model = Research fields = ['date', 'category'] And that view: class ResarchCategoryYear(generics.ListCreateAPIView): queryset = Research.objects.all() serializer_class = ResearchSerializer filter_backends = (filters.DjangoFilterBackend,) # filterset_fields = ['date', 'category'] filter_class = ResarchFilter So when I'm uncomment filterset_fields and comment filter_class it all works well but I can't filter by the year and not by the full date. So when I'm do it like in code above and goes to http://127.0.0.1:8000/...?year=2000 It literally do nothing, just gives me all of the Research objects. So what I'm doing wrong and how to enable this filtering? -
TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght'
from django.db import models class Coustomer (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) locality = models.CharField(max_lenght=150) zipcode= models.IntegerField() state = models.CharField(choices=STATE_CHOICES,max_lenght=100) class Product(models.Model): title = models.CharField(max_lenght=100) selling_price = models.FloatField() discount_price = models.FloatField() description = models.TextField() brand = models.CharField(max_lenght = 100) category = models.CharField(choices=CATEGORY_CHOICE, max_lenght=2) prodect_image = models.ImageField(uploded_to = 'Productimg') enter code here -
Performance: Best way to send large amounts of data
On my website, users can upload posts with or without files (images, audios, videos, etc.) to the database. I have two options now: Send a very large request containing the posts data as well as maybe multiple GB of data. Then create a post object and connect the files to it. Send one very small request with only the content of the post and creating one in the backend. Then sending back the UUID to the post. Then automatically sending a large request containing the files & the UUID to the backend and connecting post & files afterwards. The pro (at least IMO) to the second solution is that users could already see their posts while the files are still being processed by the backend celery worker. Would this be considered bad or good user experience? Not sure how well both solutions might scale in the future and if it'd be a difference in traffic load when there's two requests being sent. -
How to use JavaScript client-side encryption/decryption in django forms / crispy forms? Is there any python package available which can do this
Django Form fields needs to be encrypted at server side and needs to be decrypted in client browser while rendering and vice versa for form submission One approach is using JS cryptographic libraries or to use custom encryption code. But, Is there any python package available which implements this where we use this as django form widget along with js library at client side. An example will be a package like the django-autocomplete-light package which provides a widget for autocompletion for the particular field. How to implement this or Is there any package available which can be used. -
Django: in views how can a redirect if the paramater(linked to a url pattern) does not match a model result?
I apologize am still learning django and am just hitting my head on a wall with some of it. The current issue is that I have a view linked through a URL parameter the issue and it works for showing my model info but if you hard type the url to a different parameter it shows the page. I have tried to redirect it but that is not working I feel like it might because of how and where I return my render. Any advice on how to set up url's base off model and if that model info doesn't exist either through a 404 or redirect to a different page? View: @login_required(login_url='login_register') def project_page(request, name): project = Project.objects.all() issueticket1 = Issue.objects.filter(related_project__name__exact=name) table = IssueTable(issueticket1) project_list = {} for p in project: if p.name == name: project_list = {'id': p.project_id, 'startdate': p.start_date, 'enddate': p.end_date, 'description': p.description} return render(request, 'main_projects.html', {'name': name, 'project_list': project_list, 'project': project, 'table': table}) URL CONFIG: path('projects/<str:name>/', views.project_page, name="project_page"), -
How change filter variable in view from Django template?
I have review model that has reviews made by users. In view I do pagination for it. Then I do filter the reviews by variable type = 'art' How i can change variable filter for type = 'music' from template to display selectet reviews? How then use all() to display all of them? Do I have to make separate templates for each view variable or is simpler way? My view.py: def viewrevs(request): rev = Reviews.objects.filter(type = 'art') paginator = Paginator(rev,2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) ... My template.html {% for rev in page_obj %} {{ rev.name }} {{ rev.size }} {{ rev.data }} ... {% enfor %} -
requests are working locally but not on Heroku. Getting internal server error 500 and JSON not valid
I built a web application with django and react. It is working perfectly fine locally and the heroku deployment worked fine without issues. When I am testing the heroku app some of my requests are working fine like login/register. However the request where information is being sent back from the server to be displayed or post requests sending information are giving me the following error GET [request name] 500 (Internal Server Error) and Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Would this issue be related to my requirements.txt or Procfile? Since the issue is not happening when the project is run locally and only on heroku. Could anyone point me in the right direction? -
Django/Python Runtime Error: RecursionError at /blog/cubs/
I have created a website, and I keep getting recursion errors on my /blog/cubs page, I have 2 identical pages for Beavers and Scouts but when I view the cubs equivalent I keep getting this recursion error. Below is the tracefile: pastebin of tracefile as it's too large to post here Here is the urlpatterns variable from cubs/urls.py: urlpatterns = [ path('', PostList.as_view(), name='cubs_blog_home'), path('about/', views.AboutView.as_view(), name='cubs_blog_about'), path('search/', views.SearchView.as_view(), name='cubs_blog_search'), path('file_upload/', views.upload, name='cubs_blog_file_upload'), path('downloads/', views.DownloadView.as_view(), name='cubs_blog_downloads'), path('badge_placement', views.BadgePlacementView.as_view(), name='cubs_blog_badge_placement'), path('user/<str:username>', UserPostList.as_view(), name='cubs_blog_user_posts'), path('post/new_post/', PostCreate.as_view(), name='cubs_blog_post_create'), path('post/<slug:slug>/like/', views.PostLikeView, name='cubs_blog_post_like'), path('post/<slug:slug>/', views.PostDetail.as_view(), name='cubs_blog_post_detail'), path('post/update/<slug:slug>/', PostUpdate.as_view(), name='cubs_blog_post_update'), path('post/delete/<slug:slug>/', PostDelete.as_view(), name='cubs_blog_post_delete'), #path('posts/<int:year>/<int:month>/', main_website_views.CubsPostMonthArchiveView.as_view(month_format='%m'), name="cubs_blog_post_archive_month"), #path('post/tag/<slug:slug>/', views.tagged, name="cubs_blog_post_tags"), ] And this is my woodhall_website/urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('blog/beavers/', include('beavers.urls')), path('blog/cubs/', include('cubs.urls')), path('blog/scouts/', include('scouts.urls')), path('executive/', include('executive.urls')), path('', include('accounts.urls')), path('', include('main_website.urls')), path('summernote/', include('django_summernote.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('admin/password_reset/', auth_views.PasswordResetView.as_view(), name='admin_password_reset'), path('admin/password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'), name='password_reset_complete'), -
How to restrict a child table from referencing a parent table based on specific property in Django
Consider the following example: class Car(models.Model): def __str__(self): return self.name name = models.CharField(max_length=255) type_choices = [ ('Sedan','Sedan'), ('SUV','SUV'), ('Truck','Truck'), ] type = models.CharField('Type', max_length=255, choices=type_choices) class Sedan(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) class SUV(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) class Truck(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) How can I prevent a Sedan model record from referencing a Car model record with the type set as a Truck in the context of the admin dashboard? is there a better way to design this relationship? -
ReferenceError: file is not defined - Suitescript
I resolved some earlier issues and got the below script to validate and deploy. However it fails and in the logs I see this error: ReferenceError: file is not defined [at Object.execute (/SuiteScripts/purchasing.js:11:9)] but my file is definitely there in that location and is defined in the script. All help greatly appreciated. /** * @NApiVersion 2.1 * @NScriptType ScheduledScript */ define(['N/task'], function (task) { function execute(scriptContext){ var scriptTask = task.create({taskType: task.TaskType.CSV_IMPORT}); scriptTask.mappingId = 212; var f = file.load('SuiteScripts/purchasing2.csv'); scriptTask.importFile = f; var csvImportTaskId = scriptTask.submit(); }; return{ execute: execute }; }); -
How to aggregate annotate fields of related models in django
My problem is a little more complicated, but I'm posting the question in the simplest possible way. Annotated total_score in Photo. I would like to annotate max_total_score in Person. I wrote get_queryset of PersonManager, but the following error occurred. Is there a new way? models.py from django.db import models class PersonManager(models.Manager): def get_queryset(self): photos_prefetch = models.Prefetch( 'photos', Photo.objects.annotate(total_score=models.Sum('features__score')) ) return super().get_queryset() \ .prefetch_related(photos_prefetch) \ .annotate(max_total_score=models.Max('photos__total_score')) class Person(models.Model): objects = PersonManager() class Photo(models.Model): person = models.ForeignKey(Person, models.CASCADE, related_name='photos') class Feature(models.Model): photo = models.ForeignKey(Photo, models.CASCADE, related_name='features') name = models.CharField(max_length=100) score = models.IntegerField() shell >> Person.objects.all() # Unsupported lookup 'total_score' for BigAutoField or join on the field not permitted -
Nginx frontend not calling Nginx in backend
So I am using Django + react with nginx both on backend and frontend, containerized in docker. The following image will clarify how I want to serve the whole application: Having been googling but couldn't make sense of the solutions. Issue is that Nginx in frontend not connecting with nginx on backend on port 8082. Following are docker, nginx and docker-compose files. Nginx configurations for frontend: upstream react { server reactapp:3000; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { root /usr/share/nginx/html; } location /add-to-waiting/ { proxy_pass http://0.0.0.0:8082; } } Dockerfile for react and nginx for frontend: # build environment FROM node as build WORKDIR /app ENV PATH /app/node_modules/.bin:$PATH COPY package.json ./ COPY package-lock.json ./ RUN npm i --silent RUN npm install react-scripts@3.4.1 -g --silent COPY . ./ RUN npm run build # production environment FROM nginx:stable-alpine COPY --from=build /app/build /usr/share/nginx/html EXPOSE 80 EXPOSE 443 CMD ["nginx", "-g", "daemon off;"] docker-compose.yml for frontend: services: frontend: build: . ports: - "8090:80" container_name: irisfrontend Nginx configurations for backend upstream django { server website:8000; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { proxy_pass http://django; } location /media/ { alias /app/media/; } location /static/ { … -
How to correctly type utf-8 characters?
Azerbaijan language info = "Çox da uzaq olmayan gələcəkdə, tənha yazıçı Teodor" <p class="card-text"> {{ info|slice:"0:54" }} </p> <p class="card-text"> Çox da uzaq olmayan gələcəkdə, tənha yazı&ccedi </p> ç = &ccedi How to write utf-8 characters correctly? -
Django - How to save model objects in another model?
Let's say I have these two models (in models.py file): class FullName (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) class Address (models.Model): addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False) How can I merge these two models in a new model? So it becomes: class FullName (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) class Address (models.Model): addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False) class AllInformation (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False) (all fields should be inherited from FullName and Address models) PS: In my views.py file I called a save method like that: fullNameData = FullName(request.POST) fullNameData.save() and AddressData = Address(request.POST) AddressData.save() Thanks in advance and I really appreciate who answers that because I see that many people having the same problem. I also took a look at the OneToOneField from django docs but I understood nothing to be honest xD -
Django Forms ErrorList custom format HTML TAGS
In Django version 3.2 you can customize the error list format. https://docs.djangoproject.com/en/3.2/ref/forms/api/#customizing-the-error-list-format However in version 4.1 it has changed? https://docs.djangoproject.com/en/4.1/ref/forms/api/#customizing-the-error-list-format This section is very vague for me: forms.py from django import forms from captcha.fields import CaptchaField, CaptchaTextInput class ContactForm(forms.Form): first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "first name"}), required=True) last_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "last name"}), required=False) from_email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', "placeholder": "email"}), required=True) subject = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "subject"}), required=False) message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', "placeholder": "message"}), required=True) captcha = CaptchaField(widget=CaptchaTextInput(attrs={'class': 'form-control', "placeholder": "prove u r not a bot 😎"}), required=True) In my template, I need {{ form.captcha.errors }} to be displayed with another HTML tag and not the default <ul class="errorlist"> -
How to call a function from a button in Django admin
I have manipulated the List view in my Django Admin and set a button for each entry. Now, when I click on the button, I want a URL to be called from the server. In this URL, headers and parameters are to be transferred. One parameter is the field pn of the entry. How can I do that? So far I have only the buttons without function. def button(self, obj): return format_html("<button> Action </buttton>") -
django/react app on heroku coming up blank
I built a web application with django and react and deployed it on heroku. A few days ago it was working fine, but now it is coming up as blank. When i run heroku logs --a --tail everything seems perfectly fine. When i redeploy it on heroku deployment is working completely fine and when i run the application locally it is also working perfectly. I have no idea how to begin debugging the problem since I have not been able to identify it and the same code was deployed on heroku and running fine a few days ago. Can anyone help point me in the right direction to how to start debugging such an issue? Thanks -
How can I get the object id inside a prefetch queryset?
I have struggled to get the object id inside a Prefetch queryset. models.py class ProductBatch(models.Model): name = models.CharField(max_length=100) product = models.ForeignKey( MstProduct, on_delete=models.CASCADE, related_name="product_batch" ) tutors = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="handling_product_batches" ) class TrnEvent(models.Model): event_teacher = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, blank=False, related_name="trnevent", ) # -------> field for mapping the tutors from ProductBatch model title = models.TextField(null=True, blank=True) description = models.TextField(null=True, blank=True) start_time = models.DateTimeField() end_time = models.DateTimeField() product = models.ForeignKey( MstProduct, on_delete=models.CASCADE, related_name="product_batch" ) product_batch = models.ForeignKey( "MstProductBatch", on_delete=models.CASCADE, null=True, blank=True, related_name="product_batch_events", ) class Meta: app_label = "api" db_table = "trn_event" verbose_name = "trn_event" verbose_name_plural = "trn_events" views.py class ProductBatchesView(generics.ListCreateAPIView): def get_queryset(self): batches = ( MstProductBatch.objects.filter( product_id=self.kwargs["product_id"], ) .annotate(batch_id=F("id")) .prefetch_related( Prefetch( "tutors", MstUser.objects.filter( is_active=True, role__role_code="TCR", institute=self.request.user.institute, ).annotate( total_events_count=Count( "trnevent", filter=Q(trnevent__product_batch__id=F("batch_id")) ), ), ), ) ) return batches I wanted to annotate the total TrnEvent created for the tutors. I have tried to filter product_batch of TrnEvent model from annotate of batch_id F-Object. But, It didn't work. Unfortunately the total_events_count data includes other batch events that was mapped to the tutor. -
Django - creating a new object in the serializer but leaving some params from validated_data out
I'm using a ManyToManyField in my model: class CustomUser(AbstractUser): ... roles = models.ManyToManyField(Role, blank=True) And in the serializer I want to create a new object of the CustomUser class CustomUserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = CustomUser.objects.create_user(**validated_data) But off course Django complains about that: Direct assignment to the forward side of a many-to-many set is prohibited. Use roles.set() instead. How could I create new CustomUser object from all the params contained in validated_data, but leaving 'roles' alone? Is there an elegant way to do that? -
Getting this error when submitting a form > ValueError at /forms_testing/forms_testing/ Field 'id' expected a number but got 's'
This is new. I get this error when submitting form. I have another form with one textfield that works fine. Its this one that causes errors. What does it mean? Field 'id' expected a number but got 's'. What does "s" mean? Where is it coming from? I already tried fixing this by deleting migrations and making a new migration and tried it fresh and still not fixed. views.py def forms_testing(request): if request.method == 'POST': add_book_form = AddBookForm(request.POST) if add_book_form.is_valid(): add_book_form.save() return redirect('forms_testing:forms_testing') else: add_book_form = AddBookForm() return render(request,'forms_testing/forms_testing.html', { 'add_book_form':add_book_form }) urls.py path('book/<slug:book>/', views.book, name='book'), models.py class Book(models.Model): title = models.CharField(max_length=300,blank=True) slug = models.SlugField(max_length=300,blank=True) author = models.ManyToManyField(User, null=True,blank=True) featured_image = models.ImageField(upload_to='media/FEATURED_IMAGES/',blank=True) genre = models.ManyToManyField(Genres, null=True, blank=True) def get_absolute_url(self): return reverse('forms_testing:book', args=[self.slug]) def __str__(self): return self.title is there anything out of place? please help. -
Bootstrap template form doest not updating the form details in DJango
I am facing this issue. Form save url does'nt working. I tried but i didnot get any solution this. Django form doesn't working properly, may be form not saving or URL problem. Any senior django developer, please guide me. Thanks. Codes: enter image description here Editing ---- enter image description here Edit.html (Template) <div class="container"> <div class="row mt-5"> <div class="col-md-12"> <form action="/edit" method="post"> {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Note Title</label> <input type="text" value="{{post.notes_titles}}" name="ntitles" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Description</label> <textarea name="nt" value="{{post.notes}}" cols="20" rows="7" class="form-control"></textarea> </div> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Note Slug</label> <input type="text" name="nslug" value="{{post.notes_slug}}" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> <button type="submit" class="btn btn-primary mb-4" value="Update">Save</button> </form> </div> </div> Views.py Updated Form def editNote(request, notes_id): if request.method=='POST': ntitles = request.POST.get('notes_titles') nt = request.POST.get('notes') nslug = request.POST.get('notes_slug') post = note(notes_id=notes_id, notes_titles=ntitles, notes=nt, notes_slug=nslug) post.save() return HttpResponseRedirect('/notes') else: return render(request, 'iapp/edit.html') -
Syntax Error : Invalid Return in Suitescript [duplicate]
Trying to implement a very simple script that will automate the process of importing CSV files. When on the validation phase when trying to upload the below to Netsuite I get the error: syntax error: invalid return Any thoughts greatly appreciated. Code below I have adjusted the position of the curly braces to the below but this did not resolve the problem. Sorry if this is novice stuff. /** * @NApiVersion 2.0 * @NScriptType ScheduledScript */ require(['N/task',]) function execute(scriptContext){ var scriptTask = task.create({taskType: task.TaskType.CSV_IMPORT}); scriptTask.mappingId = 212; var f = file.load('SuiteScripts/Purchasing Update 2022.csv'); scriptTask.importFile = f; var csvImportTaskId = scriptTask.submit(); }; return{ execute:execute }; -
Django POST http://127.0.0.1:8000/create_member/ 500 (Internal Server Error)
i try to add usernames to my video chatting app and this error occured. I try to fetch create_member but this error occured. I try to solve many times but failed. Kindly Check it. Uncaught (in promise) SyntaxError: Unexpected token. This error occured in console and i can't get my video and audio tracks. Internal Server Error: /create_member/ Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: videoApp_roommember.name The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\hp\Desktop\ChattingApp\VideoChatting\videoApp\views.py", line 76, in createMember member, created = RoomMember.objects.get_or_create( File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 657, in get_or_create return self.get(**kwargs), False File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 492, in get num = len(clone) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 302, in __len__ self._fetch_all() File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1507, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 57, in __iter__ results = compiler.execute_sql( File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1361, in … -
Websocket connection fails when deploying Django Channels in render.com
I am deploying a project where I use Django Channels to connect users to a websocket. My deployment is working at the core, however, whenever I try to connect to the websocket from the deployed app, I get this traceback on my logs: Oct 11 10:02:31 AM Traceback (most recent call last): ... Oct 11 10:02:31 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/aioredis/stream.py", line 24, in open_connection Oct 11 10:02:31 AM lambda: protocol, host, port, **kwds) Oct 11 10:02:31 AM File "/usr/local/lib/python3.7/asyncio/base_events.py", line 971, in create_connection Oct 11 10:02:31 AM ', '.join(str(exc) for exc in exceptions))) Oct 11 10:02:31 AM OSError: Multiple exceptions: [Errno 111] Connect call failed ('::1', 6379, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 6379) Oct 11 10:02:32 AM 2022-10-11 15:02:32,909 ERROR Exception inside application: Multiple exceptions: [Errno 111] Connect call failed ('::1', 6379, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 6379) Oct 11 10:02:32 AM Traceback (most recent call last): Oct 11 10:02:32 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/channels/utils.py", line 51, in await_many_dispatch Oct 11 10:02:32 AM await dispatch(result) Oct 11 10:02:32 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/channels/consumer.py", line 73, in dispatch Oct 11 10:02:32 AM await handler(message) Oct 11 10:02:32 AM File "./signup/consumers.py", line 41, in websocket_connect Oct 11 10:02:32 AM self.channel_name Oct … -
Getting multiple columns from 4 different tables in Django Rest Framework
I'm really new to ORM and also new to Django. Here's my models. class User(models.Model): id = models.AutoField() email = models.EmailField() class ToDo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey("User", on_delete=models.CASCADE) title = models.TextField(max_length=50) detail = models.CharField(max_length=250) class ToDoResult(models.Model): id = models.AutoField(primary_key=True) todo = models.ForeignKey("ToDo", on_delete=models.CASCADE) is_done = models.BooleanField(default=False) class ToDoDay(models.Model): DAY_CHOICES = ( ("0", "MON"), ("1", "TUE"), ("2", "WED"), ("3", "THU"), ("4", "FRI"), ("5", "SAT"), ("6", "SUN"), ("7", "ALL") ) id = models.AutoField(primary_key=True) todo = models.ForeignKey("ToDo", on_delete=models.CASCADE) day = models.CharField(max_length=1, choices=Category.choices) And what I want to get would be the same as the result of this sql query. SELECT user.id, todo.title, result.is_done, day.day FROM USER as user LEFT JOIN TODO as todo ON user.id = todo.user_id LEFT JOIN TODORESULT as result ON todo.id = result.todo_id LEFT JOIN DAY as day ON todo.id = day.todo_id WHERE user.id = 1 AND day.day = 1; I already kinda implemented this by really naive approach but my code looks so messy. I tried to make a serializer to get all things at once but I got an error message that says like serializer isn't following DB schema kind of thing. How can I achieve it like every other django gurus do? Everyone else's codes …