Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid my website to get weird looking when run on a phone
I am currently working on a django website. Most of the people who will use my website will be using it on their phone. My website works perfectly on my laptop, but it gets weird looking on the phone and everything gets crammed up, especially on phone. How do I make it so that it works properly on all devices? -
is there a way to make user allow them to recover their password without going into admin panel?
I am using Django. I give an option to all public to create their account using html template made for user to login or signup but I am unable to make a layout along with function to reset or recover their password without using Django Admin panel. is there any option? -
Can't add comment with Django forms
I am making an ed-tech app and I want to add comment form for each module in the app. But whenever I try to submit the form it returns 'This page isn’t working' after the submission, and I have tried everything to figure it out, but I couldn't. Here is my code. models.py class Module(models.Model): course = models.ForeignKey(Course, related_name='modules', on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True) comment = RichTextField() order = OrderField(blank=True, for_fields=['course']) class Meta: ordering = ['order'] def __str__(self): return '{}. {}'.format(self.order, self.title) class Course(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='courses_joined', blank=True) class Meta: ordering = ('-created',) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Course, self).save(*args, **kwargs) def average_rating(self): # all_ratings = map(lambda x: x.rating, self.reviews.all()) # return np.mean(all_ratings) return self.reviews.aggregate(Avg('rating'))['rating__avg'] def get_absolute_url(self): return f'/course/{self.slug}/{self.id}/{self.owner.username}' def __str__(self): return self.title views.py class StudentCourseDetailView(DetailView): model = Course template_name = 'students/course/detail.html' def get_queryset(self): qs = super().get_queryset() return qs.filter(students__in=[self.request.user]) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['review_form'] = ModuleCommentForm() # get course object course = self.get_object() if 'module_id' in self.kwargs: context['module'] = course.modules.get(id=self.kwargs['module_id']) else: context['module'] = course.modules.all()[0] return context def … -
DJANGO how to add item to cart? (simple django shop)
I try to build simply Django shop as a code practice. I was wondering how to solve issue of adding items to cart. I must say that i'm interested in simplest solutions since i would like to practice basics before advanced techniques. Thus, i would like to use cart as a model and sth like adding items to query. Please find my code below: models.py: class Product(models.Model): name = models.CharField(max_length=64, db_index=True) shape = models.IntegerField(choices=SHAPE) material = models.IntegerField(choices=MATERIALS) price = models.DecimalField(max_digits=5, decimal_places=2) class User(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) class Cart(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) products = models.ManyToManyField(Product) quantity = models.IntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class ProductsListView(View): def get(self,request): products, search_form = self.search_product(request) order = request.GET.get('order', 'price') products = products.order_by(order) return render(request, 'shop.html', {'products':products, 'search_form':search_form}) def search_product(self, request): search_form = FilterProductForm(request.GET) search_form.is_valid() shape = search_form.cleaned_data.get('shape') material = search_form.cleaned_data.get('material') queryset = Product.objects.all() filters = Q() if shape: filters.add(Q(shape__in=shape), Q.AND) if material: filters.add(Q(material__in=material), Q.OR) return queryset.filter(filters), search_form def product_detail(request, id): product = Product.objects.get(id=id) return render(request, 'detail.html', {'product':product}) I would appreciate your help and advices since i have no idea how to move forward. -
Django tests, verify that a Profile is automatically created
thanks in advance, How could I verify that a profile is automatically created after a user creation threw a test? I've searched in the TestCase docs but found nothing but i'm sure I'm missing something really obvious. from django.test import TestCase from django.contrib.auth import get_user_model from users.models import Profile class test_user_creation(TestCase): def test_create_user(self): User = get_user_model() new_user = User.objects.create_user( username="New_user", email="New_user@user.com", date_of_birth="2002-12-23") self.assertEqual(new_user.username, "New_user") self.assertEqual(new_user.email, "New_user@user.com") self.assertEqual(new_user.date_of_birth, "2002-12-23") self.assertIs(new_user.is_admin, False) self.assertIs(new_user.is_staff, False) self.assertEqual( new_user.profile, "New_user Profile") The last one is the one i'm asking about, it's working this way but how could i do it without refering to the string returned by the Profile class ? My Profile class class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' -
Django template rendering not giving expected results
I am rendering data from my views into my template, as follows: <tbody> {% for item in lyrics %} <tr class='lyrics-table'> <td>{{item}}</td> <td> {% if item in user_flash %} <p>{{flash}}</p> {% else %} <p>xxx</p> {% endif %} </td> {{item}} works as expected, but {{flash}} only gives the same value for every row, instead of the relevant value. My views are as follows: class SongVocab(LoginRequiredMixin, generic.DetailView): model= models.Song template_name = 'videos/song_vocab.html' context_object_name = 'song' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) from pymystem3 import Mystem m = Mystem() user_flash = Flashcard.objects.filter(owner=self.request.user).values_list('question', flat=True) lyrics_list = models.Song.objects.get().lyrics_as_list() user_flash_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(user_flash))] user_flash_clean = [w for w in user_flash_ if w.strip()] ##removes empty strings lyrics_list_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(lyrics_list))] lyrics_list_clean = [w for w in lyrics_list_ if len(w.strip())] user_word = list(set(user_flash_clean) & set(lyrics_list_clean)) import icu # PyICU def sorted_strings(strings, locale=None): if locale is None: return sorted(strings) collator = icu.Collator.createInstance(icu.Locale(locale)) return sorted(strings, key=collator.getSortKey) context['percent_known'] = ((len(user_word))/(len(set(lyrics_list_clean))))*100 context['lyrics'] = sorted_strings(set(lyrics_list_clean),"ru_RU.UTF8") context['user_flash'] = user_flash_clean for word in user_word: flash = Flashcard.objects.get(owner=self.request.user, question=word) context['flash'] = flash.answer return context I thought that using the for loop would let me get flash.answer for all words in user_word. In the example … -
How to Response PDF and/or ZIP File from Django Rest Framework?
I have a Django Rest Framework API. I have a petition where I send a file in the response, can be PDF or ZIP files. But any of these working. Mi petition is: @api_view(['GET', 'POST']) def getLabels(request,): html = render_to_string( template_name='labels.html', context={}) response = HttpResponse(content_type="application/pdf") response['Content-Disposition'] = "inline; filename=etiqueta.pdf" font_config = FontConfiguration() pdf = HTML(string=html).write_pdf(response, font_config=font_config) if api: r = {'file':pdf,'type':'pdf'} return Response(r, status=status.HTTP_200_OK) Otherwise, if I have two or more labels, I create a Zip: pdf = HTML(string=html).write_pdf(font_config=font_config) files.append((f, pdf)) full_zip_in_memory = generate_zip(files) if api: r = {'file':full_zip_in_memory,'type':'zip'} return Response(r, status=status.HTTP_200_OK) I have some errors: When I response a ZIP: 'utf-8' codec can't decode byte 0xdb in position 12: invalid continuation byte When I response a PDF it answer me that it is null or Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` I have ridden documentation and request, but I did not find the correct way to answer it in a API. Anyway, the problem can be in the files, accordign to erros, but if I try to get it in Django URls, its working correctly. -
FİND RELATED ALL WORDS FROM INPUT BEAUTIFULSOUP
i started to learn BeautifulSoup and i try to making a web application that have a URL and keyword inputs and get request from form. That the point here, i want to search a keyword and result should be related to the my keyword. I tried various types of find methods like findNext but is only resulting next one of the word. How can i find all related tags via my keyword? That is the my code here: `if request.method == "POST": keyword = request.POST['keyword'] url = request.POST['url'] contents = requests.get(url) page_html = contents.text pagesoup = bs4(page_html, 'html.parser') for mykeyword in pagesoup.find_all( ['td', 'a', 'tr', 'p', 'div'], text=re.compile(keyword)): outfile = open('C:/Users/DC/Desktop/Words.txt', 'w') outfile.write(mykeyword.text) return render(request, 'BeatifulSoup.html', {}) Here i tried to make something if i get result depend on my keyword but it's return null value. -
In Django override a field in child class from the parent class
I am doing Project in Django Rest Framework, this Project is mostly completed , but suddenly the requirement come from the client. Their requirement is Worker will also be able to Signup as a customer , and Customer will also be able to signup as a Worker, They Both are different Apps. Now the problem is my Database style is implemented in a different style , I don't have a seperate table for the worker, Now im stuck what should I do, Here Below is my DB Structure Class User(AbstractUser): username email first_name last_name .... ... Class Worker(User): weight job_category Now if the worker mail is suppose (dudeworker@gmail.com) , and now they want to signup as a Customer (dudeworker@gmail.com), They will get an error , as Expected , Email is Already exist, Now if seperate The worker Table, Then I have to perform lots of changes in the Code. What is the better solution for this ? By overriding the email field in Worker table , giving the error -
Cannot compute Sum in django
I want to set a condition to my Sum function inside annotate, and I tried to use Case When but it didn't work in my case this is my models.py class MyModel(models.Model): name = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.IntegerField() price = models.IntegerField() class Prodcut(models.Model): name = models.CharField(max_lenth=20) cost = models.IntegerField() price = models.IntegerField() I want to something like this total = F('price')*F('order') base = (F(name__cost')+F('name__price')) * F('order') if total> base: income = Sum(F('total') - F('base')) I tried this MyModel.objects.values('name__name').annotate(total=(Sum(F('price') * F('order'),output_field=IntegerField())), base=(Sum((F('name__price')+F('name__cost'))*F('order'),output_field=IntegerField()) ), income=Sum( Case(When(total__gt=F('base') , then=Sum(F('total') - F('base'))),default=0),output_field=IntegerField()),) but this raise this error: Cannot compute Sum('<CombinedExpression: F(total) - F(base)>'): '<CombinedExpression: F(total) - F(base)>' is an aggregate and this MyModel.objects.values('name__name').annotate(total=(Sum(F('price') * F('order'),output_field=IntegerField())), base=(Sum((F('name__price')+F('name__cost'))*F('order'),output_field=IntegerField()) ), income=Sum( Case(When(total__gt=F('base') , then=F('total') - F('base')),default=0),output_field=IntegerField()),).annotate(income_new=(Sum('income'))) raised this error Cannot compute Sum('<Case: CASE WHEN <Q: (AND: ('total__gt', F(base)))> THEN <CombinedExpression: F(total) - F(base)>, ELSE Value(0)>'): '<Case: CASE WHEN <Q: (AND: ('total__gt', F(base)))> THEN <CombinedExpression: F(total) - F(base)>, ELSE Value(0)>' is an aggregate I don't want to use .filter(income__gt=0) because it stops quantity from counting and I don't want to count income to those products which loss its sold for example i make a post on MyModel(name=mouse ,order=2,price=20) and in my Product model i have these information … -
How to ensure form data is posted correctly in Django
I am populating Django formset with data from Ajax callback (barring a few form elements which are to be filled manually by the user). I am trying to automate filling most of the form elements to eliminate error. However, while "POST"ing, the data does not get saved in respective models. Using the same process I am able to create records (where data is filled (manually) by the user). Can't find out where I am going wrong? models.py: class mappedTargModel(models.Model): mapper_id = models.AutoField(primary_key=True, verbose_name='Map ID') mapper_name = models.CharField(max_length=50, verbose_name='Mapper name') mapper_target_model = models.CharField(max_length=100, verbose_name='Target Table') mapper_long_text = models.CharField(max_length=250, null=True, blank=True, verbose_name='Long Text') class mappedTargFields(models.Model): mapper_item = models.AutoField(primary_key=True, verbose_name='Item Number') mapper_header = models.ForeignKey(mappedTargModel, related_name='mapper_hdr_tab', on_delete=models.CASCADE, verbose_name='Mapper') mapped_field = models.CharField(max_length=100, verbose_name='Target Field') mapped_field_verb_name = models.CharField(max_length=100, verbose_name='Name') mapped_field_col_name = models.CharField(max_length=25, verbose_name='Col Name') mapped_field_fk_table = models.CharField(max_length=100, verbose_name='Field Related To') views.py def MapperDataImportConstruct(request, object_id=False): template = "map/mapper_construct.html" if object_id: qs_targ_model_form = mappedTargModel.objects.get(pk=object_id) else: qs_targ_model_form = mappedTargModel() target_field_formset = CreateMappedTargFieldsFormset() if request.method == 'POST': new_qs_targ_model_form = mappedTargModelForm(data=request.POST, instance=qs_targ_model_form) if new_qs_targ_model_form.is_valid(): qs_targ_model_form = new_qs_targ_model_form.save(commit=False) target_field_formset = CreateMappedTargFieldsFormset(request.POST, instance=qs_targ_model_form) if target_field_formset.is_valid(): qs_targ_model_form.save() target_field_formset.save() else: new_qs_targ_model_form = mappedTargModelForm() target_field_formset = CreateMappedTargFieldsFormset(instance=qs_targ_model_form) context = { 'target_model_form': new_qs_targ_model_form, 'target_field_formset': target_field_formset, # .... (context objects for getting values from Ajax callback) # .... … -
How csrf token provided by django secures our webapp?
I know that when we send post requests csrf token is to be included, but what it does i don't know except that it provides security enhancement to our website. Pls someone tell how it works or how does it help in solving security concerns of webapps -
How to iterate over an abstract class's objects in a Django template?
I have an abstract class Item and multiple product classes which inherit from Item. In my template, I want a for loop of every class that inherits from Item, but I don't want to rewrite a for loop for every class that inherits from Item. -
How to list all user groups in Django?
I am trying to list users and at the same time with the groups added to each one of them. How can I do this? Below is an example I'm trying to do. Thank you. class UserList(ListAPIView): pagination_class = LimitOffsetPagination serializer_class = serializerUser queryset = User.objects.all() def get_queryset(self): users = User.objects.selected_related('group').all() return users -
Django REST Framework seemingly ignoring field
I'm coming to you, because I think I'm going insane (or maybe I'm just a noob at this), but I'm trying to implement a lobby system in Django, which we can use for a game. For testing purposes, I have set up a private project with Django and threw the Django REST Framework into it. Inside, I have defined a few models, the main one being a Lobby. class Lobby(models.Model): """ We are no lobbyists! """ name = models.CharField(max_length=100) creation_date = models.DateTimeField() creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_lobbies') password = models.CharField(max_length=128, null=True, default="") players = models.ManyToManyField(User, related_name="lobbies") session = models.OneToOneField(LobbySession, on_delete=models.CASCADE, null=True, blank=True, related_name='lobby') Looks pretty simple, is pretty simple. I hooked this model up to a HyperlinkedModelSerializer, which lets it list all fields inside. Players and creators are both realized using PrimaryKeyRelatedFields. Plus the creation_date is filled automatically inside the serializer. The View is a regular ModelViewSet, literally just a few lines long: class LobbyViewSet(RequestLogViewMixin, viewsets.ModelViewSet): """ API endpoint for lobbies """ queryset = Lobby.objects.all().order_by('-creation_date') serializer_class = LobbySerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] Alright, now for the game's code, we serialize a narrowed down class to a JSON string, like this: {"name":"Horsey from code2","creator":1,"session":null,"players":[1]} Sending that to our API endpoint, returns me … -
Count records per day in a Django Model where date is Unix
I'm trying to create a query that counts how many queries per day there were on a certain Django table. I found a bunch of examples about it but none was dealing with Unix data. Here is what my model looks like: class myData(models.Model): user_id = models.IntegerField() user = models.CharField(max_length=150) query = models.CharField(max_length=100) unixtime = models.IntegerField() class Meta: managed = False db_table = 'myData' So the result i'm trying to get is something like: {'27/06/2020': 10, '26/06/2020': 15 ... } The doubt i have is: should i use a raw MYSQL query or should i use Django's ORM? I tried to make it with a raw query, but didn't get the expected output: select FROM_UNIXTIME(`unixtime`, '26.06.2020') as ndate, count(id) as query_count from myData group by ndate But it gave the following output: ndate query_count 26/06/2020 1 26/06/2020 1 26/06/2020 1 26/06/2020 1 .... Can anyone help me out on this? It doesn't make the difference whether the query is made with raw mysql or Django ORM, i just need a simple way to do this -
Does parent template's CSS properties applies to extended child template in Django?
I was making a site with Django in which I was applying CSS properties to an extended template file. The CSS file is imported in parent template and is used in child template. But it isn't showing any changes in child template. Here's my code: .c1 a:hover { background-color: #1D1C1C; color: white; } .theta { position: relative; left: 100px; } {% load static %} <!DOCTYPE html> <!-- Parent File --> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Site</title> <link href="{% static 'css/bootstrap-4.4.1.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'css/style.css' %}" rel="stylesheet" type="text/css"> <!-- <link href="../static/css/bootstrap-4.4.1.css" rel="stylesheet" type="text/css"> --> <!-- <link href="../static/css/style.css" rel="stylesheet" type="text/css"> --> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">Site</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent1" aria-controls="navbarSupportedContent1" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent1"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle text-white" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">A</a> <div class="dropdown-menu c1" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">a</a> <a class="dropdown-item" href="#">b</a> </div> </li> <li class="nav-item"> <a class="nav-link text-white" href="#">B</a> </li> </ul> </div> </nav> {% block content %} {% endblock %} <script src="{% static 'js/jquery-3.4.1.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap-4.4.1.js' %}"></script> <!-- <script … -
how can I get recommendation for registered users in django?
I have a site where students can register and apply request to study and upload their documents and infos, they can have 2 professors recommendations too, I was wondering to get the professors email and send them a link which they fill the recommendation form for the student (without register in site), can anyone give me a hint how to do that? -
I am not able to add attributes in forms.PasswordInput all the other input types like TextInput, EmailInput etc work perfectly fine
I am not able to add attributes in forms.PasswordInput all the other input types like TextInput, EmailInput etc work perfectly fine. There is no error when I run the code but the attributes on password fields on my form doesn't show up. from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class NewUserForm(UserCreationForm): class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'password1', 'password2', ] widgets = { 'username' : forms.TextInput(attrs={'class':"u-full-width", 'id':"user_name", 'placeholder':"uniqueusername"}), 'first_name' : forms.TextInput(attrs={'class':"u-full-width", 'id':"first_name", 'placeholder':"John"}), 'last_name' : forms.TextInput(attrs={'class':"u-full-width", 'id':"last_name", 'placeholder':"Smith"}), 'email' : forms.EmailInput(attrs={'class':"u-full-width", 'id':"email", 'placeholder':"johnsmith@example.com"}), 'password1' : forms.PasswordInput(attrs={'class':"u-full-width", 'id':"password1", 'placeholder':"Password"}), 'password2' : forms.PasswordInput(attrs={'class':"u-full-width", 'id':"password2", 'placeholder':"Confirm Password"}), } Following is a part of my html code, this is inside the form tags <div class="row"> <div class="twelve columns"> <label for="password1">Password</label> {{form.password1}} </div> </div> <div class="row"> <div class="twelve columns"> <label for="password2">Re-Enter Password</label> {{form.password2}} </div> </div> -
Trying to filter by user group using class based view with django-tables2, can't access self.user
I'm trying to use a class based view using django-tables2 to define the table and template returned based on what group the logged in user belongs to. This is my attempt at doing so: class cases(LoginRequiredMixin, SingleTableView): login_url = '/account/login/' if User.objects.filter(pk=self.request.user.id, groups__name='teachers').exists(): model = Graduation table_class = TeachersTable template_name = 'mysite/teachers.html' elif User.objects.filter(pk=self.request.user.id, groups__name='students').exists(): model = Graduation table_class = StudentsTable template_name = 'mysite/students.html' I think the approach is more or less correct (I've only learned about class based views today), but I am unsure how to access the user id. The relevant parts of this view should only be called when a user is logged in (at least I think) because I'm using the LoginRequiredMixin, so 'self' should exist. The answers I have seen addressing this problem say override get_queryset, but I am reluctant to do that as I think that will break django-tables2. What is the best approach in this case to do what I am trying to do? -
How to highlight searched queries in result page by using Function based views?
I'm searching "keyword" in title & content of blog, it returns the result as expected but i want to highlight the searched words. How could i do that? I referred stackoverflow reference but that was implemented in class based views. How could i do it using function based views? views.py: def search(request): query = request.GET.get('user_search_input') if query: results = Post.objects.filter(Q(title__icontains=query) | Q(content__icontains=query)) else: return HttpResponse("Access denied") context={ 'results' : results, 'search_word' : query } return render(request, 'blog/search.html', context) urls.py: path('search/', views.search, name='search'), -
How do i get rid of empty filters in django-filter url path and just leave the ones with an actual value selected?
I'm using django-filters to filter results in my search and when i apply filters it shows all the urls even the ones with no filters applied to them, is there a way to just show only the queries with the filters applied and also if possible show them in human friendly urls especially for foreign key fields which show numbers like http://localhost:8000/?city=1 instead of a human readable value like this http://localhost:8000/?city=Nairobi? here is what are the images and my code. models.py class Employee(models.Model): AVAILABILITY = ( ('Mornings','Mornings'), ('Afternoons','Afternoons'), ('Evenings','Evenings'), ('Nights','Nights'), ('Full-time','Full-time'), ('Part-time','Part-time'), ('Special Occassions','Special Occassions'), ('Emergencies','Emergencies'), ('On-demand','On-demand'), ) EDUCATION = ( ('Primary Level','Primary Level'), ('High School','High School'), ('Tertiary Level','Tertiary Level'), ('Open','Open') ) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,related_name='employee_profile') avatar = models.ImageField( verbose_name='profile picture', upload_to='users/employees/avatars', blank=True, null=True ) address = models.CharField(max_length=500, null=True, blank=False) education_level = models.CharField(choices=EDUCATION, max_length=50, blank=False, default=False) verified = models.BooleanField(null=False, blank=False, default=False) account_active = models.BooleanField(default=True,null=False, blank=False) bio = models.TextField(null=True, blank=False) preferred_work_locations = models.ManyToManyField(City) availability = models.CharField(max_length=100,choices=AVAILABILITY,null=True, blank=False) date_of_birth = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=False) def __str__(self): return self.user.first_name + ' ' + self.user.last_name filter.py class EmployeeFilter(django_filters.FilterSet): AVAILABILITY = ( ('Mornings','Mornings'), ('Afternoons','Afternoons'), ('Evenings','Evenings'), ('Nights','Nights'), ('Full-time','Full-time'), ('Part-time','Part-time'), ('Special Occassions','Special Occassions'), ('Emergencies','Emergencies'), ('On-demand','On-demand'), ) EDUCATION = ( ('Primary Level','Primary Level'), ('High School','High School'), ('Tertiary … -
Django unable to read script in block
I am currently working on a Django project. For one of my applications, I have a 'private_base.html' template, with 2 blocks: 'body_block' and 'js_block'. private_base.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/private_base.css' %}"> <meta charset="utf-8"> <title></title> </head> <body> <div class="sidenav"> <!-- side navbar --> </div> <div class="main"> {% block body_block %} {% endblock %} </div> {% block js_block %} {% endblock %} </body> </html> I am extending this base template into 'search_result.html' search_result.html {% extends 'private_base.html' %} {% block body_block %} <!-- contents --> {% endblock %} {% block js_block %} <script src="{% static "js/group_search.js" %}" type="text/javascript"></script> {% endblock %} When I access the site, I am given the following error message: "TemplateSyntaxError at /group/search_result/ Invalid block tag on line 41: 'static', expected 'endblock'. Did you forget to register or load this tag?" I would like to ask if I am missing something, or doing something wrong that results in Django being unable to read my <script> when within the {% block %} tag, or making Django confused with the tags. I have tried using only one {% block %} tag and placing script within the … -
Apscheduler logging in Django project
I'm using apscheduler in my Django project: from apscheduler.schedulers.background import BackgroundScheduler from updater import test def updateData(): global scheduler scheduler = BackgroundScheduler() scheduler.add_job(test.logJob, 'interval', seconds=10, id='test', replace_existing=True) scheduler.start() And my test.py: import logging def logJob(): logging.basicConfig(filename='updater/log', level=logging.INFO) logging.info('hello') Locally everything is working. But on server (Ubuntu 16, nginx + gunicorn + supervisor) it doesn't (log file is empty). More over, if I change the first file as: def updateData(): global scheduler scheduler = BackgroundScheduler() scheduler.add_job(test.logJob, 'interval', seconds=10, id='test', replace_existing=True) logging.basicConfig(filename='updater/log', level=logging.INFO) logging.info('hello') scheduler.start() It will cause 502 error page on my site. But if I remove filename parameter: logging.basicConfig(level=logging.INFO) web-site will work, but log file is still empty. -
FileNotFoundError inside a celery task
I have a celery task that operate with file from Django model class Something(models.Model): doc = models.FileField() @app.task def operate_with_file(instance_id: int): instance = Something.objects.get(id=instance_id) size = instance.doc.file.size When celery worker run this task i got error FileNotFoundError on string size = instance.doc.file.size. If i call operate_with_file manually from django shell that works fine. File already exists in a model. What wrongs with this?