Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: can I make db queries async?
In my app I have a template that I wish to make it like a control center that would display a ton of information, so I have to make a ton of queries to grab that info. So of course, the page is slow as heck and now I'm thinking how to fix this. I thought about making indexes but I don't have the space for this. I already optimized my queries to the minimun waste possible but it still takes like 1:30 minutes to load the page. I'm looking into assynchronous support on Django, but the version of Django I'm using doesn't seem to support (2.1). Does anybody got any tip that could help me in this? I didn't showed my code because I figured it's not nescessary, for this question is more abstract. It's not about my problem especifics but more about optimization in general. -
Django: make an addition inside of a model.objects.filter.update()
I have this view that has a form and I want to update a field of a model based on the user input. I cannot find a way to do that. The pytonic way =+ does not seem to work in this situation. Here is my view: def orders_on_the_way_edit2(request, Id): OnOrder2 = get_object_or_404(table_on_order, Id=Id) if request.method == 'POST': form = OnOrderUpdateForm(request.POST, instance = OnOrder2) if form.is_valid(): form.save() quantity = form.cleaned_data.get('Quantity_received') id = form.cleaned_data.get('Id') update2 = table_on_order.objects.filter(Id = Id).update(Quantity_received =+ quantity) update = table_on_order.objects.filter(Id = Id).update(StockOnOrder = (StockOnOrder - quantity)) messages.success(request, "Changed in order status successfully recorded") return redirect('OnOrder2') else: form = OnOrderUpdateForm(initial = { 'Id' : OnOrder2.Id, 'StockOnOrder' : OnOrder2.StockOnOrder, 'Quantity_received' : OnOrder2.Quantity_received, 'OrderCompleted' : OnOrder2.OrderCompleted}, instance =OnOrder2) return render(request, 'OnOrder2edit.html', {'form' : form}) the lines: update2 = table_on_order.objects.filter(Id = Id).update(Quantity_received =+ quantity) update = table_on_order.objects.filter(Id = Id).update(StockOnOrder = (StockOnOrder - quantity)) are causing the issue, update1 replaces the existing value by quantity and update2 gives me an error. Any clue on this would be appreciated! -
Django atomic transactions not actually atomic?
I was recently in an interview for a fairly upper-level django job and they stated that atomic transactions aren't truly atomic. In all my years using django ive never heard this. can anyone explain? -
Django: Can't add field to custom user model
So, I've got a well running Django 3 app with a custom user model running on a MySQl db. I've been doing makemigrations and migrate successfully for months. Today I tried to add a field to my custom User Model called Account. The second I add a field to that model, the dev server attempts to process the change and crashes with this error: django.db.utils.OperationalError: (1054, "Unknown column 'account_account.lifetimeuser' in 'field list'") Doesn't matter the type of the field or the name. The base exception is: MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'account_account.lifetimeuser' in 'field list'") Understand that this is NOT at runtime. It's right after I change the model and stop typing. Or in this case uncomment the lifetimeuser field (BTW, this is for testing only. I know I have an is_lifetime_user. That's the real field that was added sometime ago. Also note that this is ONLY with the Account model. Every other model in the file works as expected. Add, remove, edit: no problem as long as the syntax is correct. Since the error happens immediately, I can't makemigrations or migrate. I know my DB is in sync everywhere else. Can anyone give me a hint as to what is … -
Different One-To-Many relationships with same entities in Django
How would one go about implementing two different One-To-Many Relationships between the same entities in Django? For example: Suppose we have two relationships between a physical movement and muscles involved. For each movement I want to be able to distinguish between its main acting muscles and its supporting muscles. In practice I would introduce two tables (movement2primarymuscle, movement2supportingmucsle) and create a row with foreign keys for each relationship in each table. What's the Django way of implementing this with Django models? -
How to upload file from google drive to my django website?
I want the user to first upload the file from local system to google drive. Then my django website has a button to upload file from google drive to my website. -
How to dynamically create div class="row" using Django and Booststarp
I am trying to render some cards dynamically in my webpage. I want to render four cards in the first row and wants to render four more cards in the next row. How can I render div dynamically using django? Here is the view.py def User_View_Packages(request): package = Package.objects.all() return render(request, 'user_view_packages.html',{'package':package}) And index.html <div class="row"> {% for p in package %} <div class="col-md"> <div class="card" style="width: 18rem;margin-left:5%"> <img class="card-img-top" src="dp.39069 (1).jpeg" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ p.package_name }}</h5> <p class="card-text">STARTS FROM BDT. {{ p.package_cost }} PER PERSON</p> <p class="card-text">Location: INDIA</p> <a href="#" class="btn btn-primary">View More</a> </div> </div> </div> {% endfor %} </div> -
Django - sub-select returns 5 columns - expected 1
I have a django model Post with a M2M field views. When a visitor of the website views a post, he should be added to views. Here is the view: class ViewPostView(APIView): def get(self, request, format=None, *args, **kwargs): post_id = self.kwargs['post_id'] print(post_id) #17 this_post = get_object_or_404(Post, id=post_id) print(this_post) #Post abc post_count = this_post.views.all().count() print(post_count)#0 thisvisitor = get_visitor(request) print(thisvisitor)#<QuerySet [<Visitor: 127.0.0.1>]> if thisvisitor in this_post.views.all(): post_count = post_count else: post_count = post_count + 1 this_post.views.add(thisvisitor) data = {post_count} return Response(data) Traceback (most recent call last): File "/.../site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/.../site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (sub-select returns 5 columns - expected 1) was the direct cause of the following exception: ... File "/.../views.py", line 388, in get this_post.views.add(thisvisitor) File "/.../site-packages/django/db/models/fields/related_descriptors.py", line 946, in add through_defaults=through_defaults, File "/.../site-packages/django/db/models/fields/related_descriptors.py", line 1129, in _add_items ], ignore_conflicts=True) File "/.../site-packages/django/db/models/query.py", line 493, in bulk_create objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts, File "/.../site-packages/django/db/models/query.py", line 1230, in _batched_insert self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts) File "/.../site-packages/django/db/models/query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/.../site-packages/django/db/models/sql/compiler.py", line 1392, in execute_sql cursor.execute(sql, params) File "/.../site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/.../site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) … -
(Django) Can you access model methods in Create & List View?
I have a StaffProfile Model and an Establishment Model. I'm using Class Based Views, and in each of the CRUD views for the StaffProfile Model I need to check that the User logged in is an admin at the Establishment the StaffProfile is a member of. To do this I have a get_establishment() method in the views and a UserIsAdmin mixin that checks the User is an admin of the Establishment. My question is: instead of having to copy and paste the exact same method in each view, can I put it in the model itself and then reference it? I know I can for DetailView, UpdateView, DeleteView... but for CreateView and ListView it doesn't work as there is no object to reference, so I'm wondering if there is another way to access the method? Or a different approach I should be taking? My Code (shortened & simplified): views.py # URL for view is: <slug:establishment_slug>/staff/create/ class StaffProfileCreate(LoginRequiredMixin, UserIsAdminMixin, generic.CreateView): form_class = CustomStaffProfileCreationForm template_name = 'profiles/create_staffprofile.html' login_url = "login" def get_establishment(self): establishment_slug = escape(self.kwargs.get('slug')) establishment = Establishment.objects.get(slug=establishment_slug) return establishment # URL for view is: <slug:establishment_slug>/staff/<int:staff_pk>/ class StaffProfileDetail(LoginRequiredMixin, UserIsAdminMixin, generic.DetailView): model = StaffProfile template_name="profiles/detail_staffprofile.html" login_url = "login" def get_establishment(self): establishment_slug = escape(self.kwargs.get('slug')) … -
update a model in the view of a django restframework view
I can't find examples of using patch to update a partial view in rest framework and it isn't computing for me. Here is my code: class ArworkIsSold(generics.RetrieveUpdateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = ArtworkSerializer queryset = Artwork.objects.all() def partial_update(self, request, pk=None): data = {sold:True,forSale:False} serializer = ArtworkSerializer(context={'request': request},data=data, partial=True) serializer.is_valid() serializer.save() serializer.is_valid(raise_exception=True) return Response(serializer.data) However, it doesn't update and I get this error: NameError: name 'sold' is not defined My model does have sold and I am trying to just set the data in the view instead of sending it in from the ajax request. I just want to hit a view and have it update two fields. -
Django Paginator showing as disabled
I'm implementing a paginator in a blog section of a website, so that it only displays 6 items per page. Right now I have 7 items in the database, but it isn't displaying the paginator links as enabled, as if a second page didn't exist. The view: class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 6 template_name = 'blog/list.html' The template: <ul class="pagination"> {% if page.has_previous %} <li class="waves-effect"><a href="?page={{ page.previous_page_number }}"><i class="material-icons">chevron_left</i></a></li> {% else %} <li class="disabled"><a href="#!"><i class="material-icons">chevron_left</i></a></li> {% endif %} Page {{ page.number }} of {{ page.paginator.num_pages }} {% if page.has_next %} <li class="waves-effect"><a href="?page={{ page.next_page_number }}"><i class="material-icons">chevron_right</i></a></li> {% else %} <li class="disabled"><a href="#!"><i class="material-icons">chevron_right</i></a></li> {% endif %} </ul> And this is where I inserted the paginator object in the list template: <div class="col s12 m10 offset-m1 center"> <h1>blog</h1> <div class="row masonry-grid"> {% for post in posts %} <div class="col s12 m6 l4"> <div class="card fade-in-out up-in-out" data-duration="0"> <div class="card-image"> <a href="{{ post.get_absolute_url }}"><img src="http://placehold.it/600x400"></a> <span class="card-title">{{ post.title }}</span> </div> </div> </div> {% endfor %} </div> {% include 'pagination.html' with page=page_obj %} </div> So, the first page is displaying correctly, but the paginator isn't working and the second page (which should display, as I have … -
Django calls wrong function on given url
django calls the "listing" function even though I told it to use the "watchlist" function when handling the request which arises when going to the .../watchlist url. I can't find the problem. Here is the error: File "/home/simon/Dokumente/cs50WebProgramming/commerce/auctions/views.py", line 103, in listing listing_obj = AuctionListing.objects.get(id=int(listing_id)) ValueError: invalid literal for int() with base 10: 'watchlist' urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create_listing, name="create"), path("after_create", views.after_create, name="after_create"), path("<str:listing_id>", views.listing, name="listing"), path("<str:listing_id>/bid", views.after_bid, name="after_bid"), path("watchlist", views.watchlist, name="watchlist") ] views.py def listing(request, listing_id): listing_obj = AuctionListing.objects.get(id=int(listing_id)) return render(request, "auctions/listing.html", { "listing": listing_obj }) def watchlist(request): return render(request, "auctions/watchlist.html") -
Trouble with django templating looping over a dict created from an xml response
I am trying to display data in the html page from an xml request. I have converted the xml content to a dict using xmltodict. The xml data is like this: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <countriesRS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.hotelbeds.com/schemas/messages"> <from>1</from> <to>207</to> <total>207</total> <auditData processTime="30" timestamp="2020-10-01 18:10:02.666" requestHost="10.185.89.196" serverId="ip-10-185-88-253.eu-west-1.compute.internal.node.int-hbg-aws-eu-west-1.discovery" environment="[awseuwest1, awseuwest1a, ip_10_185_88_253]" release="cbd9f69ac1e7076b6ae86a8358f1e1bf26e00f44" internal="94d38b94f628408a9a0e41d7673d93a8"/> <countries> <country code="AD" isoCode="AD"> <description>Andorra</description> <states> <state code="CA"> <name>CANILLO</name> </state> <state code="EN"> <name>ENCAMP</name> </state> <state code="ES"> <name>ESCALDES - ENGORDANY</name> </state> <state code="AN"> <name>ANDORRA</name> </state> <state code="AD"> <name>ANDORRA LA VELLA</name> </state> <state code="07"> <name>ANDORRA</name> </state> <state code="XX"> <name>NOT ASSIGNED</name> </state> <state code="OR"> <name>ORDINO</name> </state> <state code="SJ"> <name>SANT JULIA DE LORIA</name> </state> <state code="MS"> <name>LA MASSANA</name> </state> </states> </country> <country code="AE" isoCode="AE"> <description>United Arab Emirates</description> <states> <state code="DU"> <name>UNITED ARAB EMIRATES</name> </state> <state code="FU"> <name>Fujairah</name> </state> <state code="AZ"> <name>Abu Dhabi</name> </state> <state code="AJ"> <name>Ajman</name> </state> <state code="07"> <name>UNITED ARAB EMIRATES</name> </state> <state code="XX"> <name>NOT ASSIGNED</name> </state> <state code="UQ"> <name>Umm Al Quwain</name> </state> <state code="RK"> <name>Ras Al Khaimah</name> </state> <state code="SH"> <name>Sharjah</name> </state> </states> </country> however, when i use a for loop to display the countries with {% for country in response.CountriesRS.countries %}, I can only see 'country' being displayed. How can I properly loop through this dict? This is how … -
Display song with preview_url and track name and image in spotipy search method
How to display all the track with their preview_urls and image and track name matching with the search query made in spotipy in django application. I am trying to do this below : sp = client_credentials_manager=SpotifyClientCredentials() track = sp.search("My Heart Will Go On", limit=10, offset=0, type='track', market=None) Now how to retrive above mentioned information from this track variable. -
How to adjust django qs-based table
I'm trying to render my Django queryset as table and adjust column sizes but simple changing class like: class="col-sm-2" dont give any results. Im using bootstrap4 and my code looks like so: <main role="main" class="container"> <table class="table"> <thead> <tr> <th class="col-sm-2">Name</th> <th class="col-md-1">Price</th> <th class="col-md-1">Weight</th> </tr> </thead> <tbody> {% for x in queryset %} <tr> <td>{{x.NAME}}</td> <td>{{x.WEIGHT}}</td> <td>{{x.PRICE}}</td> </tr> {% endfor %} </tbody> </table> </main> How to adjust these column sizes using bootstrap? And how to implement this together with following css: table { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } Because currently it only spans my rows all over the screen to avoid wrapping. Thanks. -
Why sometimes my python path from venv doesn't work?
When I try to run sudo python setup.py install having my venv activated, I get some Django and python version mismatch error, but when I use python path which is there in venv by copying its actual path and running the same command above just by replacing python path, it do works, so I am unable to understand which it worked when I kept actual path int it? Thanks in advance -
django.db.utils.OperationalError: duplicate column name: Email
I want to create a Django app that supports two different kinds of users. For that I have first extended my User by inheriting AbstractUser. Some fields are common to both the types of Users that I want my Django app to support and hence I add those fields in the extended User model. My User model is as follows. class User(AbstractUser): is_a = models.BooleanField(default=False) # a boolean flag to determine if this user is of type a is_b = models.BooleanField(default=False) # a boolean flag to determine if this user is of type b Name = models.CharField(max_length=128) Email = models.EmailField() MobileNumber = PhoneNumberField(null=False, blank=False, unique=True) Age = models.PositiveIntegerField() Gender = models.CharField(max_length=1, choices=GenderChoices) Organisation = models.CharField(max_length=128) Designation = models.CharField(max_length=128) def __str__(self): return self.Name I then make migrations. This is my first ever migration in this project. My migrations file is as follows: # 0001_initial.py # Generated by Django 2.0.1 on 2020-10-01 17:30 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), … -
Duplicating and then extending Django admin template
I want to copy and extend the admin's change_list.html for my app's model. I override the Django admin index.html to provide a link to a template, link works fine, sends to admin/links which has the following: VIEW def links(request): context = dict( #common variables for rendering the admin template admin.site.each_context(request), ) return render(request, 'links.html', context) I then copied the change_list.html template verbatim because I want to work off this as a starting point because I would like it to look and function similar, with a few modifications. This is where I run into errors: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/links/ Django Version: 3.0.8 Python Version: 3.7.7 Installed Applications: ['grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'useraudit', 'encrypted_fields', 'easyaudit', 'multiselectfield', 'algorx'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'sesame.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'useraudit.middleware.RequestToThreadLocalMiddleware', 'easyaudit.middleware.easyaudit.EasyAuditMiddleware'] Template error: In template C:\Bitnami\djangostack-3.0.8-0\python\lib\site-packages\grappelli\templates\admin\base.html, error at line 118 Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|useraudit|easyaudit|algorx)/$'] 108 : <!-- Switch --> 109 : {% switch_user_dropdown %} 110 : </ul> 111 : </li> 112 : <!-- Site URL --> 113 : {% if site_url %} 114 : <li><a href="{{ site_url }}">{% trans 'View site' %}</a></li> 115 : {% endif %} 116 … -
How can i get radio button values from html to django view.py?
This is my html code : <input type="radio" name="male" value="0"> <input type="radio" name="female" value="1"> and I am getting error for this line in views.py in django: male= request.POST['male'] -
django onetoonefield errors foreing key
i'm making a django project. I have 2 models AccountUser and Club, where club have a onetoone relationship with AccountUser. The problem is: while im logged in with the AccountUser "club1" and try to create a club record in the table Club(so a club record with the user field set to club1), django put admin in the field user and I don't know why models file class AccountUser(AbstractUser): # email = models.EmailField(_('email address'), unique=True) AbstractUser._meta.get_field('email')._unique = True first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50) terms_of_service_acceptance = models.BooleanField(default=False) terms_of_service_acceptance_datetime = models.DateTimeField(auto_now_add=True) is_club = models.BooleanField(default=False) REQUIRED_FIELDS = ['email'] USERNAME_FIELD = 'username' class Meta: verbose_name = _('Account') verbose_name_plural = _('Accounts') @property def has_profile(self): try: assert self.profile return True except ObjectDoesNotExist: return False def clean(self): if not self.terms_of_service_acceptance: raise ValidationError(_("You must accept the terms of service")) class Club(models.Model): club_name = models.CharField(max_length=50, unique=True) street = models.CharField(max_length=150) civic_number = models.CharField(max_length=5, null=False, blank=False) city = models.CharField(max_length=50) zip_code = models.CharField(max_length=5) user = models.OneToOneField( AccountUser, on_delete=models.CASCADE, related_name='club', primary_key=True ) class Meta: verbose_name_plural = 'Clubs' ordering = ['-club_name', 'city'] unique_together = ('street', 'civic_number', 'city') def clean(self): if len(self.zip_code) != 5 or not self.zip_code.isdigit(): raise ValidationError(_("Il CAP inserito non è valido")) if not self.civic_number.isdigit(): raise ValidationError(_("Numero civico … -
Invalid CSRF Verification with Django
I have a HTMl form i created and i am trying to get Django to process. Here is my main.html (shortened): <form action="/polls/thanks/" method="post" name = 'tag_name'> {% csrf_token %} <div class="w-3/4 py-10 px-8"> <table class="table-auto"> <thead> <tr> <th class="py-10 h-4"> <div class="mr-64"> <input type="checkbox" class="form-checkbox h-8 w-8"> <label class="ml-4">test</label> </div> </th> </tr> and here is the views.py: from django.http import HttpResponseRedirect from django.shortcuts import render def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = request.POST.get('tag_name') print(form) if form.is_valid(): return HttpResponseRedirect('/polls/thanks/') return render(request, 'main.html', {'form': 'mainform'}) def thanks(request): form = request.POST.get('tag_name') print(form) if form.is_valid(): print(form.cleaned_data) return render(request, 'thanks.html') yet it still returns a Invalid CSRF Verification if I try and submit the form Does anyone know how to fix this? Thanks -
How to display value from the database in input tag in django?
I am having an HTML template for displaying my form data to allow users to view as well as edit their data:- <div id="div_id_first_name" class="form-group"> <label for="id_first_name" class="requiredField"> First name<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="first_name" value="{{p_form.first_name}}" maxlength="20" class="textinput textInput form-control" required id="id_first_name" /> </div> </div> <div id="div_id_last_name" class="form-group"> <label for="id_last_name" class="requiredField"> Last name<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="last_name" value="{{p_form.last_name}}" maxlength="20" class="textinput textInput form-control" required id="id_last_name" /></div> </div> <div id="div_id_id_no" class="form-group"> <label for="id_id_no" class="requiredField"> ID No.<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="id_no" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_id_no" /></div> </div> <div id="div_id_phone_no" class="form-group"> <label for="id_phone_no" class="requiredField"> Phone No.<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="phone_no" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_phone_no" /></div> </div> <div id="div_id_cgpa" class="form-group"> <label for="id_cgpa" class="requiredField"> CGPA<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="cgpa" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_cgpa" /></div> </div> <div id="div_id_degree" class="form-group"> <label for="id_degree" class="requiredField"> Degree<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="degree" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_degree" /></div> </div> <div id="div_id_stream" class="form-group"> <label for="id_stream" class="requiredField"> Stream<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="stream" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_stream" /></div> </div> I am rendering this page with the view funstion:- def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, … -
How to properly configure route while using sockets?
I am learning django channels as well as djangochannelsrestframework and I am very new to it. I am following the tutorial. routing.py from django.conf.urls import url from channels.routing import ProtocolTypeRouter,URLRouter from channels.auth import AuthMiddlewareStack from djangochannelsrestframework.consumers import view_as_consumer from api.consumers import LiveContentListView, LiveContentDetailView application = ProtocolTypeRouter({ "websocket" : AuthMiddlewareStack( URLRouter([ url(r'api-live/',view_as_consumer(LiveContentListView)), url(r'api-live/(?P<pk>\w+)/$',view_as_consumer(LiveContentDetailView)), ]) ) }) The server is running fine and channels are also running fine. But when I browse localhost:8000/api-live/, it only searches for urls.py path. Please help me to properly configure the route here -
in python venv vscode: ModuleNotFoundError: No module named 'tastypie'
I have already tried searching your questions. This site won't allow me to paste in the command prompt message. -
Join 2 class in one query with common Foreign key
My model: class Doc(models.Model): numdoc = models.CharField(max_length=14) class DocQT(models.Model): doc = models.ForeignKey(Doc, models.DO_NOTHING, related_name='doc_qt') quantity = models.DecimalField(max_length=14) class DocDate(models.Model): doc = models.ForeignKey(Doc, models.DO_NOTHING, related_name='doc_date') date_cons = models.DateTimeField(defalt=date.today()) Now, i need to order by date_cons and get quantity using che common foreign key to join the classes. Something like: myquery= [...] for member in myquery: i need to render: member.quantity and member.date_cons