Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx Gives 502 Error but config should be correct; Please I need advise on how to debug the issue?
I have a CentOS 8 (fedora) server running and I'm trying to run my Django Webapp on it through Nginx It runs on port 8000, and I want to access it on my browser through nginx (so port 80?) These commands on the server itself This shows my webapp HTML page fine curl http://127.0.0.1:8000 curl http://0.0.0.0:8000 but these show me the Nginx 502 Bad Gateway page curl http://0.0.0.0 curl http://127.0.0.1 No errors in the nginx log files This is my nginx.config: events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; server_tokens off; server { listen 80; server_name $hostname; # I tried this with an '_' also no help location / { proxy_pass http://0.0.0.0:8000; # also tried with 127.0.0.1 proxy_set_header Host $host; } } } Running nginx -T shows the config has been loaded Any advise on what to look for? (perhaps my firewall is blocking it somehow? idk) Kind regards I'm trying to get my webpage working through Nginx -
Django Admin inline-editable like Flask admin?
Flask Admin has this really nice inline-editable option. Is there something similar in Django-Admin? Yes, there is "list_editable". Unfortunately, this is poor usability and I much more prefere the flask-Admin approach: editable fields are underlined Click -> popup opens where you can edit Save -> save via Ajax -
Django ValueError: Cannot serialize: <User: username>
When I'm trying to make migrations of my models in Django, I keep getting the same error, even after I've commented out all the changes: (.venv) C:\Users\jezdo\venv\chat\chat_proj>python manage.py makemigrations chat Migrations for 'chat': chat\migrations\0002_alter_customusergroup_custom_group_name_and_more.py - Alter field custom_group_name on customusergroup - Alter field users on customusergroup Traceback (most recent call last): File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 22, in <module> main() File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 239, in handle self.write_migration_files(changes) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 278, in write_migration_files migration_string = writer.as_string() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize _write(arg_name, arg_value) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 63, in _write arg_string, arg_imports = MigrationWriter.serialize(_arg_value) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 282, in serialize return serializer_factory(value).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 221, in serialize return self.serialize_deconstructed(path, args, kwargs) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 99, in serialize_deconstructed arg_string, arg_imports = serializer_factory(arg).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize item_string, item_imports = serializer_factory(item).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize item_string, item_imports = serializer_factory(item).serialize() File … -
Django - images upload in wrong folder
Making some kind of blog website and can't make homepage to show article images... Images should be uploaded to media/profile_pics , but it just makes profile_pics folder in app folder and uploads images there. my models.py : class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") #author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = models.ImageField(upload_to="profile_pics", blank=True, null=True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="blog_posts") def total_likes(self): return self.likes.count() def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") my views.py: class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' my forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag', 'body', 'image') widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}), 'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}), 'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}), } my home.html <div class="row"> {% for post in object_list %} <div class="col-lg-4 my-4"> <div class="card shadow" style="width: 20rem; height: 33rem;"> <img src="/media/{{post.image}}" class="card-img-top" alt="..." height="250px"> <div class="card-body"> <h5 class="card-title">{{post.title}} <br><small>by {{ post.author.first_name }} {{ post.author.last_name }}</small></h5> <p class="card-text">{{post.body|slice:":100"|safe}}</p> <a href={% url 'article-details' post.pk %} class="btn btn-primary">Read More {% if user.is_superuser %}<a href="delete_blog_post/{{post.slug}}/" class="btn btn-danger mx-4">Delete Blog</a>{% … -
Django crispy forms language settings
I am a beginner at web application development using django framework. I am creating a crispy form to update the user information and upload an image. The html file contains two forms, one for updating the information and second for uploading the image. While the rest of the form language setting is us-en, only the button and text next to the upload button are seen in german language. The settings.py file has the chosen language code as 'en-us'. In the model.py file the forms are defined like below: The forms are then used in the html file: But the webpage shows the following: could anyone please help me understand, what is making only the upload button language change to german and how could I possibly fix it? Thank you :) already tried: checking the language code in the settings.py file -
I am trying to call "sqlite db.sqlite" in my django project but i found the error mentiod below
`sqlite : The term 'sqlite' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 sqlite db.sqlite3 + CategoryInfo : ObjectNotFound: (sqlite:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ~~~~~~` When I try to run this in the cmd it wrok fine the error is in visual studio terminal I have also installed sqlite viewer -
How to pass InMemoryUploadedFile as a file?
User records audio, audio gets saved into audio Blob and sent to backend. I want to get the audio file and send it to openai whisper API. files = request.FILES.get('audio') audio = whisper.load_audio(files) I've tried different ways to send the audio file but none of it seemed to work and I don't understand how it should be sent. I would prefer not to save the file. I want user recorded audio sent to whisper API from backend. -
duplicate key value violates unique constraint error in Django
I have a model named package in an app named exam. I use Django rest framework and have the following View: class PackageListCreaet(ListCreateAPIView): queryset = Package.objects.all() serializer_class = PackageSerializer permission_classes = (IsAdminAndReadOnlyForStaff,) @method_decorator(rest_error_decorator(logger)) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) and the following serializer: class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = ('pk','name','price','exams','active') when I try creating a new package from Django admin it works just fine. But when I try creating a new package using the API above it throws the following error: duplicate key value violates unique constraint \"exam_package_pkey\"\nDETAIL: Key (id)=(1) already exists I looked around a bit to find a solution and realized the problem is that the id field of exam_package table is out of sync. I tried syncing it like this and it didn't work. Then I tried removing all records (which happened with no error) and setting the primary key to 1 like this. And it still doesn't work. I looked into this link and realized maybe my probmlem is the same and maybe DRF is creating two new instances which is why I get the error. But I have no idea how to fix it. -
How I'm be able to query a multiple data in single model?
How do I able to query if have three Car Models Car A, Car B andCar C and I wanted to switch this position base on their ordering? How do I able to perform that and what class based view should I use or just a function-based view? Original DB : Car A --> Car B --> Car C Alter DB : Car C --> Car B --> Car A class CarColor(models.Model): colors = models.CharField(max_length=50) def __str__(self) -> str: return self.colors class Car(models.Model): car_name = models.CharField(max_length=50) car_model = models.CharField(max_length=200) car_description = models.TextField(max_length=200) car_color = models.ForeignKey(CarColor, on_delete=models.CASCADE) car_image = models.ImageField(null=True, blank=True, upload_to='media', default='imageholder.png') date_manufactured = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): """ After creating or updating a Car, this function will be triggered and redirection using reverse""" return reverse("car_detail", kwargs={"pk": self.pk}) class Meta: ordering = ['date_manufactured'] def __str__(self): return f'{self.car_name}' -
Django tests AssertionError for update view
I tried to create Django test for UpdateView but I have such problem as: self.assertEqual(application.credit_purpose, 'House Loan') AssertionError: 'Car Loan' != 'House Loan' Car Loan House Loa def test_application_update(self): application = Application.objects.create(customer=self.customer, credit_amount=10000, credit_term=12, credit_purpose='Car Loan', credit_pledge=self.pledge, product=self.product, number_request=2, date_posted='2020-01-01', reason='None', repayment_source=self.repayment, possible_payment=1000, date_refuse='2020-01-02', protokol_number='123457', status=self.status, language=0, day_of_payment=1, credit_user=self.user) response = self.client.post( reverse('application_update', kwargs={'pk': application.id}), {'credit_purpose': 'House Loan'}) self.assertEqual(response.status_code, 200) def test_application_update(self): application = Application.objects.create(customer=self.customer, credit_amount=10000, credit_term=12, credit_purpose='Car Loan', credit_pledge=self.pledge, product=self.product, number_request=2, date_posted='2020-01-01', reason='None', repayment_source=self.repayment, possible_payment=1000, date_refuse='2020-01-02', protokol_number='123457', status=self.status, language=0, day_of_payment=1, credit_user=self.user) response = self.client.post( reverse('application_update', kwargs={'pk': application.id}), {'credit_purpose': 'House Loan'}) self.assertEqual(response.status_code, 200) self.assertEqual(application.credit_purpose, 'House Loan') -
Templates are not found in django deployed project
I have got a Django Project. It runs perfectly using "python2 manage.py runserver". I have deployed the project in a server and I get "Template not found" error. I have changed the path in views file for the main page and now it works, but I have got two new issues: I have got an {% include "/lateral/menu.html" %} line that does not work in main.html All the href in buttons that redirect the user to other html files do not work either. I think it has something to do with the paths, how should I added them in order to be relative path? My structure: -APP1 -APP2 -WEB ---manage.py ---TEMPLATES ------main.html ------logout.html ------loging.html ------LATERAL ---------menu.html Some lines of my views file in order to check how I add the paths: def loging(request): # Función vista return render(request, "loging.html") I have tried changing to some variations of the paths and with absolute paths too without success. All was working perfectly locally. -
when i submit my form My Comment form dosen't save in database
I create a 5 star rating system using django with javascript and i want to user comment like this: i want to click on the stars and then return the value that is an integer this is my models: class Review(models.Model): course = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='reviews') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) rating = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)]) comment = models.TextField() created = models.DateField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name} my views: @csrf_exempt def productDetailView(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) new_comment = None if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.course = product new_comment.rating = request.POST['rating'] new_comment.save() else: form = ReviewForm() return render(request, 'shop/product_detail.html', {'product': product, 'form': form}) js function: $(document).ready(function(){ $('.rate .rate-item').on('click', function(){ var value = $(this).data('value'); $.ajax({ url: '{{ product.get_absolute_url }}', type: 'POST', data: {'rating': value}, success: function(response){ alert('Rating saved successfully!'); } }); }); }); and my template: <form method="post"> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Fast name" }} </div> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Last Name"}} </div> <div class="rate-label">Your Rating:</div> <div class="rate"> <div data-value="1" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="2" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="3" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="4" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="5" class="rate-item"><i class="fa fa-star" … -
How to delete File Field and File(in project root) in django?
I want to delete the data inside the file field and the file uploaded through the file field. I'm beginner. models.py class Fruits(Signable): name = models.CharField( _('Name'), max_length=200, ) description = models.TextField( _('Description'), null=True, blank=True, ) this_is_my_file = models.FileField( _('Photo image'), null=True, blank=True, upload_to='myfile/' ) def __str__(self): return self.name def delete(self, *args, **kwargs): if self.this_is_my_file: self.this_is_my_file.delete() super().delete(*args, **kwargs) Like the code above, I added 'def delete' to the existing model as shown above through search. But I don't know how to use this function. How do I use this in view and template? My part of view is below. views/fruits.py class FruitsDetailView(LoginRequiredMixin, DetailView): template_name = 'frutis/detail.html' login_url = 'login' model = MyObjects def get_context_data(self, **kwargs): pk = self.object.pk context = super().get_context_data(**kwargs) ... return context How do I execute the delete function in this view? I want to delete it when I press the 'delete' button on the template. Should I send a post request from template and receive it from view? I've been thinking about it for 4 days, but I don't know what to do. -
Single model instances on separate html
What is a best way to display single model instances on different html? I know how it is done on single page (forloop), but could not figure out how the same would be possible on different html. i.e. single question per page? my pseudo model: class Question(models.Model): desc = models.CharField() -
Remote DRF Auth and handle payload with JWT
I have auth_service, tpm_api and frontend enviroments. All services use the same secret_key. My users and permissions are on the auth_service. I am using jwt_simple for Authentication on auth_service. On the frontend service, I get token from auth_service with username and password. I am sending requests to endpoints in my tpm_api service with this token. I'm parsing the response and displaying it in my frontend service. So far, no problem. However, I am not getting the token.payload data within the tpm_api service. I added REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), } in settings.py. When I send request to tpm_api service, under self.request.authenticators there is <rest_framework.authentication.BasicAuthentication object 0x000001668986C430> and <rest_framework.authentication.SessionAuthentication object at 0x000001668986C6A0>. I need <rest_framework_simplejwt.authentication.JWTAuthentication object at 0x000001FFDCD23790>. I don't have user model anywhere except auth_service. ##### auth_service model.py ##### from django.db import models from django.contrib.auth.models import AbstractUser perm_parent_choices = [ ("app", "app"), ("factory", "factory"), ("department", "department"), ("role", "role"), ] class User(AbstractUser): perms = models.ManyToManyField("login.Perm", related_name="user_perms", blank=True) gsm = models.CharField(max_length=15, null=True) class Perm(models.Model): parent = models.CharField(max_length=50, choices=perm_parent_choices, null=True) name = models.CharField(max_length=50) short_code = models.CharField(max_length=5) def __str__(self): return self.short_code ##### auth_service views.py ##### class UserViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserSerializer queryset = models.User.objects.all() def list(self, request, *args, **kwargs): ############################## from rest_framework_simplejwt.authentication import … -
Django FileSystemStorage does not save anything to media folder
I'm working on a Django backend deployed on a server, here's my settings: DEBUG = False STATIC_URL = "/staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") And I want to save the users' images outside the django folder, so I've created a custom FileSystemStorage in this way: from django.core.files.storage import FileSystemStorage key_store = FileSystemStorage(location="/home/usr/project/media/", base_url="/media") Where I put the absolute path of ubuntu server. def profile_picture_url(instance, *_): return f"{instance.user.uuid}/profile.picture.png" picture = models.FileField( storage=key_store, default=None, upload_to=profile_picture_url ) But it doesn't create any file inside media folder. Any solution? -
Adding image for blog posts
Coding some kind of blog with django, and I can't make homepage to contain images of the articles... It just doesn't upload a image... my Views.py : class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' my Models.py: class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") #author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = models.ImageField(upload_to="profile_pics", blank=True, null=True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="blog_posts") def total_likes(self): return self.likes.count() def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") My Forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag', 'body', 'image') widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}), 'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}), 'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}), } and my add_post.html : {% extends 'base.html' %} {% block title %}Make an article{% endblock %} {% block content %} {% if user.is_authenticated %} <h1>Make an article</h1> <div class="form-group"> <form method="POST"> <br/> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button class="btn btn-dark">POST</button> </div> {% else %} <h1>You are not allowed to post! You need to <a href="{% url 'login' %}">Log in</a> or <a href="{% … -
Rest api detail User Not Found code user not found Error postman
i am generating a token for each logged in user. But on Get request through postman i am getting this error. please guide me what's wrong ! postman error screenshot my models.py class allmodelfields(AbstractBaseUser): USERNAME_FIELD = 'email' #id_no = models.BigAutoField(primary_key=True,serialize=False,verbose_name="ID",) email = models.EmailField(verbose_name='Email',max_length=255,unique=True,) password = models.CharField(max_length=255) confirm_password = models.CharField(max_length=255) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30,blank = True) last_name = models.CharField(max_length=30,blank = True) number_code = models.CharField(max_length=10) phone_no= models.CharField(max_length=10) pincode = models.CharField(max_length=10) house_no = models.CharField(max_length=50) street = models.CharField(max_length=50,blank = True) locality = models.CharField(max_length=50,blank = True) state = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) ip = models.CharField(blank = True,max_length = 20) # auto filled fields full_name = models.CharField(max_length=100,)#default = first_name + middle_name + last_name) full_number = models.CharField(max_length = 23)#f'{number_code} {phone_no}' created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) is_ active = models.BooleanField(default=False) unique_id = models.CharField(max_length = 10, editable=False) def __str__(self): return self.email def full_name_func(self): return f'{self.first_name} {self.middle_name} {self.last_name}' def full_number_func(self): return f'{self.number_code}|{self.phone_no}' class Meta: abstract = True class Customer(allmodelfields): account_type = models.CharField(max_length=20,choices=customer_account_choices,default=" ") class Dealer(allmodelfields): account_type = models.CharField(max_length=20,choices= dealer_account_choices,default=" ") serializers.py class customerprofileserializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['id','full_name','email','unique_id','full_number'] class dealerprofileserializer(serializers.ModelSerializer): class Meta: model = Dealer fields = ['id','full_name','email','unique_id','full_number'] urls.py path("customerprofileview/", customerprofileview.as_view(),name='customerprofileview'), path("dealerprofileview/", dealerprofileview.as_view(),name='dealerprofileview'), views.py class customerloginview(APIView): renderer_classes = [apirenderer] def post(self,request,format=None): … -
Django Rest api Update View form can't update single attribute
I have created an Employee CRUD in Django REST using generic views. when update view page is loaded I couldn't find the current values in the fields. so I can't update a single value. when i update a single value it shows other fields must be required. I need to update a single value. eg: Phonenumber How can i do that? class EmpUpdateView(UpdateAPIView): queryset = Employee.objects.all() serializer_class = EmpModelSerializer lookup_field = 'id' [enter image description here](https://i.stack.imgur.com/7Slum.png) enter image description here -
session expires while switching to another app.route in flask
Session expires when the '/mobile-confirmation' app.route runs and the user redirects to login page @app.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "POST": #SignUp form Insert codes ...... db.execute("SELECT tempcode FROM users WHERE id = %s", [userID]) tmpcode = db.fetchall() sms_soap.send_by_base_number([tmpcode[0][0]], phonenum[0][0], 999999) executor.submit(tempcodecountdown, username) session["user_id"] = userID return redirect("/mobile-confirmation") else: return render_template("signup.html") @app.route("/mobile-confirmation", methods=["GET", "POST"]) @login_required def confirmmobile(): user_id = session["user_id"] if request.method == "POST": enteredcode = request.form.get("tempcode") db.execute("SELECT tempcode FROM users WHERE id = %s", [user_id]) tmpcode = db.fetchall() if enteredcode == tmpcode[0][0]: db.execute("UPDATE users SET activation = %s WHERE id = %s", ['yes', user_id]) mydb.commit() return redirect('/dashboard') else: return render_template("mobileconfirmation.html") and these are session settings @app.after_request def after_request(response): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response app.config["SESSION_FILE_DIR"] = mkdtemp() app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" app.config["TEMPLATES_AUTO_RELOAD"] = True app.config['SESSION_COOKIE_SAMESITE'] = "None" app.config['SESSION_COOKIE_SECURE'] = True it was working correctly in another ide but now I have this problem on cpanel -
Django - how to retrieve data from two models (at the same time) related with OneToOne relation?
In Django I have two models: class Car(models.Model): model_name = CharField(...) make_name = CharField(...) car_exterior_color= = CharField( CHOICES ) class CarWash(models.Model): car_washed = BooleanField(...) wash_date = DateTimeField(...) added_wax = BooleanField(...) car = models.OneToOneField(Car, on_delete=models.CASCADE, verbose_name="Car washed") I need to show such table in view, that retrieves data from two models: model_name make_name car_ext_col car_washed ? added_wax ? wash date IS Lexus blue Yes No 2023-02-02 G37 Infiniti white No No -- RX Lexus red Yes No 2023-02-02 Corolla Toyota green No No -- Tundra Toyota blue Yes Yes 2023-02-02 Q70 Infiniti yellow Yes Yes 2023-02-03 Civic Honda black Yes No 2023-02-03 Malibu Chevrolet red Yes Yes 2023-02-04 GS Lexus yellow Yes No 2023-02-04 Q30 Infiniti white No No -- What should I write in views.py? How to retrieve data from two models to get table as above? -
hi, i want add search bar to myproject but don't return anything
this view for search: class Search(generic.ListView): model = Blog template_name = 'pages/blog_list_view.html' context_object_name = 'blog' def get_queryset(self): search = self.request.GET.get("q") search_result = Blog.objects.filter( Q(title__icontains=search) | Q(description__icontains=search) | Q(active=True)) return search_result search form in _base.html <form action="{% url 'search' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> my model class Blog(models.Model): title = models.CharField(max_length=100) cover = models.ImageField(upload_to='blog_cover/') description = models.CharField(max_length=200) text = models.TextField() author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) active = models.BooleanField(default=False) date_create = models.DateField(auto_now_add=True) date_modified = models.DateField(auto_now=True) def __str__(self): return f'{self.title} : {self.author}' def get_absolute_url(self): return reverse('blog_detail', args=[self.id]) tip: "I use Persian language for search" I tried __icontains and __contains but result was same -
Writing a tuple search with Django ORM
I'm trying to write a search based on tuples with the Django ORM syntax. The final sql statement should look something like: SELECT * FROM mytable WHERE (field_a,field_b) IN ((1,2),(3,4)); I know I can achieve this in django using the extra keyword: MyModel.objects.extra( where=["(field_a, field_b) IN %s"], params=[((1,2),(3,4))] ) but the "extra" keyword will be deprecated at some point in django so I'd like a pure ORM/django solution. Searching the web, I found https://code.djangoproject.com/ticket/33015 and the comment from Simon Charette, something like the snippet below could be OK, but I can't get it to work. from django.db.models import Func, lookups class ExpressionTuple(Func): template = '(%(expressions)s)' arg_joiner = "," MyModel.objects.filter(lookups.In( ExpressionTuple('field_a', 'field_b'), ((1,2),(3,4)), )) I'm using Django 3.2 but I don't expect Django 4.x to do a big difference here. My db backend is posgresql in case it matters. -
Can i make an stackedInline connnection between two model without having any connection between them ? in Django
class Item(models.Model): name=models.CharField(max_length=250) description = model.TextField() class Photo(models.Model): item = models.ForiegnKey(Item) title=models.ChaField(max_length=250) here is admin.py class PhotoInline(admin.StackedInline): model = Photo class ItemAdmin(admin.ModelAdmin): inlines = [PhotoInline] admin.site.register(Item,strong text ItemAdmin) admin.site.register(Photo) i want to have an inline connection between without them having any relationship -
(Django model) How does this Message model works?
So I am following a Youtube video on how to create a chatting app. Then it build a model that I don't understand. Here's the Message model I came across and can't understand how it works. class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') body = models.TextField() date = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def send_message(from_user, to_user, body): sender_message = Message(user=from_user, sender=from_user, recipient=to_user, body=body, is_read=True) sender_message.save() recipient_message = Message(user=to_user, sender=from_user, recipient=from_user, body=body, is_read=True) recipient_message.save() return sender_message def get_message(user): users = [] messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last') # filter by user=the login user, recipient=the sender, the lastest message from each sender, order the lastest message by sender using time for message in messages: users.append({ 'user': User.objects.get(pk=message['recipient']), 'last': message['last'], 'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count(), }) return users I understand the different fields of the Message model but I fail to understand why it create two instances of the message model in the send_message() function. One for sender message and another for recipient message. recipient_message = Message(user=to_user, sender=from_user, recipient=from_user, body=body, is_read=True) Then for the recipient_message I'm not clear why the recipient field is set to from_user instead of to_user?? Could anyone please help me with this? I am …