Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there a way to display a particular inline in a new page based on a condition?
I need to display only one inline in a new page based on the condition like if the url has the parameter country_id then i need to display only one inline. Since I cannot make it in one ModelAdmin since the model admin has form validations in it, I used two modelAdmins for the same model. I have a readonly field called get_countries in CorporateConfig(admin which has form validations) and it will display a list of countries. If i click on a country based on that country id i need to display CorporateBrand which is an inline model to CorporateConfig on a new page(remember only that inline needs to be displayed). class CorporateConfigurationAdmin(admin.ModelAdmin): form = CorporateConfigurationAdminForm inlines = [CorporateIncludeBrandAdmin, CorporateExcludeBrandAdmin, CorporateBrandsAdmin] def get_urls(self): from django.urls import path urls = super(CorporateConfigurationAdmin,self).get_urls() filter_url = [ path('filter_brand/',self.admin_site.admin_view(self.brand_filter), name='brand-filter'), ] return filter_url + urls def brand_filter(self, request, obj=None): pass def get_countries(self, instance): country_list = '<ul style="font-weight: bold;list-style-type:circle;">' countries = Country.objects.all() print("countries", countries) for country in countries: url = reverse_lazy('admin:brand-filter') print("urls is",url) country_list += '<li class="changelist"><a href="{url}?country_id={id}" target="_blank">{country}</a></li>'.format(url=url, country=country.name,id=country.id) country_list+='</ul>' return mark_safe(country_list) get_countries.short_description = 'Country Url' Clicking on the link above should go to the custom url which is created by get_urls() class BrandOrderFilter(CorporateConfiguration): class … -
Django: Could not found exception in Traceback
I have facing some issue with python requests in a Django project. It only occur in 2nd requests.post(). Although It exited with exception TypeError: getresponse() got an unexpected keyword argument 'buffering'. But after updating urllib3. There is no exception in traceback. Traceback (most recent call last): File "/home/ubuntu/projects/project/api/views/a_view.py", line 765, in create_power_trace headers=power_trace_headers) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/api.py", line 117, in post return request('post', url, data=data, json=json, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/sessions.py", line 542, in request resp = self.send(prep, **send_kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/sessions.py", line 655, in send r = adapter.send(request, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/adapters.py", line 449, in send timeout=timeout File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 677, in urlopen chunked=chunked, File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 426, in _make_request six.raise_from(e, None) File "<string>", line 3, in raise_from File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 421, in _make_request httplib_response = conn.getresponse() File "/usr/local/lib/python3.7/http/client.py", line 1373, in getresponse response.begin() File "/usr/local/lib/python3.7/http/client.py", line 319, in begin version, status, reason = self._read_status() File "/usr/local/lib/python3.7/http/client.py", line 280, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "/usr/local/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/gunicorn/workers/base.py", line 201, in handle_abort sys.exit(1) SystemExit: 1 For your information, my code is something like this:- res1 = requests.post(url1, data=data1) result = res1.json() print(result['id']) # successfully prints data2 … -
Django - form validate images on upload
How to clean() an image with his size and extension? Image is uploading well into db, but when i'm trying to get cleaned_data it returns None. I set same looking validator on models and it works well, but only when i upload an image by adminsite. forms.py: class AdditionalInfoForm(forms.Form): first_name = forms.CharField(label='First name', max_length=20) last_name = forms.CharField(label='Last name', max_length=40) male = forms.ChoiceField(label="Male", choices=MALES, required=False) date_of_birth = forms.DateTimeField(label="Date of birth", required=False, widget=DateInput) about = forms.CharField(label='Tell us about yourself', widget=forms.Textarea(), required=False) image = forms.ImageField(label="Profile picture", required=False) def clean_image(self): avaible_formats = [ 'png', 'jpeg', 'jpg', ] img = self.cleaned_data.get('image') print(img) #always None if img: img_ext = img.name.split(".")[-1] if img.size > 4194304: raise ValidationError("Image size must be less than 4MB") if img_ext not in avaible_formats: raise ValidationError("Image extension is not avaible") return img -
Django - Show date and time of appointment
I'm currently showing all dates that appointments are not booked. from datetime import date, timedelta num_days = 5 start_date = date.today() timeframe = [start_date + timedelta(days=d) for d in range(num_days)] exclude = list(Transaction.objects.values_list("start_appointment__date", flat=True).distinct()) set(timeframe) - set(exclude) For example i have appointments booked for: [datetime.date(2021, 12, 8), datetime.date(2021, 12, 7), datetime.date(2021, 12, 7), datetime.date(2021, 12, 7)] And the dates not booked: {datetime.date(2021, 12, 10), datetime.date(2021, 12, 9), datetime.date(2021, 12, 11)} I would like to show also the available times for the not booked dates with a time interval between 11:00AM to 21:00PM:. Is that possible with the current implementation? If yes how can i achieve that? If not could you please suggest an alternative way? Thank you -
Django autoredirect to default language not work with Debug=False
I have app, with next urls.py urlpatterns += i18n_patterns( path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), path('admin/', admin.site.urls), path('accounts/social/login/cancelled/', RedirectView.as_view(url='/')), path('accounts/', include('allauth.urls')), path('', include(cms_urls)), ) also in settings.py I setup: LANGUAGE_CODE = "de" LANGUAGES = [ ('de', _('German')), # ('en', _('English')), ] so, if DEBUG = True when I go to / url app automatically redirect me to '/de/', but if DEBUG = False - app not autoredirect me to /de, I just got 404 error How I can manage it on production with DEBUG = False? -
fetch data using ForeignKey relationship data filtering
hai stackoverflow community, i need a favour from your side to complete this one class Store_Master(models.Model): id = models.IntegerField(primary_key=True) d_code = models.CharField(max_length=50,blank = True,null = True) showroom =models.CharField(max_length=50,blank = True,null = True) short_code=models.CharField(max_length=50,blank = True,null = True) type=models.CharField(max_length=50,blank = True,null = True) flat_house_no =models.CharField(max_length=50,blank = True,null = True) street_building_name=models.CharField(max_length=50,blank = True,null = True) landmark=models.CharField(max_length=50,blank = True,null = True) pincode=models.CharField(max_length=50,blank = True,null = True) area=models.CharField(max_length=50,blank = True,null = True) taluk=models.CharField(max_length=50,blank = True,null = True) district= models.CharField(max_length=50,blank = True,null = True) state=models.CharField(max_length=50,blank = True,null = True) status=models.CharField(max_length=50,blank = True,null = True) dob=models.CharField(max_length=50,blank = True,null = True) closed=models.CharField(max_length=50,blank = True,null = True) def __str__(self): return self.showroom class edition(models.Model): id = models.IntegerField(primary_key=True) district= models.ForeignKey(Store_Master, on_delete=models.DO_NOTHING) state = models.CharField(max_length=50, blank=True,null=True) vk_daily = models.CharField(max_length=50, blank=True,null=True) vk_dhinam= models.CharField(max_length=50,blank=True,null=True) def __str__(self): return self.district help me to write views for this on. in both tables district is present I use that as a foreign key. and I have some limited districts in that district we have more showrooms I need to map that using ForeignKey my expected output is when I click district the store_master data will appear on table view. please help me to resolve this thanks in advance -
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor h22sm15927247pfv.25 - gsmtp') Environment Variable are set but does not work (even though it's the exact value). I have set the app password in google account, captcha is disabled I have set the env variables in .bashrc file export EMAIL_USER='da24@gmail.com' Comparision btw the os.environ.get('EMAIL_USER') and the mail value string is True -
When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine
When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from .models import Client,Worker #worker signal def worker_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='worker') instance.groups.add(group) Worker.objects.create( user=instance, name=instance.username, ) print('profile created!') post_save.connect(worker_profile, sender=User) #client signal def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, ) print('Profile created!') `post_save.connect(client_profile, sender=User`) When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine signals.py Here is the views.py file from django.http.response import JsonResponse from django.shortcuts import render, redirect from .forms import CreateUserForm, AppointmentForm from .models import * from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from django.contrib import messages from .decorators import allowed_users, unauthenticated_user, worker_only from .forms import * from .filters import AppointmentFilter @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created … -
Django Youtube video download to client machine
Hi Friend I want to write python code to that video download to user machine. Now I send ajax request my view.py file and download video But my project videos file. def download_youtube_video(url): url="https://www.youtube.com/watch?v="+str(url) myVideo = YouTube(url) higest = myVideo.streams.get_highest_resolution().resolution if myVideo.streams.filter(res=higest).first().download('videos'): return True else: return False def ajax(request): if request.method == "GET": url=request.GET.get('url') if download(download_youtube_video(url)) == True: return JsonResponse(data = {"success":"Successs"}) else: return JsonResponse(data = {"success":"Error"}) -
Getting an CommandError in virtual environment in django app : You appear not to have the 'sqlite3' program installed or on your path
I am trying to create my first django website.I am using windows and visual studio code. I am following the tutorials given on their sitehere I have completed the part 1, now I want to use sqlite database. I have used the command $ python manage.py migrate Now I want to check the schema of the database created. I have tried running the command $ python manage.py dbshell But it is giving me error : CommandError: You appear not to have the 'sqlite3' program installed or on your path. I don't how to resolve. What I did? I have installed precompiled binaries from the official site. and also downloaded sqlite3.exe from the same link. Then I created a folder in my C:/ directory and included a folder SQLite and included these 3 files: sqlite3.def, sqlite3.dll and sqlite3.exe files. And also include the path of that folder into Environment Paths. Its working in a windows command prompt. But not running in virtual environment. Please suggest some solutions. -
Ran into this problem while using webbot library on python
Traceback (most recent call last): File "C:\Users\Anil\Desktop\instagram\instagram-brute-force.py", line 14, in <module> web = Browser() File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\webbot\webbot.py", line 68, in __init__ self.driver = webdriver.Chrome(executable_path=driverpath, options=options) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 70, in __init__ super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog", File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 93, in __init__ RemoteWebDriver.__init__( File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 268, in __init__ self.start_session(capabilities, browser_profile) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 359, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute self.error_handler.check_response(response) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary (Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.19042 x86_64) -
Multithreading in Django
I'm working on a Django project, in which I will need the use of multithreading and multiprocessing concepts (Send and receive data from other servers such as PACS server/ I/O Threads... ). The question I have is Django capable of applying multithreading /multiprocessing? Can we make two tasks run simultaneously or concurrently ? Thank you -
Django + PostgreSQL: how to identify user contributions?
I'm building a Django website based on a PostgreSQL database. Identified users will be allowed to add entities through the admin. I'm looking for a way to identify which entity was added by which user, to be able to keep the information associated with the record and retrieve it later. Is it possible? The "recent actions" widget that a connected user can see in the admin suggests it is. -
Reverse for 'edit-todo' with arguments '('',)' not found. 1 pattern(s) tried: ['edit\\-todo/(?P<id>[0-9]+)/$']
I've dug around the internet and can't find a solution. Please help me lovely people of the internet. In my views.py @login_required def edit_todo(request, pk): usertodo = get_object_or_404(Todo, pk=pk) return HttpResponse('test') In my urls.py urlpatterns = [ ... path('edit-todo/<int:pk>/', views.edit_todo, name='edit-todo'), path('test/<int:pk>/', views.edit_todo, name='test'), ... ] In my template/component that's included <form hx-encoding="multipart/form-data" hx-post="{% url 'core:edit-todo' tododetail.todo.id %}" hx-target="#todo-list" method="post"> tododetail.todo.id is called because I've got an ordering table which has todo & user as foreign keys. When accessing the view directly using a test URL it works -
How to allow the user to change theme color for a bootstrap4 theme using a color picker in a django website?
I want to allow the application users to be able to change the bootstrap theme color using a color picker. I haven't found any good examples yet on how to achieve this in Django. I understand that adding predefined themes and toggling between them is simpler. But in this case, I need to allow user to select from a color picker rather than switching between few predefined templates. -
Django Channels Consumer Not Connecting to websocket
i created a websocket with javascripts on the client side...then followed up with setting up my project to handle webocket connections as follows(following the official django-channels documentation). But each time i refresh the page and watch the websocket from the browser console...its fails. i inserted an print statement in the init of the consumer class and it was printed(each time a page containing a websocket was visited or refreshed)..which mean that the routing is working fine...but for some reasons the consumer is not connecting/accepting the connection as expected to the websocket. and again there is no log in the development server as to any websocket connection process.Please can anyone help and suggest a fix. my setting.py file(relevant lines) INSTALLED_APPS = [ ... 'channels', ] ASGI_APPLICATION = 'ma_mall.asgi.application' CHANNEL_LAYERS = { "default": { 'BACKEND': "channels_redis.core.RedisChannelLayer", "CONFIG": { 'hosts': [('127.0.0.1', 6379)], } } } my asgi.py file application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( routing.websocket_urlpatterns ) }) my routing.py file websocket_urlpatterns = [ path("ws/notifications/", consumers.NotificationConsumer), ] my consumer file class NotificationConsumer(AsyncJsonWebsocketConsumer): groups = ['general_group'] async def connect(self): await self.accept() await self.channel_layer.group_add('notification_group', self.channel_name) await self.channel_layer.group_send('notification_group', { 'type': 'tester.message', 'tester': 'tester' } ) async def disconnect(self, close_code): await self.channel_layer.group_discard('notification_group', self.channel_name) the javascript for the … -
Removing element from for loop html django?
I have a for loop in my html to show the user their favourite games. Like this: <div class="dropdown-cart-products"> {% if user.is_authenticated %} {% for i in wishlist %} <div class="product"> <div class="product-details"> <h4 class="product-title"> <a href="{% url 'detail' i.oyunlar.platformurl i.oyunlar.slugyap %}">{{i.oyunlar.title}} {{i.oyunlar.platform}}</a> </h4> <span class="cart-product-info"> <!-- <span class="cart-product-qty">1</span>--> Anlık en ucuz Fiyatı: {{i.oyunlar.en_ucuz}} </span> </div><!-- End .product-details --> <figure class="product-image-container"> <a href="{% url 'detail' i.oyunlar.platformurl i.oyunlar.slugyap %}" class="product-image"> <img src=" {{i.oyunlar.image}}" alt="product"> </a> <a href="javascript:{document.getElementById('upvote1').submit()}" class="btn-remove" title="Favorilerden Çıkar"><i class="icon-retweet"></i></a> <form id="upvote1" method="POST" action="{% url 'favhome' i.oyunlar.game_id %}"> {% csrf_token %} </form> </figure> </div><!-- End .product --> {% endfor %} I am trying to remove element like this: form id="upvote1" method="POST" action="{% url 'favhome' i.oyunlar.game_id %}"> {% csrf_token %} </form> The problem is that I can only remove first element in this loop cannot remove the second one third one or last one. How can I change my code to remove the selected element? -
How do i inspect all tables in databes mssql by Django inspect
I have mssql database with few tables: [dbo].[one_table] [dbo].[two_table] [model].[three_table] [model].[four_table] [plan].[five_table] my django settings.py: DATABASES = { 'default': { "ENGINE": "mssql", "NAME": "ips_db", "USER": "sa", "PASSWORD": "***", "HOST": "***", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } When i try inspect db by python inspectdb > models.py I get only one_table and two_table class One_table(models.Model): firstname = models.CharField(db_column='FirstName', max_length=30, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. lastname = models.CharField(db_column='LastName', max_length=40, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. class Meta: managed = False db_table = 'One_table' class Two_table(models.Model): test = models.CharField(db_column='Test', max_length=10, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. tes2 = models.CharField(db_column='Tes2', max_length=10, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Two_table' How can i get all tables models from my database??? -
How to fetch warnings from a django mysql query?
I'm trying to get a list of warnings after a mySQL query, using Django admin. I can see from the documentation here that it's possible to record warnings by setting connection.get_warnings to true. But I can't find anything explaining how to read those warnings. I do not want to throw an exception - I am deleting items from the database using a DELETE IGNORE statement and want to get all instances of deletions that failed (due to external keys, etc.) I've tried returning the result of the execute function itself (just gave me a number) and calling fetchwarnings() on the cursor (threw a "Cursor object has no attribute fetchwarnings" error). I'm still new to both Python and Django. I'm looking through all the documentation I can find but can't find anything that works. from django.db import connection query = "{query here}" connection.get_warnings = True with connection.cursor() as cursor: cursor.execute(query) <-- Returns a number return cursor.fetchwarnings() <-- Throws an error -
django logdna not working. server getting stuck
import logging from logdna import LogDNAHandler LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s]" + "%(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'color': { '()': 'colorlog.ColoredFormatter', 'format': '%(log_color)s%(asctime)s %(levelname)-8s %(name)s %(module)s %(pathname)s:%(lineno)s%(reset)s \n\r\t %(message)s', 'datefmt': "%d/%b/%Y %H:%M:%S", 'log_colors': { 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', } } }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'color' }, 'logdna': { 'level': logging.DEBUG, 'class': 'logdna.LogDNAHandler', 'key': "f47ec154e993efce66ed784ad7g3g76b8cb91", 'options': { # 'app': '<app name>', # 'env': "alpha", 'index_meta': True, }, }, }, 'loggers': { '': { 'level': logging.DEBUG, 'handlers': ['logdna'], 'propagate': True, }, } } I am using above code for django logging using logdna. But when i am running django server it is getting stuck . what can be the reason ? Am i doing it correctly ? Please take a look I am following https://github.com/logdna/python doc for implementation. django with logdna for logging -
Sanitizing SQL input in Django for PostgreSQL
I know that there are tools how to prevent sql injection especially with psycopg2 and how to work with them, but i have an other use case. The query should not be directly executed in PostgreSQL, but in InfluxDB as a part of join between metadata from PostgreSQL and measurements from InfluxDB that is done with the sql package from it. So i need to produce a string part of a bigger query that is totally safe, especially in the filter part of the query where a LIKE part is entered. I think this is possible by acquiring the the cursor object of the connection from the connection pool and then use mogrify() to get the safe sql after binding, but this approach seems complex and unnecessary as i don't need to execute it in PostgreSQL directly. Is there a tool or library in Python that can check/adapt/escape/sanitize the query as a string, or bind parameters in a safe way? -
JQuery and Vuejs APIs not passing nor retrieving data to database Django
I had working been on a web app using Django and had to take a 3-month break. I decided to continue and suddenly all my jquery and vuejs code is not working although it had been perfectly working 3-months ago. This is my base.html <head> <link href="https://vjs.zencdn.net/7.11.4/video-js.css" rel="stylesheet"> <!-- Vue Js --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- JQuery script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> urls.py from conversation.api import api_add_message urlpatterns = [ path('api/add_message/', api_add_message, name='api_add_message'), ] api.py import json from django.http import JsonResponse from django.contrib.auth.decorators import login_required from .models import ConversationMessage @login_required def api_add_message(request): data = json.loads(request.body) content = data['content'] conversation_id = data['conversation_id'] message = ConversationMessage.objects.create(conversation_id=conversation_id, content=content, created_by=request.user) template.html <li class="chat-left" v-for="message in messages"> <div class="chat-avatar"> <img :src="message.image"alt="Retail Admin"> <div class="chat-name">[[ message.user ]]</div> </div> <div class="chat-text">[[ message.content ]]</div> <div class="chat-hour">[[ message.user ]]</div> </li> And this is my script in the template {% block script %} <script> var conversationapp = new Vue({ el: '#conversationapp', delimiters: ['[[', ']]'], data () { return { messages: [], content: '', user: '{{ request.user.username }}', created_at: 'Now', image: '{% if request.user.profile.image %}{{ request.user.profile.image.url }}{% endif %}' } }, methods: { submitMessage() { if (this.content.length > 0) { var message = { 'content': this.content, 'user': this.user, 'created_at': this.created_at, 'image': this.image, … -
How do you combine two querysets into one queryset(not a list) in django?
I want to simply combine two querysets from different models into one queryset (and not a list as shown in other stackoverflow questions!). For example, here are two querysets: a = Modelone.objects.all() b = Modeltwo.objects.filter(number__gte=4) Then, I want a queryset c that combines both a and b. Thank you, and please leave me any questions you have. -
hello, why does my template Django not want to display the results of my review form?
I cannot understand why the result of my review form is not showing in the template, even though my ticket form is working fine. However, I have linked the 2 models with a foreign key. Then in the template I added "ticket.id". Finally, the objective of this app is to limit the review to one person. Thank you in advance for your help. My models: class Ticket(models.Model): title = models.CharField(max_length=128) content = models.TextField(max_length=2048, blank=True, null=True) image = models.ImageField(null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def __str__(self) : return self.title class Review(models.Model): ticket = models.ForeignKey(Ticket, related_name="reviews" ,on_delete=models.CASCADE) rating = models.PositiveIntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) headline = models.CharField(max_length=128) body = models.TextField(max_length=8192, blank=True, null=True) time_created = models.DateTimeField(auto_now_add=True) def __str__(self) : return self.ticket.title My forms : class TicketForm(forms.ModelForm): class Meta: model = models.Ticket fields = ['title', 'content','image'] class ReviewForm(forms.ModelForm): class Meta: model = models.Review fields = ['rating','headline','body'] My view : @login_required def review(request, ticket_id): ticket = get_object_or_404(models.Ticket, id=ticket_id) review_form = forms.ReviewForm(instance=ticket) if request.method == 'POST': review_form = forms.ReviewForm(request.POST, instance=ticket) if review_form.is_valid(): review = review_form.save(commit=False) review.user = request.user review.save() return redirect('home') return render(request, 'flux/create_review_post.html', context={'review_form': review_form}) My urls: path('home/', flux.views.home, name='home'), path('ticket/create/', flux.views.ticket, name='ticket_create'), path('flux/<int:ticket_id>/', flux.views.view_ticket, name='view_ticket'), path('<int:ticket_id>/review/create/', flux.views.review, name='review_create'), My template review … -
How to make media file's URL restricted to the unauthenticated users in Django?
I am going to build a Django storage application where users can upload files to the server. Users also can download their files from the server. To download the file, the server returns the URL of the media file to the user. I added a permission class, if the user is authenticated & owner of the file then return the URL of the media file, otherwise return 404. But there is a problem, if any unauthenticated user found the URL of the media file from the history of the browser, then he can download/access the file. How can I handle this case?