Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
db service connection error when Docker Compose Up
Right now I am working on containerize my Python django app with docker. I has two services in docker-compose file: web and db. And web service depends on the db service. While I ran docker-compose build is fine but when I ran docker-compose up, the web service always error out with error: web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 127, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | psycopg2.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Cannot assign requested address web_1 … -
Django not detecting foreign key in a ManyToManyField when passed through a Model
I am trying to build a relation between the Subject model and the Teacher model and the Classes model. This is how I am relating it- A subject can be taught in many classes and a class can have many subjects. A subject in a class can be taught by only one teacher. So basically what I am trying to do is this- there's a subject, say Maths, the subject can be taught in many classes, say Class 1 to Class 10 and there will be various teachers teaching in different classes. Here's my Subject model: class Subjects(models.Model): subject_id = models.CharField(unique=True, max_length=20) classes = models.ManyToManyField(Classes, through='ThroughTeacher') ThroughTeacher model: class ThroughTeacher(models.Model): class_id = models.ForeignKey(Classes, null=True, on_delete=models.SET_NULL) teacher = models.ForeignKey(Teacher, null=True, on_delete=models.SET_NULL) Classes model: class Classes(models.Model): class_id = models.CharField(unique=True, max_length=30) teacher = models.ManyToManyField(Teacher) Teacher model: class Teacher(models.Model): name = models.CharField(max_length=30) contact = models.CharField(max_length=10) This is the error I am getting: subjects.ThroughTeacher: (fields.E336) The model is used as an intermediate model by 'subjects.Subjects.classes', but it does not have a foreign key to 'Subjects' or 'Classes'. -
How I can save a list of string in my model?
I want to store a list of strings as a field of my model. categories=['Abstract Strategy', 'Medieval'] I want to save the category as a field. my database is sqlite3. -
Can I limit the displaying of Django's Page not found?
When I develop Django websites, I always develop them on a server that sits on the Internet in order to mirror my production environment (I run macOS locally but my servers are Linux). During development I also will set DEBUG = True for debugging purposes. The problem is that if I or anyone else who's poking around on my site enters an invalid URLconf string, Django displays the "Page not found (404)" page along with all valid URL patterns, which I feel is a bit of a security risk. For example, my custom URL for the Django admin site is listed there. Is there a way to disable the showing of this specific error page when I have DEBUG set to True or perhaps to limit its display to particular IP addresses? -
ValueError at /sendrequest/bandit Cannot assign "'jacob'": "ConnectRequest.sender" must be a "Profile" instance
i am making a friend request feature and i am not able to save my data this error is showing up everytime. this is my views.py def sendrequest(request,receiver): receiver_user = Profile.objects.get(username=receiver).username sender=request.user sender_user=Profile.objects.get(username=sender).username connection=ConnectRequest(sender=sender_user, receiver=receiver_user, status="Pending" ) connection.save() return redirect("buddylist") this is my Profile model class Profile(models.Model): idno=models.AutoField(primary_key=True) name=models.CharField(max_length=30) email=models.CharField(max_length=40) username=models.CharField(max_length=30) this is my ConnectRequest model class ConnectRequest(models.Model): sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(Profile,on_delete=models.CASCADE, related_name="receiver") choice=( ("Accepted","Accepted"), ("Declined","Declined"), ("Pending","Pending") ) status=models.CharField(max_length=10,choices=choice,blank=True) def __str__(self): return f"{self.sender} to {self.receiver} status {self.status}" -
How to create a new HTML li upon creation a new page in Django
I have created a new model and added it to the admin page so the admin can add new pages via /admin section. Now I need to add every page which is created to the html footer as a new home.html (footer section) <div class="col-md-6 col-lg-6"> <ul class="list-unstyled"> <li><a href="#">Home</a></li> <li><a href="#">Services</a></li> <li><a href="#">Events</a></li> <li><a href="#">Team</a></li> <li><a href={{ footer.faq }}>FAQ</a></li> <li><a href={{ footer.terms_and_conditions }}>Terms & Conditions</a> {% for i in context %} <li>{{i.title}}</a> {% endfor %} </li> </ul> </div> </div> </div> I tried to loop through in every new page created views.py def custom_page(request, slug): context = { 'all': CustomPage.objects.filter(slug=slug), 'toBePublished': CustomPage.objects.all() } return render(request, 'member/custom_page.html', context) models.py class CustomPage(models.Model): title = models.CharField(max_length=20, blank=True) subtitle = models.CharField(max_length=50, blank=True) slug = models.SlugField(max_length=500,blank=True) content = RichTextField() displayOnFooter = models.BooleanField(default=False) def __str__(self): return f'{self.title}' def get_absolute_url(self): return reverse('custom-page', kwargs={'slug': self.slug}) I have successfully created the slug so when a new page is created via admin I can find it via / but cannot seem to add it into the footer. Thanks Onur -
unable to upload image in folder using django
trying to upload image in folder a name 'pics' but after successful submision of form Just url of the image is stored in database column but there isn't any image in pic's folder stored. please help me to store images in pics folder using form. thank you. here is html <form id="form1" action='/indexpage' method="POST"> {% csrf_token %} <div id="jQueryProgressFormBar"></div> <div id ='part1'> <div class="row"> <div class="input-group col-6 ml-0 pl-0 m-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupFileAddon01">Upload</span> </div> <div class="custom-file"> <input type="file" name='img' class="custom-file-input" id="upload"> <label class="custom-file-label" for="inputGroupFile01" id="inputGroupFile02">Choose file</label> </div> </div> </div> <div class="row"> <div class="col-sm"> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label pr-3">Session:</label> <div class="col-sm-10"> <select class="form-control" name="session"> <option value='2019-2022'>2019-2022</option> <option value='2020-2023'>2020-2023</option> <option value='2021-2024'>2021-2024</option> </select> </div> </div> </div> </form> main URL's from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url urlpatterns = [ path('', include('index.urls')), url(r'^accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ]+static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ TEMPLATE_DIR, ] STATIC_ROOT ='/home/manteeform/Projects/manteeform/staticfiles' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = "/media/" models.py from django.db import models class Student_personal(models.Model): session = models.CharField(max_length=12) img = models.ImageField(upload_to='pics') clas = models.CharField(max_length=15) -
Django ON_DELETE policy not being applied in DB
I have the following model: class GeneMiRNACombination(models.Model): gene = models.CharField(max_length=50) experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE) source_statistical_data = models.OneToOneField( SourceDataStatisticalProperties, on_delete=models.SET_NULL, blank=True, null=True, default=None ) So I'd expect tha the ON_DELETE will be setted in the DB (Postgres in my case). But when I see the CREATE script this is what it prints: CREATE TABLE public.gene_mirna_combination ( id integer NOT NULL DEFAULT nextval('gene_mirna_combination_id_seq'::regclass), gene character varying(50) COLLATE pg_catalog."default" NOT NULL, experiment_id integer NOT NULL, source_statistical_data_id integer, CONSTRAINT gene_mirna_combination_pkey PRIMARY KEY (id), CONSTRAINT gene_mirna_combination_properties_id_key UNIQUE (source_statistical_data_id), CONSTRAINT gene_mirna_combinati_experiment_id_31b52a17_fk_api_servi FOREIGN KEY (experiment_id) REFERENCES public.api_service_experiment (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED, CONSTRAINT gene_mirna_combinati_source_statistical_d_7d0f04a8_fk_statistic FOREIGN KEY (source_statistical_data_id) REFERENCES public.statistical_properties_sourcedatastatisticalproperties (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ) TABLESPACE pg_default; ALTER TABLE public.gene_mirna_combination OWNER to root; CREATE INDEX gene_mirna_combination_experiment_id_31b52a17 ON public.gene_mirna_combination USING btree (experiment_id ASC NULLS LAST) TABLESPACE pg_default; So, there is no action on delete! Why? It should set the ON DELETE CASCADE when creates the table, shouldn't it? Is there any implicit behaviour? If there isn't an ON DELETE policy so every time I remove a referenced object it must be removed from Django, which will be extremely slower than … -
Is it okay to call django functions through an API?
I'm building a project and now I'm new to VueJS I'm currently learning it. and I found that you can make HTTP Requests on APIs using axios. And to make my project easy, Can I call functions on my views.py thru axios? Like I'm fetching urls in urls.py to execute some functions on my backend. Is it okay? I mean for security and best practices. etc. Thanks -
Authentication problem using Nginx and Django Rest Framework
When trying to create a Django Rest Framework based web app, we encountered the following problem: Our whole app should and is protected by our settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ), But for one single route (which provides the schema for the front end code generation) we would like to have basic auth (test:test@host/special_route). The idea was to add the route to nginx like here. Our nginx conf looks as follows: server { ... location /special_route { auth_basic "API Schema"; auth_basic_user_file /etc/nginx/.htpasswd; } } Now when accessing this route the authentication popup shows and the password and username are validated, but on success it shows 404. When deleting this piece of code it shows up without the 404, so I am guessing it's not a Django problem. I tried adding basic authentication to the auth classes, reloading and restarting the server and changing the special_route to avoid misspells. I even experimentally deleted the location and applied the config to the whole server, which worked as expected. -
appending the data according "id" : Python
I'm getting the "km_difference" data in a dictionary of list format in another list. but i want to get the "km_difference" data inside the first index of list according it's "id". Any helpful, would be much appreciated. thank you so much in advance. data = ShopOwnerShopDetailsSerializer(garage_qs, many=True, context={'request': request}).data km_difference = [] for record in data: lon = record['lon'] lat = record['lat'] lon1 = float(lon) lat1 = float(lat) km_differ = distance(lon1, lat1, lon2, lat2) km_difference.append({"km_difference":km_differ}) data.append({"km_difference":km_difference}) Result: how i get the data format is: { "message": "success", "search_result": 2, "data": [ { "id": 2, "city_name": "CAIRO", "shop_location": "iuaisd,qweqw,qwe", "lat": "14.56", "lon": "89.90", }, { "id": 5, "city_name": "CAIRO", "shop_location": "iuaisd,qweqw,qwe", "lat": "14.56", "lon": "89.90", }, { "km_difference": [ { "km_difference": 7853.450620509551 }, { "km_difference": 7853.450620509551 } ] } ] } Expecting: how i want output on this format is: { "message": "success", "search_result": 2, "data": [ { "id": 2, "city_name": "CAIRO", "shop_location": "iuaisd,qweqw,qwe", "lat": "14.56", "lon": "89.90", "km_difference": 7853.450620509551 }, { "id": 5, "city_name": "CAIRO", "shop_location": "iuaisd,qweqw,qwe", "lat": "14.56", "lon": "89.90", "km_difference": 7853.450620509551 }, ] } -
Redirect to the another html page after clicking input tag in django template
I want to redirect the website after edit (http://127.0.0.1:8000/account/edit/) to the dashboard (http://127.0.0.1:8000/account/dashboard) in Django template. I have a file named dashboard.html in the same directory. But it keeps me to the same page (http://127.0.0.1:8000/account/edit/. edit.html {% extends "base.html" %} {% block title %}Edit your account{% endblock %} {% block content %} <h1>Edit your account</h1> <p>You can edit your account using the following form:</p> <form action="dashboard.html" method="post" enctype="multipart/form-data"> {{ user_form.as_p }} {{ profile_form.as_p }} {% csrf_token %} <p><input type="submit" value="Save change"></p> </form> {% endblock %} -
Ignoring duplicate records when using bulk create
I have implemented and endpoint that is used to read a csv or an excel file and seeds the records into the database as shown below. How do I ensure that I don't upload duplicates into the database? def post(self, request, *args, **kwargs): """Upload the CSV file. Then reads it and saves *.csv *.xlsx data to database. Endpoint: /api/import_data/ """ print(request.data['file'].__dict__) file_serializer = FileSerializer(data=request.data) # Commented code is for debugging only # import pdb; pdb.set_trace() # print(to_dict['_name']) _dict_file_obj = request.data['file'].__dict__ _csv = _dict_file_obj['_name'].endswith('.csv') _excel = _dict_file_obj['_name'].endswith('.xlsx') if request.data['file'] is None: return Response({"error": "No File Found"}, status=status.HTTP_400_BAD_REQUEST) csv_data = self.request.data.get('file') if file_serializer.is_valid(): data = self.request.data.get('file') if _csv is True: print('Show') data_set = data.read().decode('UTF-8') io_string = io.StringIO(data_set) io_string = io.StringIO(data_set) csv_file = pd.read_csv(io_string, low_memory=False) columns = list(csv_file.columns.values) first_name, last_name, email = columns[0], columns[1],\ columns[2] instances = [ Business( business_id=row[0], business_name=row[1], business_activity=row[16], pin_number=row[29], activity_code=row[21], town=row[33], physical_address = row[8], po_box=row[31], sub_county_code=row[22], ward_code=row[23], plot_number = row[9] ) for index, row in csv_file.iterrows() ] result = Business.objects.bulk_create(instances) serialize= IssuedPermitSerializer(result,many=True) return Response(data=serialize.data) ........................... -
ValueError at /sendrequest/jacob Cannot assign "'jacob'": "ConnectRequest.receiver" must be a "User" instance
i am making a friend request feature and i got this error this is my models.py for friend request class ConnectRequest(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(User,on_delete=models.CASCADE, related_name="receiver") choice=( ("Accepted","Accepted"), ("Declined","Declined"), ("Pending","Pending") ) status=models.CharField(max_length=10,choices=choice,blank=True) this is my urls.py def sendrequest(request,receiver): sender=request.user connection=ConnectRequest(sender=sender,receiver=receiver,status="Pending") connection.save() return redirect("buddylist") -
How to show data by formatting string into django templates?
Here i am creating a blog and formatting some content bold as show below: on a detail page that text is showing me like this: how to fix it and change its format , -
Django runserver problem "python manage.ph runserver"
i have a django file, and i'm trying to see that file in django but when i command "python manage.ph runserver" it's not showing anything. just emty line in cmd after i commend. i tried to fin and error in my pip but there wasn't any problem. and the file is fine as well. i tried to create and run another file from scrach but it didn't work too. so is there anyone who knows the solution ?as you can see, when i try to run the file in django, it's not responding anything -
Problems with creating slug
Hello good afternoon I am developing an application that handles two roles of administrator and developer, the administrator data as developer is created without problems but when trying to use slug the program does not recognize them. This is my model class ProfileAdministrator(models.Model): user = models.OneToOneField(Administrator, on_delete=models.CASCADE) image = models.ImageField(default='avatar.png', upload_to='profiles/') slug = models.SlugField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.slug class ProfileDeveloper(models.Model): user = models.OneToOneField(Developer, on_delete=models.CASCADE) image = models.ImageField(default='avatar.png', upload_to='profiles/') slug = models.SlugField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.slug @receiver(post_save, sender=Administrator) def set_profile_administrator(sender, instance, *args, **kwargs): if kwargs.get('created', False): ProfileAdministrator.objects.create(user=instance) @receiver(post_save, sender=Developer) def set_profile_developer(sender, instance, *args, **kwargs): if kwargs.get('created', False): ProfileDeveloper.objects.create(user=instance) @receiver(pre_save, sender=ProfileAdministrator) def set_slug_profile_administrator(sender, instance, *args, **kwargs): if instance.user: instance.slug = slugify(instance.user) @receiver(pre_save, sender=ProfileDeveloper) def set_slug_profile_administrator(sender, instance, *args, **kwargs): if instance.user: instance.slug = slugify(instance.user) the program works fine even when I enter the slug, it does not recognize them, but the data is created correctly -
Cannot assign "[{'id': '2'}]": "Model .field" must be a "ForeignKey" instance
I have two model BAI and EMT. BMI has a CharField called country, in my EMT model i have country_name field where i am passing as foreignkey of BMT, Now when i am trying to create a new EMT i am getting this error: Cannot assign "[{'id': '2'}]": "EMT.country" must be a "BAI" instance. my models ### Country Related Model ### class BAI(models.Model): country = models.CharField(max_length=100, null=True) currency = models.CharField(max_length=100, null=True) capital = models.CharField(max_length=100, null=True) def __str__(self): return self.country class Meta: db_table = 'app_country_banner_and_information' ordering = ['id'] ### Country Export Related Model ### class EMT(models.Model): country = models.ForeignKey( BannerandInformation, on_delete=models.CASCADE, null=True) year = models.CharField(max_length=100, null=True) def __str__(self): return ('Export') class Meta: db_table = 'app_emt' ordering = ['id'] my views @csrf_exempt def emt(request, id=None): if request.user.profile.role == '2': if request.method == 'GET': if id is not None: try: offer = EMT.objects.get(id=id) data = { 'country': '', 'year': '', } except Exception: return HttpResponse(json.dumps({"status": 0}), content_type='application/json', status=401) else: return HttpResponse(json.dumps({"status": 0}), content_type='application/json', status=401) elif request.method == 'POST': data = json.loads(request.body) if id is not None: try: existInfo = EMT.objects.get( id=id, ) existInfo.country=data.get('country', None) existInfo.year=data.get('year', None) try: existInfo.save() return HttpResponse(json.dumps({"status": 1}), content_type='application/json') except IntegrityError as e: err = e.args[1] err = err.replace(" for … -
Django Social-Auth - save Stripe Email
I'm using Django Social Auth for Stripe. My goal is to create an account on my website with all those : email, stripe_account That works well except for the email: I got username = stripe_account without any email. I've read the Stripe Doc but I did not find anything on this. settings.py 'social_core.backends.stripe.StripeOAuth2', SOCIAL_AUTH_STRIPE_KEY = '****' SOCIAL_AUTH_STRIPE_SECRET = '****' SOCIAL_AUTH_STRIPE_SCOPE = ['read_only'] {% url 'social:begin' 'stripe' %} -
django custom authentication backend is not being called
I am using Django 3.1, and trying to figure out why my custom Authentication backend isn't being called. In my settings.py file I have: AUTHENTICATION_BACKENDS = ( 'sizzy.backends.EmailBackend', ) And in my sizzy.backends.py file I have: from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import ModelBackend from .models import User class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None): try: print("Trying the email backend!") user = User.objects.get(email=username) print("Got the user") if user.check_password(password): # check valid password return user print("password didn't work") except ObjectDoesNotExist: return None def get_user(self, user_id): try: print("Getting the user of the Email Bkacned") return User.objects.get(pk=user_id) except ObjectDoesNotExist: return None I then open up the manage.py shell and input: from django.contrib.auth import authenticate email = "billypop@a.pop" password = "password" user = authenticate(username=email, password=password) And it outputs: Login failed. Credentials: {'username': 'billypop@a.pop', 'password': '********************'} And I don't see any print statements. "Trying to get the Email Backend!" is never printed. Am I missing something? I tried changing my settings file to point to sizzy.backends.EmailBackendqwertyui just as a sanity check, and that threw an error instead of Login failed. So the backend is being loaded somehow I think, but never called. I've also tried changing out ModelBackend for BaseBackend, with the same results. -
MultiValueDictKeyError in accessing same form element in Django
I have some dropdowns here in my Index.html file. I have accessed the values selected in name=player1 and name=player2 dropdowns. But when I am going to access the value of name=selectcountry1 on same page in same form. Django is showing MultiValueDictKeyError. If I comment out the line in which I am accessing name=selectcountry1, all works fine. It takes the values of other dropdowns correctly. Also when I use request.POST.get('selectcountry1'), it is returning 'None', What is the problem as well as the solution. I don't want None, I want the value selected in dropdown. My HTML Page - <form method="post" action="{% url 'dynamic' %}" enctype="multipart/form-data"> {% csrf_token %} {% comment %} Defining a Form for Accepting first and second country and submit button {% endcomment %} <!--Defining Left Division for Team 1 (team1div)--> <div style="float : left; margin-top: 2%; width: 50%; padding-left: 10px;"> <div style="margin-left: 15px;"> <select name="selectcountry1" id="c1" onchange="getValue1(this)" style="width:180px;"> <option class="sel" selected value="select">Select Country 1</option> <option data-img_src='/static/India.png' value="India" >India</option> <option data-img_src='/static/Australia.png' value="Australia" >Australia</option> <option data-img_src='/static/England.png' value="England" >England</option> <option data-img_src='/static/NewZealand.png' value="NewZealand" >New Zealand</option> <option data-img_src='/static/SouthAfrica.png' value="SouthAfrika" >South Afrika</option> <option data-img_src='/static/WestIndies.png' value="WestIndies" >West Indies</option> <option data-img_src='/static/Pakistan.png' value="Pakistan" >Pakistan</option> <option data-img_src='/static/Srilanka.png' value="SriLanka" >Sri Lanka</option> <option data-img_src='/static/Bangladesh.png' value="Bangladesh" >Bangladesh</option> <option data-img_src='/static/Afganistan.jpg' value="Afganistan" >Afganistan</option> … -
Streaming multiple files through Django
I would like to stream a multiple files through Django. My ideas is to zip the files in memory then send it, as in the below code. But the problem is this will take too much time and ressources on my server. My question is: is there a better way to serve multiple urls through Django without zipping them ? import requests from django.http import StreamingHttpResponse def download(request): url = ['https://myondownlaod.com/file1.mp4','https://myondownlaod.com/file2.mp4','https://myondownlaod.com/file3.mp4'] in_memory = StringIO() for u in url: filename = os.path.basename(u) r = requests.get(u) zip = ZipFile(in_memory, "a") zip.write(r) zip.close() response = HttpResponse(mimetype="application/zip") response["Content-Disposition"] = "attachment; filename=my_zippedfiles.zip" in_memory.seek(0) response.write(in_memory.read()) return response I have seen this example which work pretty well when I tried it, but them my question would be how do you deal with multiple files. import requests from django.http import StreamingHttpResponse from django.contrib.auth.views import login_required def download(request): url = 'file_url_here' filename = os.path.basename(url) r = requests.get(url, stream=True) response = StreamingHttpResponse(streaming_content=r) response['Content-Disposition'] = f'attachement; filename="{filename}"' return response -
Global continuous 3 minutes countdown
I have a django webapp I'm working on, so I don't know of its possible to have a global countdown of 3 minutes that refreshes the page at the end of each 3 minutes continously. I tried to use js but if I refresh the page the countdown starts over again -
multiple (upload) files extensions check in Django template?
how can i check file extension in Django template side? I want to upload multiple files like (photos&videos) in a single post like Facebook. if file is video format then automatically video player detects if it is an image file then it display automatically? when i post an image file i want only that particular file to be shown i don't want video area to show along with it. when i post certain files i want only that to be displayed! models.py class Article(models.Model): title = models.CharField(max_length=300,) file_data = models.FileField(upload_to='stories', blank=True, null=True) def __str__(self): return self.title def extension(self): name, extension = os.path.splitext(self.file_data.name) return extension forms.py class ArticleForm(forms.ModelForm): file_data = forms.FileField(required=False, widget=forms.FileInput( attrs={'accept': 'image/*,video/*', 'multiple': True})) class Meta: model = Article fields = [ 'title', 'file_data', ] {% for object in newss %} <div class=" card"> {% if object.file_data %} <img src="{{object.file_data.url}}" alt="article" height="400"> {% endif %} {% if object.file_data %} <video class="afterglow" id="myvideo" width="1280" height="720" data-volume=".5"> <source type="video/mp4" src="{{object.file_data.url}}#t=0.9" /> </video> {% endif %} </div> {% endfor %} -
Django TemplateDoesNotExist, when trying to redirect user's
I have this structure,and basically what I want is to send the user to the right place depending on their group. myproject/ |-- myproject |--urls.py |--settings.py |--views.py |-- pluviais/ |--urls.py |--views.py |-- eletricistas/ |--urls.py |--views.py So when they login, my settings.py redirect to index, (LOGIN_REDIRECT_URL = 'index') myproject/urls.py from .views import index urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('pluviais/', include('pluviais.urls')), path('eletricistas/', include('eletricistas.urls')), ] document_root=settings.MEDIA_ROOT) myproject/views.py from django.contrib.auth.models import Group,User from django.shortcuts import render, redirect def index(request): users_in_group = Group.objects.get(name="tablet").user_set.all() if request.user in users_in_group: user_responsaveis_pluviais = User.objects.filter(username=request.user, groups__name='Responsáveis - pluviais').exists() user_chefes_pluviais = User.objects.filter(username=request.user, groups__name='Chefes - pluviais').exists() print(user_responsaveis_pluviais) if user_responsaveis_pluviais == True or user_chefes_pluviais==True: return render(request, '/pluviais/tablet/') else: return render(request, '/eletricistas/tablet/') As you can see the idea is simply depending on the groups that the users are in, they are redirected to the right place ( or go to pluviais/ or eletricistas/ pluviais/urls.py urlpatterns = [ path('tablet', views.intervencao, name='intervencao'), ] eletricistas/urls.py urlpatterns = [ path('tablet', views.tarefas, name='tarefas'), ] the problem is that always giving me the error TemplateDoesNotExist at /, so maybe i am doing this wrong.