Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to login custom user in django? (UNIQUE)
I want to login custom user, but it returns an error {'username': [ValidationError(['A user with that username already exists.'])]} . I have a model of Worker which inherits from User model, but also has some unique fields. models.py class Worker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=150) branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True) position = models.CharField(max_length=200) manager = models.BooleanField(default=False) def __str__(self): return self.fullname views.py def loginUser(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) fullname = request.POST.get('fullname') if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') try: user = User.objects.get(username=username) except: print('User does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) try: worker = Worker.objects.get(user=user, fullname=fullname) if worker.manager == False: return redirect('main') else: return redirect('manager-main') except: print('No such worker') form = UserForm() return render(request, 'supply/login.html', {'form':form}) else: print('Username or password does not exist') else: print(form.errors.as_data()) return render(request, 'supply/login.html', {'form':form}) So, I'm trying to login user, and then trying to get worker using user. After that, I check if the worker is manager. If he is, I redirect him to a page for managers. If he is not, I redirect him to his page. But if there is no such worker, I render login page … -
How to select multiple choices for a field in django?
Ihave this Actor model on the app called crew. from django.db import models # Create your models here. class Parent(models.Model): # name=models.CharField(max_length=30,unique=True,default=None) name=models.CharField(max_length=30,unique=True,default=None) about=models.TextField(max_length=2000,blank=True,null=True) class Meta: abstract = True def __str__(self): return self.name class Actor(Parent): slug=models.SlugField(max_length=50,unique=True) photo=models.ImageField(upload_to='crew/actor') i want to add this model as a foreign key into the model called Movie which is on the app movie. and also want to select multiple actors on the fiels called starring from django.db import models from django.contrib.auth.models import User from crew.models import * from review_awards.models import * # Create your models here. class Movie(models.Model): name=models.CharField(max_length=100,unique=True,blank=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) poster=models.ImageField(upload_to='movies/poster') cover=models.ImageField(upload_to='movies/cover',null=True) duration=models.CharField(max_length=50,default=None) streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True) ott=models.TextField(max_length=50,blank=True,null=True) **starring**=models.ForeignKey(Actor,on_delete=models.CASCADE,related_name='actor',blank=True,null=True) director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True) cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True) writer=models.CharField(max_length=100,blank=True) based =models.CharField(max_length=100,blank=True,null=True) genre=models.CharField(max_length=100,blank=True) awards=models.ForeignKey(Award,on_delete=models.CASCADE,null=True,blank=True) critic_reviews=models.ForeignKey(Critic_Review,on_delete=models.CASCADE,null=True,blank=True) audience_reviews=models.ForeignKey(Audience_Review,on_delete=models.CASCADE,null=True,blank=True) rating=models.CharField(max_length=20,blank=True) certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True) synopsis=models.TextField(max_length=1000,blank=True) trailer=models.TextField(max_length=50,blank=True) def __str__(self): return self.name How can i implement it?, currently iam able to select only one choice. -
Reverse Serializing Many to Many Relations Causes RecursionError
Following on from this answer, I've attempted to reverse serialize objects from a many to many relationship. Using a serializer method field, I've tried to populate the people that have a person type however this is causing a RecursionError from django. I can see the issue, PersonA has PersonTypeA who has PersonA etc. but I'm not sure how to 'flatten' the returned people to one level. How can I overcome the recursion error? Models: class PersonType(models.Model): name = models.CharField(max_length=128) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now_add=True) start_time = models.DateTimeField() end_time = models.DateTimeField(null=True) class Person(models.Model): title = models.CharField(max_length=16) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email_address = models.CharField(max_length=256) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now_add=True) start_time = models.DateTimeField() end_time = models.DateTimeField(null=True) person_types = models.ManyToManyField(PersonType, related_name="people") Serializers: class PersonTypeSerializer(serializers.ModelSerializer): people = serializers.SerializerMethodField() class Meta: model = PersonType fields = '__all__' def get_people(self, obj): people = obj.people.all() response = PersonSerializer(people, many=True).data return response class PersonSerializer(serializers.ModelSerializer): person_types = PersonTypeSerializer(many=True) class Meta: model = Person fields = '__all__' depth = 1 -
errror 503 in host /opt/alt/python310/bin/lswsgi: No such file or directory
I uploaded my python project to the host and made the necessary database settings and things, but it still gives me a 503 error. When I look at the log file, I get the following error. Please, if anyone knows, I would appreciate it. /usr/local/lsws/fcgi-bin/lswsgi_wrapper: line 18: /opt/alt/python310/bin/lswsgi: No such file or directory install packeges mysqlclient migrate settengs database allwed_host and passenger_wsgi , I did all these things, but the site did not load -
I am not able to save comments enter by user to database and retrive it to show on templates
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>{{hotel.name}}</h1> <p>{{hotel.address}}</p> <p>{{hotel.city}}</p> <p>{{hotel.state}}</p> <p>{{hotel.Zip_code}}</p> <h2>Comment</h2> {% for C in hotel.comment.all %} <p>{{ C.comment }}</p> {% endfor %} <form action="/hotel/{{hotel.id}}/comment/" method="POST"> {% csrf_token %} <input type="text" name="comment" placeholder="your comment"> <input type="submit" value="comment"> </form> </body> </html> above code is for hotel_details.html where user will put comment and it will save in database and user will also able to see other users comment from django.shortcuts import render from demo.models import Hotel def hotel_list(request): hotel = Hotel.objects.all() context = { 'hotel': hotel, } return render(request, 'hotel_list.html',context) def hotel_details(request,hotel_id): hotel=Hotel.objects.get(id=hotel_id) context={ 'hotel':hotel, } return render(request, 'hotel_details.html',context) # Create your views here. def comment_on_hotel(request,hotel_id): hotel=Hotel.objects.get(id=hotel_id) if request.method == 'POST': comment=request.POST['comment'] hotel.comment += f'\n{comment}' hotel.save() return render(request, 'hotel_details.html',{'hotel':hotel}) above is views.py Models .py from django.db import models # Create your models here. class Hotel(models.Model): name=models.CharField(max_length=255) address=models.CharField(max_length=255) city=models.CharField(max_length=255) state=models.CharField(max_length=255) Zip_code=models.IntegerField() comment=models.TextField() urls.py from django.contrib import admin from django.urls import path from demo import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.hotel_list,name='hotel_list'), path('hotel/<int:hotel_id>/',views.hotel_details, name='hotel_details'), path('hotel/<int:hotel_id>/comment/',views.comment_on_hotel , name='comment'), ] please anyone can help why this problem is happening I want that in hotel_details.html page a user should able to enter comment for particular hotel selected by him and it should … -
Django Rest Framework custom api.html throws warnings on OPTIONS request ajax form
I'm building my custom api.html template for Django Rest Framework api project (based on the official base.html template to customize mine), but I'm facing some issues implementing the OPTIONS button. Here it is my code: {% load static %} {% load i18n %} {% load rest_framework %} <!DOCTYPE html> <html lang="en" id="myHtml"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>My project title</title> <link rel="shortcut icon" href="{% static 'assets/compass-fill.ico' %}" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3/dist/css/bootstrap.min.css" rel="stylesheet" /> <link id="theme-link" rel="stylesheet" href="https://bootswatch.com/5/darkly/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" /> <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script> </head> <body> <div class="container"> ... {% if options_form %} <form class="button-form" action="{{ request.get_full_path }}" data-method="OPTIONS" > <button type="submit" class="btn btn-primary" data-bs-toggle="tooltip" data-bs-title="Make an OPTIONS request on the {{ name }} resource" data-bs-custom-class="tooltip-success" > OPTIONS </button> </form> {% endif %} ... </div> ... <script type="application/json" id="drf_csrf"> { "csrfHeaderName": "{{ csrf_header_name|default:'X-CSRFToken' }}", "csrfToken": "{% if request %}{{ csrf_token }}{% endif %}" } </script> <script src="{% static 'rest_framework/js/ajax-form.js' %}"></script> <script src="{% static 'rest_framework/js/load-ajax-form.js' %}"></script> <script src="{% static 'rest_framework/js/csrf.js' %}"></script> <script> other scripts </script> </body> </html> I created the OPTIONS button like in the original template base.html and in the end of the body I loaded js functions without them the button … -
add request.user to serialized data
iam created api request for creating a entity with collected data my view is like this ` @permission_classes([IsAuthenticated]) @api_view(["POST"]) def createAppoinment(req): appoinment=CreateAppoinmentSerializer(data=req.data) if appoinment.is_valid(): appoinment.save() return Response(appoinment.data,status=status.HTTP_201_CREATED) print(appoinment.data,"this is appoinment") return Response(appoinment.errors,status=status.HTTP_404_NOT_FOUND)```` and my serializer is like this class CreateAppoinmentSerializer(serializers.ModelSerializer): class Meta: model=Appoinment fields=['applicant_name','submission_date','appoinment_date', 'care_of','phone','appoinment_time','pass_seva_username', 'pass_seva_password','office','agency','paid','net_amo my model have additional foreign key field owner and a onetoone field, transaction how can i add the owner field and transaction field to to serilizer for create new entity i want to save datas from the front end in data base but i dont know how to add user and other foreign keys to serialization -
Celery task not executing in Django project with Redis broker
I'm working on a Django project where I'm using Celery with a Redis broker to run asynchronous tasks. I have a task that is supposed to run every minute, but it's not executing as expected. The task is received by the Celery worker, but it doesn't seem to be executed. Here's the code for my task: # socials/tasks.py from celery import shared_task import logging logger = logging.getLogger(__name__) @shared_task def hello(): logger.info("Hello") print("Hello") And here's my Celery configuration in Django settings: # settings.py CELERY_BROKER_URL = 'redis://localhost:6379/0' # I'm running Redis locally CELERY_BEAT_SCHEDULE = { 'every-minute': { 'task': 'socials.tasks.hello', 'schedule': crontab(minute='*/1') }, } I'm running the Celery worker and beat services with the following commands: celery -A my_project worker --loglevel=info celery -A my_project beat --loglevel=info The worker log shows that the worker is running and the socials.tasks.hello task is registered: [tasks] . socials.tasks.hello The beat log shows that the beat service is running and connected to the Redis broker: Configuration -> . broker -> redis://localhost:6379/0 However, the hello task is not executing. There are no error messages in the logs, and the task doesn't print "Hello" or log the message "Hello". I've checked that the Redis server is running, and the worker … -
How to display images in webpage in django with multiple apps
I currently have 2 applications. When I first made the first app it was displaying the images correctly. I would upload the images in the admin console then the image would be displayed in the webpage. Feeling confident I made another app on the same project with a different purpose but recycled the code to display images and now both apps are no working. The directory crm |_crm |_settings.py |_urls.py |_wsgi.py |_*.py |_website(app1) |_*.py |_templates |_*.html |_media |_images.png |_gamot(app2) |_*.py |_templates |_*.html |_manage.py Main/Global files Settings.py STATIC_URL = 'static/' MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_FILES_DIRS = (os.path.join(BASE_DIR,'static'),) urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('gamot/', include('gamot.urls'),name='gamot'), path('crm/', include('website.urls'),name='crm'), ] App Files View.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .forms import SignUpForm,AddRecordForm from .models import * def upload_image(request): person = Person.objects.get(id=1) return render(request,'upload.html',{'person':person}) models.py from django.db import models class Person(models.Model): image = models.ImageField(null=True,blank=False,upload_to='img/') created_at = models.DateTimeField(auto_now=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) Urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ ... path('upload',views.upload_image, name='add_record'), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Html {% extends 'base.html'%} {% … -
How to filter the most similar object from the sql query
I have the model which contains name with max length of 100 and there are about 5 lack data. And i have to filter the list of most similar object -
Django post_save signal, executing chained tasks
When I save a model I want to create some folders, then download a few things to those folders. Folders need to be created for the downloads, obviously, downloads can happen in parallel. HEre's what I have: @receiver(post_save, sender=Game) def after_game_model_save(sender, instance, created, **kwargs): logger.info("after_game_model_save") task = None task_id = uuid4() tasks_chain = chain(create_game_folder.s(instance.id)) if created: tasks_chain |= download_game.s(instance.id, instance.download_link).set( task_id=str(task_id) ) else: if instance.tracker.has_changed("screenshots_urls"): tasks_group = group( [ download_game.s(instance.id, instance.download_link).set( task_id=str(task_id) ), download_screenshots.s(instance.id), ] ) if instance.tracker.has_changed("download_link"): tasks_group = group( [ download_game_update.s(instance.id, instance.download_link).set( task_id=str(task_id) ), download_screenshots.s(instance.id), ] ) tasks_chain |= tasks_group tasks_chain.delay() try: task_obj = Task.objects.get(game=instance) task_obj.task_id = str(task_id) task_obj.save() except Task.DoesNotExist: Task.objects.create(game=instance, task_id=str(task_id)) I'm getting the error TypeError: download_game() takes 2 positional arguments but 3 were given If I interpret the examples correctly, the result of the first chained task get's sent as an argument to the second task? How can I chain tasks so they're executed in order without worrying about this? The functions return nothing. So I guess right now I end up with something like download_game.s(instance.id, instance.download_link, None) -
How to encrypt and decrypt access passwords in Django?
My Django application needs a table to store credentials of different users to access external databases that store their information. There are security and technical reasons not to use the same database that Django uses. But during storage, I would like to encrypt the passwords before inserting to the persistance, and later a way to decrypt them in order to make use of them. My first approach was to use make_password function, but I couldn't find a way to decrypt back the passwords. Right now I'm testing django signals with a pre_save script that encrypts the password using cryptographi.fernet algorithm. And later, this is decrypted inside the view execution. For encryption and decryption, I'm saving the key in settings file (loaded from environment). I would like to know if this is secure enough procedure to manage credentials to critical information of my users. Also if there is any way to get the password back when using make_password function. -
Django inbuilt Auth not logging me in despite successfully registering the user
i would like to login after registering a user that is saved using my customuser model that exends abstractuser. after registering the user, i redirect them to the login page. and when i try to login the user with the credentials that is just created, it will say "__ all __ Please enter a correct username and password. Note that both fields may be case-sensitive." when i print form.errors i am not sure why the backends is throwing this error, i have tried looking into the authenticationform that i extended as well as the save and create_user. just wondering too; is it better if i created a userprofile model instead of extending the default django user model? here is my models.py class CustomUserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password, **other_fields): print('in customusermanager create_user') if not email: raise ValueError(gettext_lazy('You must provide a valid email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, last_name=last_name, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, email, username, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser %s must be assigned to is_staff=True' % (username)) if other_fields.get('is_superuser') is not True: raise ValueError('Superuser %s must be assigned to … -
How do I set up python intepreter in VS code on Mac OS 13.4.1?
After I post the path of the project obtained by the command pipenv --venv into the command palette of vs code, it is supposed to create a new vs code settings file according to this tutorial https://www.youtube.com/watch?v=rHux0gMZ3Eg&t=3158s (timestamp 20 mins) however in my case, none of the changes are taking place. What could be the possible problem or solution for this? I tried creating a new directory which did not work. I even tried entering /bin/python3.11 as the path of the interpreter but it was unsuccessful. -
My css is no longer linking to my django template
Everything was working very fine,my css file was linking to my django template,all of a sudden everything stopped working. I already configured my settings.py,my URL'S.py,and used "{% load static %}" in my template and everything was okay but for some reason it just stopped at some point.Please can anyone please help with the solution I have tried to use a different browser but it still is not working -
how i doing deploy django app to vercel when i get this error
I've been stuck for a few days when I try to deploy my django app through the vercel. And vercel give the syntax error. Failed to run "pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt" Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [35 lines of output] /tmp/pip-build-env-cc0ii6jl/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg` !! ******************************************************************************** The license_file parameter is deprecated, use license_files instead. By 2023-Oct-30, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! parsed = self.parsers.get(option_name, lambda x: x)(value) running egg_info writing psycopg2.egg-info/PKG-INFO writing dependency_links to psycopg2.egg-info/dependency_links.txt writing top-level names to psycopg2.egg-info/top_level.txt Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). … -
ReactJS + django 400 bad request
I'm making website using django and react. I have already set up backend in django and tested it using postman, everything works fine but when I'm doing exact same thing using react i'm getting 400 error. Tried to do it like that: To avoid any other error I used static data in this example export default function MakePost(){ const [userID, setUserID] = useState(1); const [text, setText] = useState(''); const submit = async e => { e.preventDefault(); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({id: 1, text: 'some text'}) } fetch('http://localhost:8000/api/make-post/', requestOptions) .then(response => { console.log(response) if(response.ok){ return response.json(); } }); window.location.reload(); } -
Django How to download files from file system?
I'm fairly new to Django so any help will be much appreciated. I'm trying to make a link to a file path on a Windows server downloadable to the user after they click the file link. My app displays entries from a result of searching a ticket model. The results on the page include items like: Ticket number, description, status and a link to a flat file (that is stored on a Windows server network share drive; starting with \server.name\folder A\folder B\folder C\file to download.txt *Note \server.name, \folder A and \folder B are a constant \folder C (as well as the file to download are dynamic (they location and file name will change) users will NOT be uploading files. All files that are downloadable - are already saved to a Windows share. On the display page/template.html I can list all my values in a table (even a link the the file I'd like to download). However, when I hover over the link at the bottom of the browser I see file://server.name/folder A/folder B\folder C\file to download.txt. Yes, the last "slash" is a forward slash while all the others are back slashes (not sure why they are changing?) When I pass … -
I want to make Sales invoice، purchase invoice by django
I create models and forms then in template i repeat form to look like multi items but when i click save it save one of these item Can any one help me to solve Model = item.Name, price, quantity, expiry date, supplier name, item code, I want to write 25 item in on sales invoice Then save them all in one time -
import errors in pytest unable to run tests
I'm having a problem with my imports in my django project, I'm trying to run my first tests in pytest but I'm getting import errors: name = 'tasks', package = None def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: msg = ("the 'package' argument is required to perform a relative " "import for {!r}") raise TypeError(msg.format(name)) for character in name: if character != '.': break level += 1 > return _bootstrap._gcd_import(name[level:], package, level) E ModuleNotFoundError: No module named 'tasks' /usr/local/lib/python3.11/importlib/__init__.py:126: ModuleNotFoundError ================================================================================= short test summary info ================================================================================= FAILED core_apps/tracker/tests/test_tasks.py::FetchAndStoreVehicleModelsTest::test_existing_models_are_updated - ModuleNotFoundError: No module named 'tasks' FAILED core_apps/tracker/tests/test_tasks.py::FetchAndStoreVehicleModelsTest::test_new_models_are_created - ModuleNotFoundError: No module named 'tasks' this is my project diretory tree core_apps ├── __init__.py ├── tracker │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── services │ │ ├── coopart.py │ │ └── __init__.py │ ├── tasks.py │ ├── tests │ │ ├── __init__.py │ │ └── test_tasks.py … -
How to optimize django postgres search
I'm using postgres search on my Django project. And I must search by title, content and tag of article model. Couse of conetent could contain too many chars, search works too slow. For example, my db has 1000 articles and each article has 5000 chars there will be 5 million chars. So search will work slow. How can I optime it? # models.py class Article(models.Model): class Statuses(models.TextChoices): DRAFT = ( "draft", _("Draft"), ) PUBLISHED = "published", _("Published") BANNED = "banned", _("Banned") DELETED_ARTICLE = "deleted_article", _("Deleted Article") DELETED_AUTHOR = "deleted_author", _("Deleted Author") FOR_TEST = "for_test", _("For test") objects = ArticleQueryset.as_manager() title = models.CharField(verbose_name=_("title"), max_length=255) author = models.ForeignKey(User, related_name="articles", null=True, on_delete=models.SET_NULL) content = BleachField( verbose_name=_("content"), max_length=20000, validators=[MinLengthValidator(750)] ) status = models.CharField(max_length=15, choices=Statuses.choices, default=Statuses.DRAFT) banner = models.CharField(blank=True, max_length=255) created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True, null=True) modified_date = models.DateTimeField(auto_now=True, blank=True, null=True) deleted_date = models.DateTimeField(blank=True, null=True) slug = models.SlugField(default="", editable=False, max_length=255, null=False) read_time = models.IntegerField(default=0) liked_users = models.ManyToManyField(User, related_name="liked_articles", blank=True) view_count = models.IntegerField(default=0) total_users_viewed = models.IntegerField(default=0) # seconds total_users_engagement_duration = models.IntegerField(default=0) score = models.IntegerField(default=0, db_index=True) tags = TaggableManager() def __str__(self): return self.title # filters.py class ArticleFilter(django_filters.FilterSet): q = django_filters.CharFilter(method="search_filter") def search_filter(self, queryset, _, value): search_vector = ( SearchVector( "title", weight="B", ) + SearchVector(StringAgg("tags__name", delimiter=" "), … -
Django DRF: Why is the field not populated by the user from the request
When sending a POST request to create a follow in the FollowViewSet view, there is a requirement to manually enter the user field. Why isn't the user field automatically populated and how can this be fixed? I suspect the issue is with the validator... views.py class FollowViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = FollowSerializer permission_classes = (IsAuthenticated,) filter_backends = (filters.SearchFilter,) search_fields = ('following__username',) def get_queryset(self): return self.request.user.follows_user.all() def perform_create(self, serializer): serializer.save(user=self.request.user) serializers.py class FollowSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(read_only=True, slug_field='username') following = serializers.SlugRelatedField( queryset=User.objects.all(), slug_field='username' ) class Meta: fields = ('user', 'following') model = Follow validators = [ UniqueTogetherValidator( queryset=Follow.objects.all(), fields=['user', 'following'] ) ] def validate(self, data): user = self.context['request'].user if user.username == data['following']: raise serializers.ValidationError('Нельзя подписаться на себя!') return data models.py class Follow(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follows_user', verbose_name='Подписавшийся пользователь') following = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follows', blank=False, verbose_name='Пользователь, на которого подписаны') class Meta: verbose_name = 'Подписка' verbose_name_plural = 'Подписки' unique_together = ["user", "following"] def __str__(self): return f'{self.user.username} отслеживает {self.following.username}' With a GET request, all subscriptions should be displayed in the form: [ { "user": "string", "following": "string" } ] For a POST request with a request body like: { "following":"admin" } a Follow object should be created and output as a … -
How do I get around ModuleNotFoundError: No module named 'dot env
I am doing the official django tutorial polls app on part 5 which is about testing in django. As a part of the instructions I am supposed to go into my models.py file and run the python manage.py shell command to activate a shell terminal. From there I am supposed to run a series of commands to import things for my test. Link to material: https://docs.djangoproject.com/en/4.2/intro/tutorial05/ The commands I need to run are: >>> import datetime >>> from django.utils import timezone >>> from polls.models import Question >>> # create a Question instance with pub_date 30 days in the future >>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30)) >>> # was it published recently? >>> future_question.was_published_recently() True I run the import datetime, and from django.utils import timezone and there are no issues. Once I get to from polls.models import Question I am hit with an error message no modulenotfounderror" no module named dot env. I have tried looking at stack overflow articles and they suggested installing it via pip. So I exited my shell command and tried installing dotenv with pip. When I do so I get the following error message shown in the screenshot. I looked at this stack overflow article python … -
Implementing real time filtering/search with Django and React not working as expected
I'm trying to implement real time filtering/search with Django and React. But I'm not getting desired results? Please what did I do wrong? Here is my views.py file: class FilterFormView(generics.ListAPIView): serializer_class = JournalSerializer def get_queryset(self): qs = Journal.objects.all() title_contains_query = self.request.query_params.get("title_contains") if is_valid_query_param(title_contains_query): qs = qs.filter(title__icontains=title_contains_query) return qs The filtering Form in React looks like this: useEffect(() => { fetchJournals(); }, [title_contains]); const fetchJournals = async () => { setLoading(true); try { const res = await axios.get(myurl); setPost(res.data); setLoading(false); } catch (e) { console.log(e); } }; const handleChange = (e) => { settitle_contains({ ...title_contains, [e.target.name]: e.target.value, }); }; return ( <React.Fragment> <input onChange={handleChange} type="text" name="title_contains" id="title_contains" /> {post.map((jour) => { return <div>{jour.title}</div>; })} {loading && <div>Data is Loading</div>} </React.Fragment> ); This was how I set my url: const [title_contains, settitle_contains] = useState(""); const url = new URL("http://127.0.0.1:8000/api/?"); url.searchParams.set("title_contains", title_contains); I got this from the server console whenever I typed in the input field and no filtering occured in the frontend: [08/Jul/2023 19:40:38] "GET /api/?title_contains=%5Bobject+Object%5D HTTP/1.1" 200 2 But if url is set like this: const myurl = http://127.0.0.1:8000/api/?${title_contains}; Then I got this from the server console each time I type in the input field and no filtering occured in the … -
How to show more object information on forms in django
This is a follow up question to this question: How to pass user object to forms in Django Here is my form: class SellForm(forms.Form): symbol = forms.ModelChoiceField(queryset=None, widget=forms.Select(attrs={ 'class': 'form-control', 'placeholder': 'Symbol', 'autofocus': 'autofocus', })) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(SellForm, self).__init__(*args, **kwargs) self.fields['symbol'].queryset = Holdings.objects.filter(student=self.request.user.student) This form is providing me with this dropdown: I have extra information in the model which is the purchase price of each share, is there a way to get this onto the form also? It would have to be non editable though as its the price that the share was purchased at. Here is the model that the form is getting the data from: class Holdings(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) symbol = models.CharField(max_length=10) purchase_price = models.DecimalField(max_digits=10, decimal_places=2) class Meta: verbose_name_plural = "Holdings" ordering = ['symbol'] def __str__(self): return self.symbol I would very much appreciate any help if possible! Thank you!