Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render StructBlock which is inside StreamBlock to template?
How can I render heading, text, image in my carousel_block.html template. I can't access these. Here is my code. My custom block class CarouselBlock(blocks.StreamBlock): carousel_items = blocks.StructBlock([ ('heading', blocks.CharBlock(label='Nadpis', max_length=128)), ('text', blocks.CharBlock(label='Text')), ('image', ImageChooserBlock(label='Obrázek')), ]) class Meta: template = 'cms/blocks/carousel_block.html' This is my html template, where I want to render heading, text and image <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for carousel_items in self.carousel_items %} {% image carousel_items.value.image max-1920x1080 as image_1920 %} <div class="carousel-item {% if forloop.first %}active{% endif %} "> <section class="banner-area" id="home" style="background-image: url({{ image_1920.url }})"> <div class="container"> <div class="row justify-content-start align-items-center"> <div class="col-lg-6 col-md-12 banner-left"> <h1 class="text-white"> {{ carousel_items.value.heading }} </h1> <p class="mx-auto text-white mt-20 mb-40"> {{ carousel_items.value.text }} </p> </div> </div> </div> </section> </div> {% endfor %} <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> -
How to start a background thread on django to run everytime is launched and if some conditions are fullfilled?
I'm facing this situation: I have an app backend on Django that process the data of the app. In certain cases the users are allowed to join a waitlist for doing certain tasks. If the user is going to do a task and there's nobody in the waitlist, it is allowed to do it (it is joined into the waitlist with the status of "doing the task" and redirected in the app to the action screen. But if the user is going to to a task and there are someone in the waitlist it is joined with the status of "waiting". When his turn comes, the backend sends a notification trough Firebase Cloud Messaging for him to do the task and set him in the waitlist as "doing the task". The main problem is that users has time limits to accept his turn in the waitlist, so everytime a user is notified i have to wait for 60 seconds. If that time is over the user is deleted form the waitlist and the next is notified. How can I accomplish this on Django so the users can interact with the app, making petitions through the API and having that running … -
How to make user email unique in Django?
Hi I'm just trying to create a signUp form in Django but not able to make email field unique. Please tell me how to make that email field unique so any other user can't signUp using the same email. class User(models.Model): user_name = models.CharField(max_length=50,unique=True) first_name = models.CharField(max_length=50,blank=False) last_name = models.CharField(max_length=50,blank=False) User_email = models.EmailField(max_length=70,blank=False,unique=True) password = models.CharField(max_length=12,blank=False) -
How to Fast Search with Django Which Supports JSONField?
I'm looking for a fast searching alternative for my postgres jsonfield,I'm storing a large JSON dataset in below web_results JsonField , Using default objects filtering over that field takes a lot of time. I'm looking for any fast alternative to query the results. models.py class Web_Technology(models.Model): web_results = JSONField(blank=True,null=True,default=dict) ### Large dataset web_results field format as follow: {"http://google.com": {"Version": "1.0", "Server": "AkamaiGHost"}} I tried using django elasticsearch dsl for mapping the above field with elasticsearch but that doesn't seem to support jsonfield as described in below thread. https://stackoverflow.com/questions/57866149/jsonfield-workaround-on-elasticsearch-mapperparsingexception If you have any suggestion/alternative/libraries which support above jsonfield for making fast searches across all json objects, Do let me know. -
How do I filter my model within itself twice in Django?
I'm looking for some help with filtering my model twice in Django. This is my current model: class Medarbejder(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(max_length=200) ma = models.IntegerField(help_text="Indtast medarbejderens MA-nummer. (F.eks 123456)") fornavn = models.CharField(max_length=30, help_text="Indtast medarbejderens fornavn.") efternavn = models.CharField(max_length=30, help_text="Indtast medarbejderens efternavn.") holdnavn = models.CharField(max_length=200, null=False, help_text="Indtast medarbejderens hold.") delingnavn = models.ForeignKey('Deling', on_delete=models.CASCADE, null=True) fagnavn = models.ForeignKey('Fag', on_delete=models.CASCADE, null=True) The model is a model for employees (medarbejder). Now I wish to filter the teamname (holdnavn) with distinct, which I have accomplished. The next step is to then filter all the departments (delingnavn) within each teamname (holdnavn). So when I click on one teamname such as "GSU19", then I wish to get a list of all the departments within that teamname only. I can't seem to wrap my head around how to do this? I am able to do it with slug and with pk, but both teamname and department are not a slug or a pk, so I'm abit lost to how to get the value in the url and filter again. This is currently how the URL looks after I click on a specific teamname: http://127.0.0.1:8000/hold/%3CQuerySet%20%5B%7B'delingnavn_id':%202%7D,%20%7B'delingnavn_id':%204%7D,%20%7B'delingnavn_id':%205%7D,%20%7B'delingnavn_id':%203%7D,%20%7B'delingnavn_id':%206%7D,%20%7B'delingnavn_id':%204%7D,%20%7B'delingnavn_id':%202%7D,%20%7B'delingnavn_id':%204%7D,%20%7B'delingnavn_id':%205%7D,%20%7B'delingnavn_id':%205%7D,%20%7B'delingnavn_id':%206%7D,%20%7B'delingnavn_id':%206%7D,%20%7B'delingnavn_id':%202%7D,%20%7B'delingnavn_id':%203%7D,%20%7B'delingnavn_id':%202%7D,%20%7B'delingnavn_id':%203%7D,%20%7B'delingnavn_id':%203%7D%5D%3E/ I'm getting all the department id's in the url..which is not … -
Form not registering on Django Admin
I have two forms on the profile page and when I submit them, it successfully submits the form but is not registering on the admin. What should I do? I've been building this app for over a month already but is stuck at 70%. My models are: class Translate(models.Model): title = models.CharField(max_length=255) body = models.CharField(max_length=10000) class Meta: verbose_name = "translation" verbose_name_plural = "translations" def __str__(self): return self.title class Narrate(models.Model): title = models.CharField(max_length=255) body = models.CharField(max_length=10000) class Meta: verbose_name = "narration" verbose_name_plural = "narrations" def __str__(self): return self.title Now on my views.py, it's structured this way because it has 2 forms on one page. Is it better to used class based views on my situation or function based views? class ProfilePageView(TemplateView): template_name = 'profile.html' def get(self, request, *args, **kwargs): add_narration = NarrateForm(self.request.GET or None) add_translation = TranslateForm(self.request.GET or None) context = self.get_context_data(**kwargs) context['add_narration'] = add_narration context['add_translation'] = add_translation return self.render_to_response(context) class NarrateFormView(FormView): form_class = NarrateForm template_name = 'profile.html' def post(self, request, *args, **kwargs): add_narration = self.form_class(request.POST) add_translation = TranslateForm() if add_narration.is_valid(): add_narration.save() return self.render_to_response( self.get_context_data( success=True ) ) else: return self.render_to_response( self.get_context_data( add_narration=add_narration, ) ) def submittedView(request): return render(request, 'submission.html') class TranslateFormView(FormView): form_class = TranslateForm template_name = 'profile.html' def post(self, request, … -
How to make html call a javascript function from an external js file, in Django environment
I am developing an app with Django. I want an alert windows pops up as soon as the user lands on a certain HTML page. The javascript function that makes the window pop up is called funprova and this function is stored inside a js file called prova.js, at the path static/js/prova.js I want HTML call this function. How do I do that? -
I am new and just installed Python3.7.4 on Windows 10 and tried to check pip -v in cmd but got this error. OSError: [Errno 9] Bad file descriptor[1]
I am using windows 10 and just installed python3.7.4 but when I run pip -v in cmd, it gives me an error OSError: [Errno 9] Bad file descriptor[1]. I also installed conda and run anaconda-navgator but got the exact same error. I am stuck -
(django) define models dynamically for importing different columns of csv files
I want to make web Test Report system using django to display hundreds type of csv files. each csv files have different fields and i have to display all of these csv files . so i want to define new models dynamically when new csv files(test result data)was made and has to be imported to model is there any way to solve this? -
Django Model Issue cant makemigrations
I created three table Person, Movie and Roll. I used table relationship as Onetomany and many-to-many. But when I start makemigrations. It can't take migrations. When I would like to action for makemigrations for my app It give this traceback(I use sqlitedb) RuntimeWarning: Model 'core.movie' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) SystemCheckError: System check identified some issues: ERRORS: core.Movie_writers: (fields.E336) The model is used as an intermediate model by 'core.Movie.writers', but it does not have a foreign key to 'Movie' or 'Person'. But when I removed writes field from Movie table(model). It worked fine. this is my full models.py file class Person(models.Model): first_name = models.CharField(max_length=140) last_name = models.CharField(max_length=140) born = models.DateField() died = models.DateField(null=True, blank=True) class Meta: ordering = ('last_name', 'first_name') def __str__(self): if self.died: return '{}, {} ({}-{})'.format(self.last_name, self.first_name, self.born, self.died) return '{}, {} ({})'.format(self.last_name, self.first_name, self.born) class Movie(models.Model): director = models.ForeignKey(to='Person', on_delete=models.SET_NULL, related_name='directed', null=True, blank=True) writers = models.ManyToManyField(to='Person', related_name='writing_credits', blank=True) actors = models.ManyToManyField(to="Person", through="Role", related_name="acting_credits", blank=True) class Role(models.Model): movie = models.ForeignKey(Movie, on_delete=models.DO_NOTHING) person = models.ForeignKey(Person, on_delete=models.DO_NOTHING) name = models.CharField(max_length=140) def __str__(self): return f"{self.movie.id} {self.person.id} {self.name}" -
Creating a related object in an admin form
First time using the Django's admin framework and it's just overwhelming considering I only want to do a little thing. There is this class: class RefereeAdmin(ImportExportMixin, admin.ModelAdmin): form = autocomplete_light.modelform_factory(Referee, fields='__all__') list_display = ['name', 'player', 'referee_association', 'grade', 'rating', 'matches_by_month'] list_editable = ['rating'] search_fields = ['name', 'player__user__email', 'player__user__first_name', 'player__user__last_name'] view_on_site = True Which seems to be using a dependency, django-autocomplete-light. All I want is to add an Association field to the form and create an AssociationReferee object which takes a name, an association and a referee (the one we are creating). To populate the association select widget I need to access the request object to exclude those associations where the user has no authorization. How do I do all this? -
How to get the filter class or viewset class through model?
I want to find the corresponding filter class or viewset class only through Model. The corresponding Model can be found by filter class or viewset class, but it cannot be reversed. I have a naming of these three, there is a rule, I guess it can be found through the string name of the filter class or viewset class, but it can not be achieved class Manager(models.Model) class ManagerFilter(filters.FilterSet): class Meta: model = Manager fields = {'name': ['exact', 'in', 'startswith']} class ManagerViewSet(viewsets.ModelViewSet): filter_class = ManagerFilter I can only get the Model class, I want to get the corresponding filter class or viewset class according to this Model. -
How can I display a message to the user at a certain time Django
I was wondering how I could display a simple message to the user at the top of their screen at a certain time in Django. I haven't been able to find anything online about this, so I was wondering how I would go about doing this. Would I need to do something with DateTime? What view/model would I include the code in? Thanks for any help you can give :) -
Python web application to monitor and control multiple remote systems
I want to develop web app using python django Purpose- 1 monitor remote system(multiple client)usage in real time and display on web 2. Control remote system (multiple clients )from web to start stop service As far I know I would need socket ,thread. I am new to python and having basic knowledge and very new to web applications.. Appreciate you guidance.. -
django - How to save the uploaded file to a spefic folder specifying a name
I have a form that the user fills, submits and uploads a file with the same ID from the form. There is a table with the user name and the name of the supervisor. (user -supervisor). I want the user uploaded files to be saved in a folder under the name of the supervisor. Is this possible in django? -
Specific data pulled in foor loop
{% for min m %} currently pulls everything as I wanted HOWEVER REQUIREMENTS HAVE CHANGED Code on the home page:- {% for movies in movies %} {{ movies.title}} Tags- {{ movies.tags }} {% endfor %} Models.py I would like to run through the for loop for a specific field then again for another different field. Example :- Heading result one List containing field Tag = result one Heading result two List containing field Tag = result two -
Git command line syntax meaning?
I've created a .gitignore file but I'm not sure if it is working or not. Currently i have this in the gitignore file in the DEMOPROJECT directory *db.* __init__.py And I'm getting this output in the windows command line (venv) C:\..\..\PycharmProjects\WebP1\DEMOPROJECT>git checkout newMast Switched to branch 'newMast' D .gitignore M db.sqlite3 What is the significance of the D and M? -
How to set email field in Django?
Hi I'm making a user model in Django but getting an error regarding to email field class User(models.Model): User_id = models.AutoField(primary_key=True) user_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) User_email = models.EmailField(max_length=70,blank=True) password = models.CharField(max_length=12) The error I am getting is You are trying to add a non-nullable field 'User_id' to user without a default; we can't do that (the database needs something to populate existing rows). -
How to store item based on selected week
I am building an attendance system and i have to capture their attendance every week and compute their final mark attendance. Right now, im not sure what is the best way of implementing it. But below is my current idea: Model.py: studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) wk1 = models.IntegerField(default=0) wk2 = models.IntegerField(default=0) wk3 = models.IntegerField(default=0) attendance = models.IntegerField(default=100) so my current idea is that, when the admin clicks week 1: the attendance of the student should be stored in wk1. Subsequently, if week 2 then store in week2. I am new to django n python so i am not sure how and where to implement the if-else statement. I need your suggestion how can i capture their attendance effectively. My end product is that i shld be able to compute their attendance and export their final mark attendance only. -
How write import code for foreign key used in bulk file imports using django-import-export?
"I'm trying to import data to one of my models, but it's failing because model has foreignKey Id." Same problem I am facing but given solution is not working. Adding foreignKey widget to django-import-export There is no more explanation for 'import' in django-import-export. Thankyou for helping me. -
Django pass family in template inside for cycle
In a simple view I pass a family in template like this: def page(request): family= Author.objects.all() return render(request, "myapp/page.html", {'family':family}) and I render in template like this: {% for item in family %} {{ item.pk }} {% endfor %} But, if I put my family inside a for cycle; for example: def page(request): family = [] for i in range(5): family= Author.objects.filter(name='John')[i] return render(request, "myapp/page.html", {'family':family}) it not render anything in template... Any idea? -
How to delete users information when he logs out from my app?
I am created web app, who output info about user and users friends. But when user logs out from their account on VK.com, my app continues to store information about him. Ideally I would like to remove user information from the template by clicking on the link. I tried to delete 'token' and 'user_id' from sessions, but it did not work. I am assuming need to delete 'code' which i get from SocialAuth view. But i don't know how i can do it, or problem may be something else. Can you help me? from django.shortcuts import render, redirect, reverse from django.views.generic import View import requests # Create your views here. class SocialAuth(View): def get(self, request): if 'token' in request.session: return redirect(reverse('user_detail_url')) return render(request, 'main/index.html') class UserPage(View): def get(self, request): if 'token' not in request.session: url = 'https://oauth.vk.com/access_token?client_id=7******2&client_secret=pNPPZ******9duWSq' \ '&redirect_uri=http://127.0.0.1:8000/social/user_detail/&code={}'.format(request.GET['code']) response_data = requests.get(url).json() token = response_data['access_token'] user_id = response_data['user_id'] request.session['token'] = token request.session['user_id'] = user_id user_data = requests.get(f'https://api.vk.com/method/users.get?userd_id={request.session["user_id"]}' f'&fields=photo_400&access_token={request.session["token"]}&v=5.101').json()['response'][0] friends_data = requests.get(f'https://api.vk.com/method/friends.get?user_ids={request.session["user_id"]}' f'&fields=photo_100&access_token={request.session["token"]}&v=5.101').json()['response']['items'] context = { 'user': user_data, 'friends': friends_data[:5] } return render(request, 'main/user_detail.html', context=context) def log_out(request): del request.session['token'] del request.session['user_id'] return redirect(reverse('authorize_url')) -
Test case not working properly in django?
Here I am writing some TestCase for my two functions but the code is not working.There is no redirect in function view_positions so I did assertEqual(response.status_code,200) but it says AssertionError: 302 != 200 and In case of test_create_position, I am using random username and password to login but I am not getting any error,faliures. It says Ok. What I am doing wrong here? This is my first unit testing so I want to know is this the good way of writing test case in django ? Note:there is no any error in the view.It is working fine urls.py path('add/job/positions/', views.add_jobs_positions, name='add_position'), path('list/job/positions/', views.view_jobs_position, name='view_positions'), views.py def view_jobs_position(request): if not request.user.is_superuser: return redirect('/login/') jobs_positions = Position.objects.all() return render(request, 'organization/view_positions.html', {'positions': jobs_positions}) def add_jobs_positions(request): if not request.user.is_superuser: return redirect('/login/') form = AddPositionForm() if request.method == 'POST': form = AddPositionForm(request.POST) if form.is_valid(): position = form.save() messages.success(request, 'New Position {} created.'.format(position.title)) return redirect('organization:view_positions') return render(request, 'organization/add_positions.html', {'form': form}) tests.py from django.test import TestCase class PositionTestCase(TestCase): def setUp(self): # create admin user for authentication self.admin = get_user_model().objects.create(username='admin',email='admin@admin.com',password='password321',is_superuser=True) self.admin.set_password('password321') self.admin.save() self.position = Position.objects.create(title='Sr.Python Developer') def test_get_all_positions(self): self.client.login(username='admin',password='password321') response = self.client.get(reverse('organization:view_positions')) self.assertEqual(response.status_code,200) self.assertTemplateUsed(response,'organization/view_positions.html') def test_create_position(self): #using random username and password but working as well self.client.login(username='admin564378483', password='12345667889') response … -
How to fix 'NoReverseMatch ' error in Django, Python
I got this error. NoReverseMatch at /reservation/ Reverse for 'reservation_remove' with arguments '('',)' not found. 1 pattern(s) tried: ['reservation/reservation_remove/(?P[0-9]+)/$'] I don't know how to solve it. This is my urls.py of reservation app. from django.urls import path from .import views app_name='reservation' urlpatterns = [ path('add/<int:nursery_id>/', views.add_reservation, name='add_reservation'), path('', views.reservation_detail, name='reservation_detail'), path('reservation_remove/<int:nursery_id>/', views.reservation_remove, name='reservation_remove'), path('full_remove/<int:nursery_id>/', views.full_remove, name='full_remove'), ] This is my views.py from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from .models import City,Nursery from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.contrib.auth.models import Group, User from .forms import SignUpForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, authenticate, logout def index(request): text_var = 'Start!!!' return HttpResponse(text_var) def allCity(request, c_slug=None): c_page = None cities_list = None if c_slug!=None: c_page = get_object_or_404(City,slug=c_slug) cities_list = City.objects.filter(city=c_page) else: cities_list = City.objects.all() paginator = Paginator(cities_list, 6) try: page = int(request.GET.get('page','1')) except: page = 1 try: cities = paginator.page(page) except (EmptyPage,InvalidPage): cities = paginator.page(paginator.num_pages) return render(request,'service/category.html',{'cities':cities}) def allSitting(request, c_slug=None): c_page = None sittings_list = None if c_slug!=None: c_page = get_object_or_404(City,slug=c_slug) sittings_list = Nursery.objects.filter(city=c_page,available=True) else: sittings_list = Nursery.objects.all().filter(available=True) paginator = Paginator(sittings_list, 6) try: page = int(request.GET.get('page','1')) except: page = 1 try: sittings = paginator.page(page) except (EmptyPage,InvalidPage): sittings = paginator.page(paginator.num_pages) return render(request,'service/city.html',{'city':c_page, 'sittings':sittings}) def SittingDetail(request, c_slug, nursery_slug): … -
Passing template variable to parent in Django
I have a number of apps that each have their own intro section. This intro section has quite a few lines of HTML and only a few lines are adjusted for each app (Think title and intro). I would like this intro section to live at the project level (where the navbar template lives), but I can't find a way to pass template variables from the app to the project. All of my apps(about 15) follow this template scheme: app_base.html extends project base.html app_base.html has an {% include %} to pull in app_intro.html all <app_unique_templates>.html that are called <app>/views.py, extend the app_base.html To reiterate, how can I pass a template variable from /views.py to project base.html template using my app template scheme? If I can't use this scheme, can I adjust it in a way that will allow me to accomplish this? Thank you all in advance!