Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show row numbers in django admin listview using the frontend
I wanted to show row number in django admin listview as in the image tried doing it in the admin.py with the following code in different modeladmins: indexCnt = 0 def index_counter(self, obj): count = Basic_inspection.objects.all().count() if self.indexCnt < count: self.indexCnt += 1 else: self.indexCnt = 1 return self.indexCnt But there are problems with this approach, it gets disordered when changing the list page, changing the "sort by" or even when multiple requests to the site. How can I show row numbers in listview using the templates? -
value too long for type character varying(100) in django
i am trying to add an item from admin panel but when i click to save then it throws me above-mentioned error and i don't have any slug field in my model here is the trace back of that error do i have to paste the model or you got the issue Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (value too long for type character varying(100) ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1657, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1540, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1586, in _changeform_view self.save_model(request, new_object, form, not add) File … -
cPanel Django Deploy: Passengerfile.json' for reading: Permission denied (errno=13)
I am trying to deploy my first Django application via my GoDaddy cPanel. I created my application in a virtual environment, but I'm stuck. I installed django then create wsgi file also. but now when I run the site it shows me this: Passenger error #2 An error occurred while trying to access '/home/u4sgzlaz0pwz/repositories/rentaltake/Passengerfile.json': Error opening '/home/u4sgzlaz0pwz/repositories/rentaltake/Passengerfile.json' for reading: Permission denied (errno=13) Apache doesn't have read permissions to that file. Please fix the relevant file permissions. -
Html tags are displayed on webpage, after rendering django template
{% for neighborhood in neighborhoods_formset %} {% csrf_token %} <td> <input class="form-control" type="text" value="{{ neighborhood.name }}" name="name_{{ neighborhood.id | default:'' }}" /> </td> {% endfor %} {{ neighborhoods_formset.management_form }} I used modelfomset_factory to create a formset, but I have this issue when trying to render it. Here you can see how it appears -
Django Custom Model Data Field Is Using Wrong Function
Here is model.py: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.core import signing from django.db import models class EncryptedApiField(models.TextField): def __init__(self, *args, **kwargs): super(EncryptedApiField, self).__init__(*args, **kwargs) def get_db_prep_save(self, value, connection): value = super().get_db_prep_value(value, connection) if value is None: return value print('get_db_prep_save') return ((signing.dumps(str(value))).encode('utf-8')).decode('utf-8') def to_python(self, value): if value is None: return value return signing.loads(value) def from_db_value(self, value, *args, **kwargs): return self.to_python(value) class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, first_name, password, **other_fields): return self.create_user(email, username, first_name, password, **other_fields) def create_user(self, email, username, first_name, password, **other_fields): email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class NewUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_subscribed = models.BooleanField(default=False) subscription_level = models.IntegerField(default=0) test = EncryptedApiField(blank=True) objects = CustomAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['test', 'email', 'first_name', 'last_name'] def __str__(self): return self.username I'm trying to create a custom data field where the data is automatically encrypted/decrypted the problem is when I createsuperuser the EncryptedApiField class runs to_python instead of get_db_prep_save thus I'm getting django.core.signing.BadSignature: No ":" found in value error I'm also not getting print('get_db_prep_save') in the terminal but a print in to_python would work … -
getting error when try to run "rasa x" in terminal using anaconda3 with python 3.7.0
(rasa_conda_env) C:\Users\Admin\Desktop\rasa_conda>rasa x Starting Rasa X in local mode... 🚀 Traceback (most recent call last): File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\rasa\cli\x.py", line 502, in run_locally domain_path=domain_path, File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\rasax\community\local.py", line 226, in main rasax.community.jwt.initialise_jwt_keys() File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\rasax\community\jwt.py", line 68, in initialise_jwt_keys private_key, public_key = cryptography.generate_rsa_key_pair() File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\rasax\community\cryptography.py", line 28, in generate_rsa_key_pair backend=default_backend(), File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\cryptography\hazmat\backends_init_.py", line 14, in default_backend from cryptography.hazmat.backends.openssl.backend import backend File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\cryptography\hazmat\backends\openssl_init_.py", line 6, in from cryptography.hazmat.backends.openssl.backend import backend File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\cryptography\hazmat\backends\openssl\backend.py", line 113, in from cryptography.hazmat.bindings.openssl import binding File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\cryptography\hazmat\bindings\openssl\binding.py", line 14, in from cryptography.hazmat.bindings._openssl import ffi, lib ImportError: DLL load failed: The specified procedure could not be found. Sorry, something went wrong (see error above). Make sure to start Rasa X with valid data and valid domain and config files. Please, also check any warnings that popped up. If you need help fixing the issue visit our forum: https://forum.rasa.com/. -
Posts which are not liked by user
I am building a Blog App and I am trying to show posts which are not liked by request.user, I have tried :- from django.db.models import Exists checkIt = BlogPost.objects.annotate(is_liked=Exists( Like.objects.filter(user=request.user))) But it is showing all the posts. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE) views.py def unliked_posts(request): posts = BlogPost.objects.filter(like__user=request.user).exclude(like__user=request.user) context = {'posts':posts} return render(request, 'unliked_posts.html', context) I have tried many time but it didn't worked for me. I will really appreciate your Help. Thank You -
Django DRF - Nested serializers for OneToOne related models results in KeyError when retrieving data objects
Background I have an OneToOne relation between a type of user (UsertypeA) and my custom base user (UserProfile). However, there is an issue when hitting the API endpoint to retrieve all objects of UsertypeA, I keep getting "Got KeyError when attempting to get a value for field 'user' on serializer UserTypeASerializer. The serializer field might be named incorrectly and not match any attribute or key on the 'dict' instance. Original exception text was: 'usertypeA'." I tried and follow the Django-OneToOne-Relations and DRF-nested-serializers docs as much as I can, but still cannot find the issue of the logic below, and why my UserTypeA.user attribute is not getting serialized UserProfile: # models.py class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=150, unique=True) ... # serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: fields = ('email', 'username', 'first_name', 'last_name', ...) model = UserProfile def create(self, validated_data): return UserProfile.objects.create_user(validated_data) def update(self, instance, validated_data): return UserProfile.objects.update_user(instance, validated_data) UserTypeA # models.py class UserTypeA(models.Model): usertypeA_uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField( UserProfile, on_delete=models.CASCADE, related_name='usertypeA', related_query_name='usertypeA') ... @property def username(self): return self.user.username def __str__(self): return str(self.usertypeA_uuid) # serializers.py class UserTypeASerializer(serializers.ModelSerializer): user = UserSerializer(required=True, source='usertypeA') class Meta: fields = ('usertypeA_uuid', 'user', 'membership_type' ...) model = UsertypeA depth = 1 def … -
Custom Primary Key in Django
so I am creating a project called an "Electronic Reference Library" (ERL). I am using Django 3.2 to create this app and here is a model of the Resource Table. class Resource (models.Model): resource_id = models.CharField(primary_key=True, max_length=20) type = models.CharField(choices=RESOURCETYPE, default="WebLink", max_length=10) link = models.URLField() subject = models.ForeignKey(YearGroupSubject, on_delete=models.CASCADE) topic = models.CharField(max_length=50) description = models.TextField() unit_no = models.CharField(max_length=10) search_query = models.CharField(max_length=300) status = models.CharField(choices=STATUS, default="Pending", max_length=30) posted_by = models.ForeignKey(ProfileStaff) posted = models.DateTimeField(auto_now=True) approved_time = models.DateTimeField(null=True, blank=True) views = models.PositiveIntegerField(default=0) So in this case my client wanted a custom Primary Key, where the format has to be something like MATH-YYMMDD-HHMMSS-00. Where MATH can be replaced by the primary key of the YearGroupSubject table which is a 4 letter string. Where YYMMDD-HHMMSS is replaced by the current date and time. Replacing the 00 with any random integer (can even be 5 integers long, not a worry). But I am not aware of how to have a custom made primary key, which is automatically generated by Django. Is this possible? If not is there any other better alternative? Any help would be greatly appreciated. Thanks! -
Django Models : How to update value if case matches else keep the current value
I want to perform an update operation on a Django queryset conditionally such that the value of an attribute is updated only when it matches a condition otherwise keep the value it is currently having. I know that conditional updates in django are performed using Case, When, then, default but not getting how to keep the existing value for the default case. I tried leaving default from the query but then it throws an error. I want something like the following. Say there are 4 types of schemes: PRO, REGULAR, HOME, FREE. Customer.objects.filter(age__lte=18)\ .update(type=Case(When(type=HOME, then=FREE), default=<keep current value>), subscribed=False) -
How to pass concatenated functions as a argument in django model method
I am trying to pass timezone.now() + timedelta(days=-2) and timezone.now() as arguments in django model method but am getting def performance(user, timezone.now() + timedelta(days=-2), timezone.now()): ^ SyntaxError: invalid syntax I know the error is as a result of the concatenation but I dont know how to solve this problem. class User(AbstractUser): ......................... fields ......................... def get_performance(self, timezone.now() + timedelta(days=-2), timezone.now()): actual = Sum("scores", filter=Q(status="completed")) q = self.taskassignt.filter( due__gte=timezone.now() + timedelta(days=-2), due__lt=timezone.now() ).annotate(actual=actual, total=Sum("scores")) return (q[0].actual / q[0].total) * 100 -
Mulitple Django Projects as PWAs
I read this question: Django multiple Project using same database tables I am developing a PWA using Python/Django, but I thought, to help with authentication and authorization, I should have two versions, since I have one admin (owner). I am developing a fitness app. The owner (my client) can add/edit/update etc exercises, create workouts with these exercises, add new clients, assigned workouts to clients, etc The Client version, (my client's clients) will be able to complete registration, view workouts, view workouts by exercises, rate workouts. Should I even do this? Can I do this? If so, do I still need to create models in the client version? How would I even access these tables? Thank you for your suggestions. -
Image doesn't render from MySql database in my webpage
I have a database and table where i have store some info about some automobiles. The problem here is all the information saved in the database (through modelform) shows up in output page except the image. I get b'' in column of image. However, if i add the models from my admin site, i get b'Image_Name' in the image column but not image. Opps! I don't have enough points to paste the picture here! -
Views are different but rendering same template
i want to use slug field in both url which is path('<slug:title>/',views.news_read,name="news_read"), path('<slug:title>/',views.movie_read,name="movie_read"), but both the url picking same template instead of their template i am trying to create blog site i don't understand both the url are uniques so why django is picking wrong template my views for both the url def movie_read(request, title): movie = Movie.objects.filter(urltitle=title) if request.method == 'POST': form = Commentform(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank You For Your Comment') else: form = Commentform() return render(request,'movie_read.html',{'movie':movie,'form':form}) def news_read(request, title): news = News.objects.filter(urltitle=title) if request.method == 'POST': form = Commentform(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank You For Your Comment') else: form = Commentform() return render(request,'news_read.html',{'news':news,'form':form}) but i when do some change like this it work path('<slug:title>/news',views.news_read,name="news_read"), path('<slug:title>/movie',views.movie_read,name="movie_read"), but this doesn't look good any idea what to do solve the issue -
Django filter module: lookup expression (year) does not return the desired queryset
I am using the django-filter module. I would like to get all objects where the year is 2011 or greater. this is my setup ... Actual behaviour: When I enter a year, then I get the error message: "Enter a valid date." and the queryset is unchanged. I tried entering a date instead of the year, but then the whole page fails with the error message Field 'None' expected a number but got datetime.date(2011, 1, 1). The model: class BaseInvoice(models.Model): id = ShortUUIDField(primary_key=True) invoive_number = models.CharField(max_length=50) invoicing_party_ID = models.ForeignKey(InvoicingParty, on_delete=models.CASCADE) invoice_type = models.CharField( max_length=2, choices=invoice_type, default='IN' ) realestate_id = models.ForeignKey(RealEstate, on_delete=models.CASCADE) user_group = models.ForeignKey(Group, on_delete=models.CASCADE) year_of_contribution = models.DateField(auto_now=False, auto_now_add=False) start_of_period = models.DateField(auto_now=False, auto_now_add=False) end_of_period = models.DateField(auto_now=False, auto_now_add=False) interval = models.ForeignKey(Interval, on_delete=models.CASCADE, default=0) currency = models.ForeignKey(Currency, on_delete=models.CASCADE, default='EUR') class Meta: abstract = True class RealEstateTax(BaseInvoice): realestate_tax = models.DecimalField(max_digits=20, decimal_places=2) The Filter import django_filters from django_filters import DateFilter from .models import * class InvoiceFilter(django_filters.FilterSet): billing_year = DateFilter( label='Abrechnungsjahr', field_name='start_of_period', lookup_expr='year__gt' ) class Meta: model = RealEstateTax fields = ['realestate_id', 'billing_year'] The view from realestate.models import RealEstate from django.shortcuts import render from django.http import HttpResponse from .models import * from .filters import InvoiceFilter from django.db.models import Sum def utilities_bill(request): realestate_tax = RealEstateTax.objects.all() insurance_invoice … -
Heroku returns desc="No web processes running" while running Django even with a Procfile?
Ran into an issue with Django returning at=error code=H14 desc="No web processes running" method=GET path="/set-crf/" host=appxxxx.herokuapp.com request_id=8c8ded0a-5470-46c3-b371-29602549d533 fwd="100.38.206.95" dyno= connect= service= status=503 bytes= protocol=https while trying to connect to the app. After adding a Procfile, importing django-heroku and setting up requirements.txt, nothing seems to work. Here's what I have so far: Relevant Code Procfile: web: gunicorn rpa_django.wsgi settings.py: import django_heroku from pathlib import Path from corsheaders.defaults import default_headers import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'pc_algo', ] MIDDLEWARE = [ ..., "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ..., 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'rpa_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'rpa_django.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } … -
Querying Reverse ManyToMany Relationship in Django
I have a category Model and a Product Model in my django application... the product model has a many2many field pointing to the category model... and the product model has a created field to denote when it was created. how do i filter the categories model based on the created field of the product? -
Django - issue with loading css
I've recently started learning Django and I've been having a lot of issues with implementing css into my code. I've found a lot of people with the same issue as me but I am still unable to find an answer. Currently when I run open the website it give me this https://imgur.com/a/0N23s7b And I'm not sure if this is because of the settings, the actual css or something in the html. My html boilerplate {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>homepage</title> <link rel="stylesheet" type="test/css" href="{% static'css/home.css' %}"/> </head> settings.py DEBUG = True STATIC_ROOT = '' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] STATIC_URL = '/static/' views.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from leatherbiscuit.views import index urlpatterns = [ path('admin/', admin.site.urls), path('', index), ] if settings.DEBUG: urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urls.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView def index(request): return render(request, 'index.html') def home_view(request): return HttpResponse(request, 'index.html') -
same notification to multiple selected users in django
I am trying to implement a notification page on my website in Django. But I have a problem that how can I send the same notification to multiple users. let suppose I have to send it to just one user. then I can create a model of notification with noti = models.TextField() user= models.foreignkey is_seen = models.bool so this is just a sample but the the problem is this how i can send this notification to selected multiple users one important is that is_seen is compulsory for each user I hope you will understand -
How do you create a view for each model entry in Django?
I'm working on a project that is suppose to function similarly to a Wikipedia page. Each page will be formatted nearly identical with different attributes for each page. Each page would render the same template like this: <body> <ol> <li>{{object.image}}</li> <li>{{object.title}}</li> <li>Date Created: {{object.date}}</li> </ol> </body> That way all that needs to change is the object that gets fed in and it will be like there is a page for each entry in the class. The part I don't really understand how to do is how to change what object is fed through based on a url. Can i have it setup up such that domain.com/class_name/object_name will render that template displayed above and will feed through the object based on it's title? -
Django: delete user SkillFollow model when Category is unselected, every skiils belongs to a category
I have a django blog with category, skill, and course model. when users follow a category, they'll see list of skills, and when they follow a skill, they'll see list of courses.. I simply want users not to be shown course list if they are not following a category. Category=>Skill=>Courses views.py class homeview(ListView): model = Skill template_name = 'blog/bloglist.html' def get_queryset(self): return CategoryFollow.objects.filter(user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['category'] = Category.objects.all() return context class FollowCategoryView(TemplateView): template_name = 'blog/bloglist.html' def get(self, request, *args, **kwargs): category_id = kwargs['pk'] category = Category.objects.filter(id=category_id).first() skill_id = kwargs['pk'] skill = Skill.objects.filter(id=skill_id).first() if category: if request.GET.get('unfollow'): CategoryFollow.objects.filter(category=category, user=self.request.user).delete() SkillFollow.objects.filter(skill=skill, user=self.request.user).delete() else: CategoryFollow.objects.get_or_create(category=category, user=self.request.user) return redirect(reverse('index')) models.py class Category(models.Model): title = models.CharField(max_length=60) def all_user(self): return list(self.category_follow.values_list('user', flat=True)) def __str__(self): return self.title class Skill(models.Model): title = models.CharField(max_length=60) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=True) def all_user(self): return list(self.skill_follow.values_list('user', flat=True)) def __str__(self): return self.title class Course(models.Model): title = models.CharField(max_length=60) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, default=True) def __str__(self): return self.title class CategoryFollow(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_follow', verbose_name='category', ) user = models.ForeignKey(User, on_delete=models.CASCADE) class SkillFollow(models.Model): skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name='skill_follow', verbose_name='skill', ) user = models.ForeignKey(User, on_delete=models.CASCADE) bloglist.html <div class="card" style="width: 18rem;"> <ul class="list-group list-group-flush"> {% for cate in category %} {% if user.id … -
Quiz that I try to build in django - how to make it work?
I'm building a quiz of practicing Hebrew-English words. Each time the computer pulls out 4 words rednomiles from the DB and the user selects the appropriate word from the words. The problem that always starts with the request.post.get = None. And the indentation is performed in front of None which means that the result is incorrect even if the answer is correct. How can I fix it? In fact the comparison is made even before the user has made the selection. And after selection the result obtained is usually wrong. for example - in the first round the computer choose x - request.post.get = None , and now I click on x result = incorrect x != None .. next round the computer choose y - request.post.get = x , and now I click on y result = incorrect y != x.. def practice(request): words_list = Words.objects.filter(approved= True) # Take all the words that approved by the admin four_options = [random.choice(words_list) for i in range(4)] x = four_options[0] z = x.Hebrew_word random.shuffle(four_options) word = z[:4] choice_user = request.POST.get("quiz") choice_1 = str(choice_user) choice = choice_1[:4] if request.method == "POST": if choice == word: message = f'Correct {choice} == {word}' return render(request, … -
How to solve TypeError at /api/register/ Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person # fields = '__all__' fields = ('id', 'username', 'email', 'password', 'is_active', 'is_staff', 'is_superuser' , 'Designation', 'Address', 'groups', 'profile') def create(self, validated_data, ): user = Person.objects.create( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'], Designation=validated_data['Designation'], is_active=validated_data['is_active'], is_staff=validated_data['is_staff'], is_superuser=validated_data['is_superuser'], Address=validated_data['Address'], profile=validated_data['profile'], groups=validated_data['groups'] ) user.set_password(make_password(validated_data['password'])) user.save() return user How can I solve the following error: TypeError at /api/register/ Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead -
django file upload issue
i have tried to upload a picture using django file field and in my models.py file class Students(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=255) profile_picture = models.FileField() objects = models.Manager() and in project's urls.py file urlpatterns = [ path('admin/', admin.site.urls), path('', include('student_management_app.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)+static(settings.STATIC_URL,document_root=settings.STATIC_FILE_ROOT) in my setting.py file I have specified the directories like this MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATIC_URL = '/static/' STATIC_FILE_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] and in the template page I tried to view the image that got uploaded to the media folder <tbody> {% for student in students %} <tr> <td>{{ student.admin.id }}</td> <td><img src ="{{ student.profile_picture }}" style="width: 100px"></td> <td>{{ student.admin.first_name }}</td> <td>{{ student.admin.last_name }}</td> <td>{{ student.gender }}</td> <td>{{ student.address }}</td> <td>{{ student.admin.email }}</td> <td>{{ student.course_id.course_name}}</td> <td>{{ student.session_start_year }}</td> <td>{{ student.session_end_year }}</td> <td>{{ student.admin.date_joined }}</td> <td>{{ student.admin.last_login }}</td> <td><a href="/EditStudent/{{ student.admin.id }}" class="btn btn-primary">Edit</a></td> <td><a href="/DeleteStudent/{{ student.admin.id }}" class="btn btn-danger">Delete</a></td> </tr> {% endfor %} </tbody> the image is getting uploaded perfectly but I am not being able to right now the template looks like thisview them in the template the traceback is showing 11/Sep/2021 18:32:30] "GET /media/010040.jpg HTTP/1.1" 302 0 [11/Sep/2021 18:32:30] "GET /media/1580467939054_Anitha.jpg … -
IDE to develop jinja templates
I am looking for an environment to develop jinja2 for django app. I currently use pycharm but I am missing a lot of features. At least I would like live reload for the webpage (reload after template modification) or perhaps a way to set value to template variables manually without backend (for testing purposes). Any tips for jinja development in any IDE are welcome.