Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Onchange event in Django Forms?
I want to make a project which takes 4 documents from a user and I created a model, Model form, and a view. I want that when the user selects 1st field and tab to 2 fields means on change then it shows all validation error which is coming from the backend. Thanks -
what is the "complete" argument in Django and How can I use it?
I'm following a tutorial that works on a project and during he creates some code I see him use that: Order.objects.get_or_create(customer=customer, complete=False) I searched about "complete" argument on the internet but didn't find anything talking about that point, I actually don't know why he used this arg. also, I faced a problem and I didn't know what is that problem wants me to solve but I tried to add this argument in the get method in Django ORM, and when it placed this argument the error has gone. from here, why I should use this arg and when I have to use it? -
token verification fails although I sent correct token generated by view in django rest-frame work
Previously it was working fine and my token could be verified but,I don't know what happend , it returns me always as a token invalid. by using /register and email is sent for verification using these codes. view.py class RegisterView(generics.GenericAPIView) : serializer_class = RegisterSerializer renderer_classes = (UserRenderer ,) def post(self, request) : user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://' + current_site + relativeLink + "?token=" + str(token) email_body = 'Hi ' + user.username + \ ' Use the link below to verify your email \n' + absurl data = { 'email_body' : email_body, 'to_email' : user.email, 'email_subject' : 'Verify your email' } Util.send_email(data) return Response(user_data , status=status.HTTP_201_CREATED) serializers.py class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=68, min_length=6, write_only=True) default_error_messages = { 'username': 'The username should only contain alphanumeric characters'} class Meta: model = User fields = ['email', 'username', 'password'] def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not username.isalnum(): raise serializers.ValidationError( self.default_error_messages) return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) urls.py path('register/', RegisterView.as_view(), name="register"), utils.py from django.core.mail import EmailMessage import threading class EmailThread(threading.Thread): def __init__(self, email): self.email = email threading.Thread.__init__(self) … -
How to model by database for a one-to-many relationship
I am learning backend development in Django and came across this problem. Say I am designing a travel app: I have two databases USER and TRIP with one-to-many relationship. i.e., each user can have multiple trips and each trip can be taken by only one user. TRIP has a column trip-number. I would like to auto-increment this column for every row added into the TRIP database BUT the increment should be independent for each user starting from 1 TRIP table user trip-number 1 1 2 1 1 2 1 3 2 2 3 1 Something like that? I cannot auto-increment the whole column as it has to be unique for each trip taken by the user BUT the numbers can be same across different users. Ideally I prefer to this automatically on the server-end (sql) instead of writing a logic in the client. Any help would be appreciated. Thank you -
clone a Django model instance object and save it to the another model with same fields
obj = Foo.objects.get(pk=<some_existing_pk>) obj.pk = None obj.save() This method works if we are cloning objects to same model What to do if we have another model Foo2 Which is inherited from Fooconsisting of same fields of Foo I want to save obj to Foo2. Is there a shortcut to do this? -
Django: Why is it then when I put "readonly" in my input, the form becomes invalid and not submitted?
Django: Why is it then when I put "readonly" in my input, the form becomes invalid and not submitted? But when i remove the "readonly", everything works? I'm trying to make it such that users cannot edit those readonly fields. Also, after the form is submitted, I still want them to be able to view the form they have submitted but not be able to edit it. views.py @login_required(login_url=reverse_lazy("must_authenticate")) def submit_interest_view(request, slug): context = {} form = SubmitInterestForm() user = request.user blog_post = get_object_or_404(BlogPost, slug=slug) num_blogpost = BlogPost.objects.filter(author=user).count() if blog_post.author.email == user.email: return HttpResponse('You cannot submit interest to your own post.') #print(blog_post.author, user) interest_requests = Interest.objects.filter(interestsender=user, interestreceiver=blog_post.author, is_active=True, blog_post=blog_post) readonly = False if interest_requests.exists() and request.method=="POST": # This is where you could view the submitted form return HttpResponse('You have already submitted your interest to this post.') elif interest_requests.exists(): form = SubmitInterestForm(instance=interest_requests.first()) readonly=True if request.method == 'POST': # use request.method == 'POST' to submit POST request (like submitting a form) form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) author = Account.objects.get(email=user.email) # use 'author = user.account' if there is OneToOne relation between user and account obj.author = author obj.blog_post = blog_post #interest_request = Interest.objects.get(interestsender=Account.user, interestreceiver=blog_post.author, is_active=True) #obj.interestsender=user #obj.interestreceiver=blog_post.author obj.interestsender = … -
Django Channels group send only sends the message to last channel
I'm working on django channels-3.0.3, the group_send only sends my message to the last connected channel to the connected users times. settings ... INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "chat", "channels", ] ASGI_APPLICATION = "cfehome.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } chat/consumers.py import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): @database_sync_to_async def get_thread(self, user, other_username): return Thread.objects.get_or_new(user, other_username)[0] async def websocket_connect(self, event): other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] # print("connect!") # print(me, other_user) thread_obj = await self.get_thread(me, other_user) # print(me, thread_obj) chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) print(f"{self.channel_name}, {self.chat_room}, {me} - connected!") await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("msg recevied!", event) front_text = event.get("text", None) if front_text is not None: loaded_dic_Data = json.loads(front_text) msg = loaded_dic_Data.get("message") # print(msg) user = self.scope['user'] username = "default" if user.is_authenticated: username = user.username myResponse = { "message": msg, "username": username } # brodcast msg to chatroom await self.channel_layer.group_send( self.chat_room, { "type": "chat_message", "text": json.dumps(myResponse), } ) # sends the actual msg async def chat_message(self, event): await self.send({ "type": "websocket.send", … -
how i can set verbose name from pip module?
i using django-defender (pip install django-defender).this module contain "Access attempts" model. but it installed in virtuelenv.how i can to set verbose name to this models. -
django No module named 'project.settings' in separate directory(vscode)
Django version: 3.1.3 Python version: 3.8 My Project tree:\ Project: project settings.py mydirect(not app, a set of tool functions which called by my apps) myfunc.py my apps The django config in myfunc.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if BASE_DIR not in sys.path: sys.path.append(BASE_DIR) os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'project.settings') django.setup() My problem is that when I execute myfunc.py in vscode, it gives errors below: Traceback (most recent call last): File "d:/Desktop/project-dev/venv_idc_ops/dms/common/common.py", line 12, in <module> django.setup() File "D:\Desktop\project-dev\venv_idc_ops\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "D:\Desktop\project-dev\venv_idc_ops\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "D:\Desktop\project-dev\venv_idc_ops\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "D:\Desktop\project-dev\venv_idc_ops\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\program files\python36\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project.settings' But when I run runserver, everything just goes well. That means that if I want to test myfunc.py, I must test it through the api instead of just executing 'run' in vscode Does anybody know what the problem is? It has confused my for a long time -
How do I fix my test case for a view in DRF?
I'm trying to write tests for my new app and this is the first time I try to so I'm running into many errors. This is my view: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend #lists, creates and filters tasks class ListTask(generics.ListCreateAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['date'] search_fields = ['description'] #allows to see detail of a task class DetailTask(generics.RetrieveUpdateDestroyAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer I took a model from many tutorials to test that view and ended up with a very faulty code that looks like this: from django.test import TestCase from django.urls import reverse from rest_framework.test import APIRequestFactory from todo.views import ListTask, DetailTask class ListTaskViewTest(TestCase): def setUp(self): self.data = {'title':'Any title', 'description': 'Any description', 'Completed':False, 'date':'Any date'} self.factory = APIRequestFactory() def create_task(self, title='Read'): return Task.objects.create(title=title) def test_list_task(self, title='Read'): list_url = reverse('tasks-api:list') obj = self.create_task() request = self.factory.get(list_url) response = ListTaskAPIView.as_view()(request) self.assertEqual(response.status_code,200) class DetailTaskTest(TestCase): def setUp(self): self.data = {'title':'Any title', 'description': 'Any description', 'Completed':False, 'date':'Any date'} self.factory = APIRequestFactory() def test_retrieve_task(self): detail_url = reverse('tasks-api:detail', kwargs={'slug':obj.slug}) request = self.factory.get(detail_url) response = DetailTaskAPIView.as_view()(request, slug=obj.slug) self.assertEqual(response.status_code, 200) def test_update_task(self): obj = self.retrieve_task() update_url = … -
Django Multiple Form Processing in same View
I am looking for some assistance in two areas for django forms processing. I have a class view that overrides post and checks the name of the form in request.POST to determine which form has been submitted. based on the form submitted, I perform the appropriate actions for that form and save to the model. That part works correctly. I am not using a model form, just a custom html form created in the template with input fields. See the below view and html for reference. Is this the correct way to handle this or is there a best practice I should be following that makes use of model forms? Code seems a bit heavy to me and non-standardized, like there should be a better way... Being that I am not using model forms, the error processing has me a little confused. How do you handle error processing on a normal html form that does not make use of django model forms? See below in the view where notated # ERROR HANDLING FOR FORM NEEDED in code, specifically on the username field which is unique and validated on the model level. views.py class ProfileView(View): def get(self, request, *args, **kwargs): if … -
Django/Python: Filter for objects with two foreign keys and two attributes
get_messages returns messages shared between two users. def get_messages(self, sender, recipient): messages = Message.\ objects.\ filter(sender_id=sender.id, recipient_id=recipient.id) return messages This works fine, but sometimes User A will be the recipient instead of the sender or User B will the sender instead of the recipient. How can I use filter both ways more eloquently (without calling this function twice with the parameters switched)? -
can anyone find errors why the form fields is not showing in model from in djanog
Can anyone tell me why in my home page the for is not showing ,the model form to signup user , i make it using django UserCreationForm but home page it is not showing my views.py file def signup(request): if not request.user.is_authenticated: fm=signUpForm() if request.method == 'POST': fm = signUpForm(request.POST) if fm.is_valid(): fm.save() return redirect('home.html') else: fm = signUpForm() return render(request,"home.html" ,{'signupforms':fm}) home.html here i just use bootstrap model and display form to signup use using model in <div class="modal fade modelform" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center "> <h5 class="modal-title text-dark" id="exampleModalLabel">Login using your credentials </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action ='' method ='POST' > {% csrf_token %} <form action = '' method ='POST' novalidate > {% csrf_token %} {% for fm in signupforms %} <div class="form-group mt-0"> {{fm.label_tag}} {{fm}} <small class = 'text-danger'>{{fm.errors|striptags}}</small><br></div> {% endfor %} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input class="btn btn-primary my-3" type="submit" value="Submit"> </div> </form> </div> </div> </div> </div> forms.py where i create form and passing it to display from .models import loginForm from django.contrib.auth.forms import UserCreationForm # AuthenticationForm ,UsernameField create default form from django.contrib.auth.models import User … -
could not translate host name to "db" to address: Unknown host
I'm attempting to follow the guide provided by: https://docs.docker.com/compose/django/ Whenever I attempt to makemigrations, it gives me the Unknown host error given in the title. I'm trying to use PostgreSQL with Django and Wagtail as its CMS My docker-compose.yml looks like: version: "3.9" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db and my settings in the settings.py file look like: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Am I missing anything? -
Django MYSQL Lite
I am trying to learn to write a program where i need to try and find the distance between 2 points using Django with MYSQL Lite. I have tried previous ones posted on this website, however, cannot find anything that works. Currently, my HTML is set up where a user would enter the postcode (Calendar.postcode), and i need it to measure the distance from a set point. Currently, i have a file with all postcodes and longitudes and latitudes like below: GB AL3 8QE Slip End England ENG Bedfordshire Central Bedfordshire E06000056 51.8479 -0.4474 6 GB AL5 3NG Harpenden England ENG Bedfordshire Central Bedfordshire E06000056 51.8321 -0.3829 6 GB AL5 3NS Hyde England ENG Bedfordshire Central Bedfordshire E06000056 51.8333 -0.3766 6 I would like the output to be on the main part of the website (rota.html) e.g. Distance is X miles/KM please can someone show me how this would be coded? thanks -
Django MariaDB-Galera Perfermance on K8s
I'm currently trying to find a good database solution for my app that runs on K8s at a "massive scale". So I started to experiment with MariaDB Galera without having any further experiences with it. I noticed that the write performance is quite slow. On a single instance MariaDB I can write 500 rows each with 7 field in about 2,75 Seconds (Single Table). Using Galera I need about 12-15 seconds for the same insert. Sometimes even more than 20 sec. Why that? Im running on High-End Hardware with NVMe drives, 10 Gbit Network and Epyc CPUs. Overhead should be small as everything run in Containers. Is this "issue" just the nature of Galera or is my config just faulty?! please see here: https://pastebin.com/mvb3Ndww I already experimented with query_cache_type and query_cache_size but without any real success so far ... My CSI is openebs-hostpath for maximum performance through a locally attached disk for each container/Pod. Thanks in advance -
Django | formfield_for_manytomany - name display in admin
I am just learning Django, please forgive any ignorance here. Here's my models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) admin = models.BooleanField("Admin Status") class Team(models.Model): name = models.CharField("Team Name", max_length=20, default="") admins = models.ManyToManyField(User, related_name="admins") members = models.ManyToManyField(User, related_name="members") Here's my admin.py from django.contrib import admin from .models import Team, Profile from django.contrib.auth.models import User class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'admin') admin.site.register(Profile, ProfileAdmin) class TeamAdmin(admin.ModelAdmin): list_display = ('name',) def formfield_for_manytomany(self, db_field, request, **kwargs): print(db_field) if db_field.name == "admins": kwargs["queryset"] = Profile.objects.filter(admin=True) return super(TeamAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Team, TeamAdmin) This works perfect, but the admins on my admin page are showing as "Profile object (1)," "Profile object (2)," etc... What am I doing wrong? Or where do I change the way those display? -
How to save state from button input in Django?
I want to have an option to turn on or off certain features using buttons. If the button is clicked = True, enable some option to be visible, if clicked again disable it. I want to have multiple buttons in the same form, but getting it to work with one should be sufficient in order for me to continue. The problem is that if I check it to true and save it, after going to another page the state is lost and reverts back to default. models from django.db import models class Settings(models.Model): enable_name = models.BooleanField() forms from django import forms from . import models class SettingsForm(forms.ModelForm): class Meta: model = models.Settings fields = ["enable_name"] views def settings(request): if request.method == 'POST': form = SettingsForm(request.POST) if form.is_valid(): form.save() return render(request, 'settings.html', {'form': form}) else: form = SettingsForm() return render(request, 'settings.html', {'form': form}) HTML {% block content %} <div class="main"> <form action="{% url 'settings' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="save"> </form> </div> {% endblock %} -
Is it possible to return api response instead of model/database in rest framework?
I am proudly say that i am completely newbie. I am trying to understand rest framework model-view relations. But, i have a question which is i couldn't find answer in docs. I want to show some datas from outsources not my database. For example: Receive a post parameters --> SEND ANOTHER POST REQUEST TO ANOTHER SERVER --> RECEIVE RESPONSE and Return Json Response to client/visitor. All of trainings for models and showing items from database but what about if i want to show some data from another sources. Thank you in advance. I will be appreciated if you can share some documentations with me. -
Accessing javascript variables within Django HTML
I'm adding data to include in a form in Chart.js in Django. I originally had: home_data.push({x: "{{transaction.transaction_time.month}}/{{transaction.transaction_time.day}} {{transaction.transaction_time.hour}}:{{transaction.transaction_time.minute}}", y: {{transaction.price}}}) But now what I'm trying to do is adjust the transaction.transaction_time value in order to do this I want to assign it to a separate variable to later get the value of that variable. Here's what I tried doing: var transaction_adjusted = {{transaction.transaction_time}} home_data.push({x: "{{transaction_adjusted.month}}/{{transaction_adjusted.day}} {{transaction_adjusted.hour}}:{{transaction_adjusted.minute}}", y: {{transaction.price}}}) In my console window: I see that the values evaluated such as {{transaction_adjusted.month}} evaluate to nothing. Why is this? -
Can we make two static folders or more and define their roots in STATICFILES_DIRS in django?
Well my question is quite straight forward. Can we have more than one static folders in django project. In case I want to put static files and templates files in each django app dir separately. Is it possible ?. Right now my each app has its template file but the static file is one for all. I want to make that just like template approach. Can i do that. Do i have to define path of each static folder inside my STATICFILES_DIR in settings.py e.g: STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', 'myapp_1/static/', 'myapp_2/static/' ] -
Django - how to make OR query for unknown number of values
I'm working on small app where user passes list of cities in GET request. I need to fetch all data where given city exists. My current solution works but I'm looking for something more efficient. Currently I'm creating separate array and adding following querySets in loop. Is there a way to make it within one query ? I also thought about raw query but I'm not sure if it is recommended. def get(self, request): search_phrase = request.GET["search"] cities = request.GET["city"].split(",") found_results = [] for city in cities: found_results += Job.objects.filter(position__icontains=search_phrase, city=city) return render(request, "search.html", {"results":found_results}) -
Many to Many - Django - Related Fields
Let's say I have a Django project with a model called "Genres" and another model called "Books." from django.db import models class Genres(models.Model): name = models.CharField(max_length=15) class Books(models.Model): name = models.CharField(max_length=50) genres = models.ManyToManyField(Genres) Setting it up this way, I am able to access a book in my Admin page and view all the genres associated with it. I can also add and remove genres from a book there. Is there a way I can set this up so that I can ALSO open a genre in my admin page and view all the books that fall under that genre, also being able to add and remove books. I want to be able to update what books fall under a genre on the genre itself and have it ALSO update the genres on the books affected. I hope that makes some sense. -
Prevent Importing Duplicate Records In Django Admin Interface
I am trying to prevent importing duplicate records in the Django admin interface. I did this my adding this to my models class ScanData(models.Model): field1 = models.CharField(max_length=30, null=True) field2 = models.CharField(max_length=30, null=True) field3 = models.CharField(max_length=30, null=True) field4 = models.CharField(max_length=35, null=False) field5 = models.CharField(max_length=150, null=True) field6 = models.CharField(max_length=150, null=True) field7 = models.CharField(max_length=150, null=True) field8 = models.CharField(max_length=200, null=True) field9 = models.CharField(max_length=150, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['field3', 'field5', 'field7'], name='uniqueUploadsOnly') ] However, when I go to the Django admin interface, I can easily import as many duplicates as I want :( What else can I try without much grief? Django is already adding the id primary key, and I have no other single unique field. -
class based views -TypeError: super(type, obj): obj must be an instance or subtype of type
I am building an app in Django, it uses class based views. In my views.py I have this class based view that allows to inspect details of objects in my model Product: class ProductDetailView(DetailView): queryset = Product.objects.all() template_name = "products/detail.html" def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) return context As I try to run the server I get this traceback: Traceback (most recent call last): ... context = super(ProductListView, self).get_context_data(*args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type What is the problem?