Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models - how to map specific subgroup clusters to their exclusive mother groups
I have got 2 database tables I would like to model in Django The first table is named Groups and is limited to 7 specific choices, A B C D E F G. I've done that. The second table is named Subgroup and is limited to 39 specific choices, numbered 1 to 39, in clusters of different sizes. Each cluster should map to only one specific group. I can't move here. How do I set up the second model to reflect the relationship so that whenever a user chooses, say subgroup option 8, the correct foreign key used refers to B in the example, or whenever choosing subgroup option 29 the foreign key used refers to F? It should be impossible to map subgroup 15 to group G, for example. Assume the mapping should be: A: 1- 5, B: 6-13, C: 14-16, D: 17-20 E: 21-26, F: 27-30, G: 31-35 and H: 36-39 -
Unable to install mysqlclient on Django
Im trying to use mysql in Django but Im unable to install it. On going '''pip install mysqlclient''' I am getting the error: error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe' failed with exit status 2 ---------------------------------------- ERROR: Command errored out with exit status 1: 'g:\python\django\venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Admi n\AppData\Local\Temp\pip-install-6_5ziqpx\mysql-python\setup.py'"'"'; file='"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-6_5ziqpx\mysql-python \setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'ex ec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-7y6967p6\install-record.txt' --single-version-externally-managed --compile --install-header s 'g:\python\django\venv\include\site\python3.8\mysql-python' Check the logs for full command output. -
Django tabular input form (user can key in data into table)
I attempt to create a tabular input form. User can key in data into the table cells. The table should have 100 rows. The following is an illustration of the end goal. However, if such table is not possible, a suggestion to create the following table is very welcomed! This is what I have tried: forms.py class SampleInputForm(forms.Form): x = forms.FloatField() y = forms.FloatField() views.py class ToolView(View): def get(self, request): table_rows = 10 sample_form_set_factory = formset_factory(SampleInputForm, extra = table_rows) sample_form_set = sample_form_set_factory() context = { 'sample_form' : sample_form_set, } return render(request, 'tools/tools.html', context) html file {% csrf_token %} <form method="post"> <table> <tr> <th>Input</th> <th>Output</th> </tr> {{sample_form}} </table> </form> However, this attempt does not form a table. The Y input field is displayed below the X, hence not forming a table. -
Exception Value: (1054, "Unknown column 'social_auth_usersocialauth.created' in 'field list'")
When trying to implement Django Social, I think i missed a migration somewhere and now when I get a twitter redirect to the site I get the following error. Exception Value: (1054, "Unknown column 'social_auth_usersocialauth.created' in 'field list'") I can see the table has been created, and two values aren't there in the database table: mysql> describe social_auth_usersocialauth; +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | provider | varchar(32) | NO | MUL | NULL | | | uid | varchar(255) | NO | | NULL | | | extra_data | longtext | NO | | NULL | | | user_id | int | NO | MUL | NULL | | +------------+--------------+------+-----+---------+----------------+ 5 rows in set (0.17 sec) I want to run a custom migration to add the two fields that are missing from an update to the social auth migration, class Migration(migrations.Migration): dependencies = [ ('dbdisplay', '0001_initial'), ('social_django', '0008_partial_timestamp'), ] operations = [ migrations.AddField( model_name='usersocialauth', name='created', field=models.DateTimeField(auto_now_add=True, default=mytz.now), preserve_default=False, ), migrations.AddField( model_name='usersocialauth', name='modified', field=models.DateTimeField(auto_now=True), ), ] But migrations don't understand the model I am referring to, because there … -
When I click on a user in the custom user model in admin, an error occurs (django)
my custom user model is this from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): # website = models.CharField(unique=True, max_length=255) email = models.EmailField(unique=False) and When I click on a user in the custom user model in admin, an error occurs (django) error message: File "C:\Users\hyunsepk\AppData\Local\conda\conda\envs\askcompany\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: accounts_user_groups [02/Aug/2020 15:41:10] "GET /admin/accounts/user/2/change/ HTTP/1.1" 500 217698 how to fix it? thanks for let me know -
How to pass range values in jquery slider to django modelform to filter price?
I have a Jquery slider which shows a price range. I want to filter price betweeen two bounds (min, max). I want to know how to pass the two values in the jquery slider to Django ModelForm to filter items based on price. <script> $(document).ready(function() { $( "#slider-range" ).slider({ range: true, min: 1000, max: 30000, step: 500, values: [ 1000, 30000 ], slide: function( event, ui ) { $( "#amount" ).val( "Birr " + ui.values[ 0 ] + " - Birr " + ui.values[ 1 ] ); } }); $( "#amount" ).val( "Birr " + $( "#slider-range" ).slider( "values", 0 ) + " - Birr " + $( "#slider-range" ).slider( "values", 1 ) ); } ).each(function(){ // Add labels to slider whose values // are specified by min, max // Get the options for this slider (specified above) var opt = $(this).data().uiSlider.options; // Get the number of possible values var vals = opt.max - opt.min; // Position the labels for (var i = 0; i <= vals; i++) { // Create a new element and position it with percentages var el = $('<label>'+(i+opt.min)+'</label>').css('left',(i/vals*100)+'%'); } // Add the element inside #slider $("#slider-range").append(el); }); </script> -
Django template search bar
I am trying to connect a search bar with a view.py. I already built the search urls.py, and I can enter the page by giving the path, the code is like: path('.../search/<str:query>', ...), So I can manually enter the page like ".../search/abc" if I am searching "abc" But the model I built cannot use the Q function in Django Inside the view.py, I create the following code, and passes the query to the path def ....(request, query): The problem is I don't know how to build a search bar in template. The code I tried is: <form action=".../search/" method="get"> <label for="search">Information</label> <input type = "search" method = "get" name = "get" placeholder="Search required"> <button type = "submit">Search</button> But after this, I got a link as ".../search/?get=" with the "query" at last. How can I get the path as "search/query"? And the text I searched automatically changed the " " into "+", but it is "%20" if I type " " in url bar -
IntegrityError IntegrityError at /api/movies/2/rate_movie
when ever i send the data from postman api it says IntegrityError at /api/movies/2/rate_movie/ UNIQUE constraint failed: api_rating.user_id, api_rating.movie_id here is my views.py from django.shortcuts import render from rest_framework import viewsets, status from rest_framework.response import Response from .models import Movie, Rating from .serializers import MovieSerializer, RatingSerializer from rest_framework.decorators import action from django.contrib.auth.models import User # Create your views here. class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer @action(detail=True, methods=['POST']) def rate_movie(self, request, pk=None): if 'stars' in request.data: movie = Movie.objects.get(id=pk) stars = request.data['stars'] #user = request.user user = User.objects.get(id=1) print('user',user) print('movie title', movie.title) try: rating = Rating.object.get(user=user.id, movie=movie.id) rating.stars = stars rating.save() except: Rating.objects.update_or_create(user=user, movie=movie, stars=stars) response = {'message':'its working'} return Response(response, status=status.HTTP_200_OK) else: response = {'message':'you need to provide stars'} return Response(response, status=status.HTTP_400_BAD_REQUEST) class RatingViewSet(viewsets.ModelViewSet): queryset = Rating.objects.all() serializer_class = RatingSerializer -
Getting Application labels aren't unique, error while creating a Django new app
I have create an app called Auth. This is my app URL method from django.urls import path, include from rest_framework.urlpatterns import format_suffix_patterns from auth import views urlpatterns = [ path('/demo', views.snippet_list) ] urlpatterns = format_suffix_patterns(urlpatterns) In my apps.py I have `class AuthConfig(AppConfig): name = 'auth' verbose_name = 'authentication_application'` And in my init.py I have default_app_config = 'auth.apps.AuthConfig' In my main application I have INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'auth' ] When I am trying to run migrations. I am getting django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth -
Django TextChoices Behavior
class MyTypes(TextChoices): MINE_AAA = '1', 'a', MINE_BBB = '2', 'b', MINE_CCC = '3', 'c', MINE_DDD = '4', 'd', MINE_EEE = '5', 'e' my_type = models.CharField(max_length=1, choices=MyTypes.choices) I have been struggling a lot with being able to use Choices in my models. With the above example, if I create an instance "my_obj" and set "my_obj.my_type" to "MyTypes.MINE_BBB", the if I look at the "my_obj", its type is MyTypes. However, if I later query "my_obj" and look at "my_obj.my_type", its type is now a string. So, when I create the object initially and serialize it, the serializer needs to handle MyTypes, but if I serialize the value after a query, the serializer needs to handle a string. What I was really expecting when using a TextChoices field was that the value stored in the Database would be the single character, but when I reference it in code, I would see my MyTypes. Are we not supposed to get the TextChoices instance back when we reference the model? If not, what is the simplest way to get it? It seem that if I after iterate through the MyTypes.choices to get it, that it really doesn't provide much value. -
How to solve error static file not found django
I'm working on a project in which I used frontend template from online website . but I think i have put every file in correct places but instead I'm getting static file not found error. below are important file : setting.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'lj6ra=$c5t!2kkin(qvuk3o(wui!m(%%wktf%my!c_gbl6(7ap' DEBUG = True ALLOWED_HOSTS = ['*'] STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'Gym/static/'), ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Gym', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Gym.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Gym.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' urls.py: from django.contrib import admin from django.urls import path,include from . import views from django.conf.urls.static … -
No response for the first click - JavaScript & Django
I am new to Django and working on a eCommerce website and trying to improve cart functions. I follow the course to use JavaScript to update the items in the cart like below code. If I clicked the "add" or "remove" button on other page(like product list), it works fine. However, when I tried to lick "remove" button on the cart page (where I can see all the products in the cart), it worked fine as the very first time, the item removed from the cart. Afterward, I clicked the button, the page just refreshed. Then I clicked another time, it worked again. So it's like after the first item removed, I have to click two times to remove the item I want. Below are my JavaScript Code, views.py, and my cart_home.html. Hope anyone could help get through this, I've been stuck for a week.... JavaScript <script type="text/javascript"> $(document).ready(function(){ var productForm = $(".form-product-ajax") // id:#form-product-ajax productForm.submit(function(event){ event.preventDefault(); console.log("Form is not sending"); var thisForm =$(this); var actionEndpoint = thisForm.attr('data-endpoint'); var httpMethod = thisForm.attr('method'); var formData = thisForm.serialize(); $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function (data) { console.log("success"); console.log(data); console.log("Added:",data.productAdded); console.log("Removed:",data.productRemoved); var submitSpan = thisForm.find(".submit-span") if (data.productAdded) { submitSpan.html('<button class="btn … -
Python get data in this format
I have a small unit of code which is given below : round = 4 chars = 68 for k in range(round): if (k % 2) == 0: Title = 'Start '+chr(chars) else: Title = 'Reached ' + chr(chars) chars = chars - 1 print(Title) Using this i am getting output like : Start D Reached C Start B Reached A What i actually want is i want result like : Start C Reached B Start B Reached A how can i get the title in this way please help me in related to this -
'str' object is not callable while accessing 'api/users/'
I am using python 3.8 along with rest framework and please find the below details The following is my serializer for users from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user The following the view for the user using the UserSerializer from django.shortcuts import render from django.contrib.auth.models import User from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated, AllowAny from .serializers import MovieSerializer, RatingSerializer, UserSerializer from .models import Movie, Rating # Create your views here. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer urls.py(api component) router = routers.DefaultRouter() router.register("movies", MovieViewSet) router.register("ratings", RatingViewSet) router.register("users", UserViewSet) urlpatterns = [ path("", include(router.urls)) ] urls.py(main project) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include("api.urls")), path('auth/', obtain_auth_token), ] Environment: Request Method: GET Request URL: http://localhost:8000/api/users/ Django Version: 3.0.8 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'api', 'corsheaders'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\study\fullstack\Movieraterapi\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in … -
How to search by POST method in Django
I am trying to display a search result page. If the query is found, it will be redirected to the entry page. Else if a substring of the query is found, a search result page will be displayed with the entry shown as a link and if click that link, the entry page will display. Here is my code as below, please help: urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entry, name="entry"), path("search", views.search, name="search"), path("edit", views.edit, name="edit") ] views.py: from . import util import markdown2 import random from django.shortcuts import HttpResponse from django.http import HttpResponseRedirect from django.urls import reverse from django import forms def index(request): entries = util.list_entries() rand = random.choice(entries) return render(request, "encyclopedia/index.html", { "random": rand, "entries": entries }) def entry(request, title): entries = util.list_entries() rand = random.choice(entries) try: mark_content = util.get_entry(title) output = markdown2.markdown(mark_content) return render(request, "encyclopedia/title.html", { "content": output, "random": rand, "title": title }) except TypeError: return render(request, "encyclopedia/error.html", { "random": rand }) def search(request): # get search input from user search_entry = request.POST['q'] # results = list() # get entries list entries = util.list_entries() # search list results = [] # try to search if there … -
I am trying to change to a custom user model, but an error occurs
I'm trying to change the Django user model to a custom user model, but an error occurs How do I resolve the error? step1 settings.py AUTH_USER_MODEL = 'accounts.User' step2 accounts/models.py from django.contrib.auth.models import AbstractBaseUser from django.db import models # Create your models here. class User(AbstractBaseUser): email = models.EmailField(blank=True) website_url = models.URLField(blank=True) When migrating, an error occurs as follows (askcompany) C:\my_django\askcompany>python manage.py makemigrations error message: File "C:\Users\hyunsepk\AppData\Local\conda\conda\envs\askcompany\lib\site-packages\django\contrib\auth\checks.py", line 39, in check_user_model if cls.USERNAME_FIELD in cls.REQUIRED_FIELDS: AttributeError: type object 'User' has no attribute 'USERNAME_FIELD' -
Displaying sum of time by project by user using Django
I am a student new to programming. I am working on a project to create a timekeeping function. I want to be able to display the total time a user worked on a project. I have been able to display the total time for a user, and the total time for a project. class User(models.Model): class Project(models.Model): title = models.CharField(max_length=255) start_date = models.DateField() end_date = models.DateField() done = models.BooleanField(default=False) created_by = models.ForeignKey(User, related_name ='made_by', on_delete=models.CASCADE) projects_working_on = models.ManyToManyField(User, related_name = "projects_assigned_to") class Timekeeper(models.Model): clock_in = models.DateTimeField(null=True) clock_out = models.DateTimeField(null=True) total_time = models.DurationField(null=True, blank=True) entire_time = models.FloatField(null=True) is_working = models.BooleanField(default=False) users_time = models.ForeignKey(User, related_name="time_of_user", on_delete=models.CASCADE) proj_time = models.ForeignKey(Project, related_name = 'time_of_project', on_delete=models.CASCADE) Here is is clockout function: def clockout(request, proj_id): user = User.objects.get(id=request.session['userid']) now = datetime.now(timezone.utc) this_proj = Project.objects.get(id = proj_id) this_time = user.time_of_user.last() time = this_time.users_time this_time.clock_out = now this_time.is_working = False newtime = user.time_of_user.filter(proj_time=proj_id).aggregate(Sum('total_time')) # this_time.total_time_two = newtime this_time.save() Timekeeper.objects.update(total_time=F('clock_out') - F('clock_in')) Timekeeper.objects.update(entire_time=F('total_time')) Timekeeper.objects.update(total_time_two=newtime) # Timekeeper.objects.update(entire_time=user.time_of_user.filter(proj_time=proj_id).aggregate(Sum"(F('total_time')") return redirect('/dashboard/view/'+str(proj_id)) The entire_time field exists solely for another function to iterate through and find the time of all of the fields for a particular user, or project. I can't seem to get a sum of the total_times (or entire_times) of 1 user … -
return two lists into html table using tabulate in python
I am new with html and I'm trying to display two lists into a table on the html page. I can display the lists but can't get them to display as a nice table. My code is: from tabulate import tabulate def some_function(a, b, c) cols = ['Col 1', 'Col 2', 'Col3'] vals = [a, b, c] table = [cols, vals] table = tabulate(table, tablefmt='html') return table some_function(1.01, 1.03, 1.05) This returns the following html code: <table> <tbody> <tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr> <tr><td>1.01 </td><td>1.03 </td><td>1.05 </td></tr> </tbody> </table> I am using Django so I can successfully return the html script to the website with my View but it doesn't read it as code, it appears as a string: View: def post(self, request): form_c = CalculatorForm(request.POST, prefix='form_c') try: if form_c.is_valid(): post = form_c.cleaned_data numbers = some_function(1.01, 1.03, 1.05) except: pass args = { 'form_c': form_c, 'form_cols': numbers, } return render(request, self.template, args) my html: <div class="container"> {{ form_cols }} # <-- where I want my table </div> -
How to send a user to a particular URL using a form in Django
I'd like users to be able to select from a form a user and then be directed to individual/user_slug. Currently, I am redirecting to individual?slug=user_slug. I cant figure out if I need to change something with the HTML form, url mapping, or the view itself. Any help or guidance would be appreciated! HTML form <form action="individual" method="get"> <label for="slug">Choose a person:</label> <select id="slug" name="slug"> <option value="person_a_slug">Person A</option> <option value="person_b_slug">Person B</option> <option value="person_c_slug">Person C</option> </select> <input type="submit"> </form> urls.py urlpatterns = [ path('individual/<slug:slug>', IndividualView.as_view(), name = 'individual'), path('', HomePageView.as_view(), name='home'), ] views.py class HomePageView(ListView): model = Person template_name = 'home.html' class IndividualView(DetailView): model = Person template_name = 'individual.html' models.py class Person(models.Model): name = models.CharField(max_length=200) description = models.TextField() slug = models.SlugField(null=True, unique=True) photo = models.URLField(null=True) def get_absolute_url(self): return reverse('individual', kwargs={'slug': self.slug}) -
Python Desktop app - monitoring remotely / via Django please?
I wrote a Python 3 desktop app (pyqt5 UI) that performs calculations for my business - works well (Python is a great language, i've had a great time with it). This app is 'mission critical' and I'd like to monitor it remotely (thinking i can write a web app using Vue or react as the face). Like, intraday, check if the app is running, pull data from it while I'm on the road. Having full control over my desktop app i can write API between the two and such. Is this possible through Django / where i create a web service that talks to my running desk top app / interfaces with it / collects data for viewing in the browser? Does anyone know a good tutorial that would have a working example to get me started? Thank you in advance for your help... -
How do you list in one page all accounts a user is following with their respective items beneath them?
all - I need a list view page that shows all the Seller Accounts a User is following, and under each of those Seller names, their list of Product titles, i.e.: User = user1 Following: Seller 1 Items: Item1, Item2, Item3 Seller 2 Items: Item4, Item5, Item6 I am able to pull the products for any one particular seller if they are alone in the page (like a Detail View/ Vendor List) but I can't figure out the logic for displaying all users at once and connecting the products beneath them. REALLY appreciate the help here! User model: class CustomUser(AbstractUser): email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) signup_timestamp = models.DateTimeField(default=now, editable=False) objects = CustomUserManager() def __str__(self): return self.username Seller Model: class SellerAccount(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) active = models.BooleanField(default=True) username = CustomUser.username timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse("artist_detail", kwargs={"artist_name": self.user.username}) Sellers a particular user is following: class WatchedArtist(models.Model): user = models.ForeignKey(CustomUser, null=False, on_delete=models.CASCADE) seller = models.ForeignKey(SellerAccount, null=False, on_delete=models.CASCADE) watched = models.BooleanField(default=True) timestamp = models.DateTimeField(default=now, editable=False, blank=True, null=True) Products of sellers: class Product(models.Model): seller = models.ForeignKey(SellerAccount, null=False, on_delete=models.CASCADE) title = models.CharField(max_length=30, blank=False) slug = models.SlugField(unique=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): view_name = "products:detail" … -
127.0.0.1:8000 redirected you too many times
i have my decorator.py to restrict the users to access staff panel,home route is only for staffs and user_profile is only for customer def staff(view_func): def action(request,*args,**kwargs): if request.user.is_staff or request.user.is_admin: return redirect('home') elif request.user.is_user : return redirect("user_profile") else: return view_func(request) return action this is my home function: @staff def home(request): customer=Customer.objects.all() order=Order.objects.all() total_order=Order.objects.count() total_order_delivered=Order.objects.filter(status="Delivered").count() total_number_of_pending=Order.objects.filter(status="Pending").count() myFilter=OrderFilterDashboard(request.GET,queryset=order) order=myFilter.qs content={"customers":customer,"orders":order, "total_number_of_order":total_order, "total_number_of_order_delivered":total_order_delivered, "total_number_of_order_pending":total_number_of_pending, "myFilter":myFilter} return render(request, 'accounts/dashboard.html',content) this is the user_profile route: def user_profile(request): return render(request,"accounts/user.html") -
Returning 0 if resullt is None to avoid 'NoneType' and 'decimal.Decimal'
I am trying to add return 0 in case the final result of an equation is None to get away from: TypeError: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal' but it is not working for me. The reason for this is that the no. of sold count can be zero so it returns Type Error. Here is the function: def designer_total_discount_price(self): total_sold_discount = self.count_sold * self.discount_price return 0 if total_sold_discount is None else total_sold_discount def designer_total_price(self): total_sold_regular = self.count_sold * self.price return 0 if total_sold_regular is None else total_sold_regular def designer_total(self): if self.discount_price: return self.designer_total_discount_price() return self.designer_total_price() def get_designer_final(self): return self.designer_total() * self.designer_profit -
Unable to upgrade pip properly and given "/usr/local/bin/python -m pip install --upgrade pip" on command
I'm making a website on django and I receive the warning below about pip. I have updated it twice, once outside docker and the other within it. I still receive this warning. How do I go about properly updating it? WARNING: You are using pip version 20.1.1; however, version 20.2 is available. You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command. -
Does Django Channels create a new consumer with every use?
I have a consumer class BingoConsumer(WebsocketConsumer): logged_in = 0 def connect(self): async_to_sync(self.channel_layer.group_add)( "login", self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( "login", self.channel_name ) self.logged_in -= 1 def receive(self, text_data): text_data = json.loads(text_data) if text_data['type'] == 'login': self.logged_in += 1 async_to_sync(self.channel_layer.group_send)( "login", { 'type': 'login', 'count': self.logged_in, } ) def login(self, event): self.send(text_data=json.dumps({ 'type': 'login', 'total': event['count'], })) Which gets called every time a user logs in to my website, it'll automatically call the websocket with type 'login'. I want to track the amount of users currently logged in, but currently no matter how many people are logged in, it remains 1. Which makes me wonder, does Django consider a consumer to be single use class? Does it create them and destroy them as needed?