Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use annotate and Case with different field types in Django
I have a model with those field: class ModelA(models.Model): parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.PROTECT, related_name='child') number = models.PositiveIntegerField() text_code = models.CharField(max_length=255, blank=True, null=True) I want to make a query on that model using annotate and Case with those rules: When parent is null it returns the text_code field When parent is not null it returns parent__number field I can make it with SQL in PostgreSQL like: CASE WHEN "ModelA"."parent_id" IS NOT NULL THEN T3."number"**::integer** ELSE "ModelA"."text_code"**::integer** END AS "control_field" But I can't make that with Django ORM. I've tried the following: query = ModelA.objects.all().select_related('parent').annotate( control_field=Case( When(parent_id__isnull=False, then='parent__number'), default='text_code', output_field=IntegerField(), ), ) But when I call query result, it rase the following error: django.db.utils.ProgrammingError: CASE types character varying and integer cannot be matched I know it is an Database error, because the SQL result from django construct doesn't have the ::integer add. CASE WHEN "ModelA"."parent_id" IS NOT NULL THEN T3."number" ELSE "ModelA"."text_code" END AS "control_field" How can I solve this? I'm working with Django 1.11 -
Django delete function using ajax
heres my views.py containing a delete function and templateview def delete_curricula_info(request): curricula_info = request.GET.get('curricula_info') print(curricula_info) if request.is_ajax: CurriculaInfo.objects.get(curricula_info_id=curricula_info).delete() else: pass data = { 'result': 'Successfully Deleted' } return JsonResponse(data) class CurriculumClasses(TemplateView): template_name = 'architect/assignclasses.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AssignClassForm(self.request.GET or None) context['classes'] = Classes.objects.all() context['curricula_infos'] = CurriculaInfo.objects.all() context['course_abbr'] = self.kwargs.get('course_abbr') context['year'] = self.kwargs.get('year') context['semester'] = self.kwargs.get('semester') context['module_abbr'] = self.kwargs.get('module_abbr') context['curricula'] = Curricula.objects.get( course_period__course__course_abbreviation=self.kwargs.get('course_abbr'), module_period__module__module_abbreviation=self.kwargs.get('module_abbr'), course_period__period__academic_year=self.kwargs.get('year'), course_period__period__semester=self.kwargs.get('semester')).pk return context heres my urls.py for both my views path('courses/<str:course_abbr>/<str:module_abbr>/<int:year>/<int:semester>/classes/', views.CurriculumClasses.as_view(), name='curriculum_classes'), path('ajax/delete-curricula-info', views.delete_curricula_info, name='delete_curricula_info') heres my template containing the html list elements and the javascript for ajax: <ul class="list-group t20"> {% for curricula_info in curricula_infos %} <a href="{% url 'delete_curricula_info' %}"> <li class="list-group-item" id="delete_curricula_info"><b>{{ curricula_info.classes }}</b> taught by: <b>{{ curricula_info.designation }}</b></li> </a> {% endfor %} </ul> <script> $('#delete_curricula_info').click(function () { let curricula_info = $("#{{ curricula_info.curricula_info_id }}").val();; $.ajax({ url: '{% url 'delete_curricula_info' %}', data: { 'curricula_info': curricula_info }, dataType: 'json', success: function (data) { swal({ title: data.result, toast: true, position: 'top-end', type: 'success', showConfirmButton: false, allowEscapeKey: false, allowOutsideClick: false, backdrop: false, timer: 1500, }) }, error: function () { swal({ title: "Error", toast: true, position: 'top-end', type: 'error', showConfirmButton: false, allowEscapeKey: false, allowOutsideClick: false, backdrop: false, timer: 1500, }) } … -
Django-Cms and Django
I recently created a project in Django but my host provides me only Django-Cms. The problem here is that I don't even know what Django-Cms is, so I need a small guide on how can I convert my django project to Django-cms. -
How to add an extra second to datetime.time object in python 3?
I am supposed to add an extra second to the field end_time which is of type . I am not able to add an extra second to the time, for example the time is 10:34:45 and I want to make the time as 10:34:46 then using timedelta function I am not able to add the second nor can I convert this object to datetime.datetime object. -
Django ORM: window function with subsequent filtering
Answering this question, I found out that window functions are not allowed to combine with filter (technically, they are, but filter clause affects the window). There is a hint to wrap window function in an inner query, so that final SQL looks like this (as I understand): SELECT * FROM ( SELECT *, *window_function* FROM TABLE) WHERE *filtering_conditions* The question is: how can I write this query with Django ORM? -
Unit test for order in queryset in admin.py
I made solution in django 1.11, in admin - show on the top of the list in admin panel upcomming events in 2 months (60 days). Rest (also upcomming but for example for 3 months - 90 days) show below. I would like to test my solution so I wrote unit test. But when I'm printing objects is in this order: Event title 1, Event title 2, Event title 3 and should be: Event title 1, Event title 3, Event title 2. I don't know where I made mistake. Here is queryset in admin.py def get_queryset(self, request): next_two_months = datetime.today() + timedelta(days=60) not_three_months = datetime.today() + timedelta(days=90) qs = super(EventAdmin, self).get_queryset(request) next_two_months_events_list = qs.filter(event_from__gte=next_two_months, event_from__lte=not_three_months) rest_events_list = qs.filter(date__lte=datetime.today()).order_by('event_from') return next_two_months_events_list | rest_events_list Here is my test code: def test_queryset_events_list(self): self.client.login(**self._get_superuser_data()) factories.EventFactory.create(title='Event title 1', date=date(2018, 7, 24), event_from=datetime(2018, 8, 22, 10, 0, 0, 0), event_to=datetime(2018, 8, 24, 10, 0, 0, 0)) factories.EventFactory.create(title='Event title 2', date=date(2018, 7, 24), event_from=datetime(2019, 7, 24, 10, 0, 0, 0), event_to=datetime(2019, 7, 29, 10, 0, 0, 0)) factories.EventFactory.create(title='Event title 3', date=date(2018, 7, 24), event_from=datetime(2019, 2, 22, 10, 0, 0, 0), event_to=datetime(2019, 2, 24, 10, 0, 0, 0)) url = reverse('admin:events_event_changelist') response = self.client.get(url) print(models.Event.objects.all()[0]) print(models.Event.objects.all()[1]) print(models.Event.objects.all()[2]) self.assertEquals(models.Event.objects.count(), … -
Django Form test with request.POST & request.FILE
I have problem testing form, it wont accept file upload even I tried many ways, it just returns error that file upload field can't be empty: AssertionError: False is not true : <ul class="errorlist"><li>file<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Test.py: def test_applicant_form(self): placements = Position.objects.filter(published=True)[0] client = Client() file = File(open('root/static/applications/file.pdf', 'rb')) data_set = {'name': 'Caleb', 'surname': 'Dvorszky', 'phone_number': '+1963124575', 'city': 'Kansas City', 'country': 'United States', 'message': 'Would like to be there', 'file':file} form = ApplicantForm(data=data_set) self.assertTrue(form.is_valid(), form.errors) even tried and: response = client.post(placements.get_absolute_url,data=data_set, content_type='multipart/form-data') And still doesnt work. Here is forms.py class ApplicantForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'})) surname = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'})) phone_number = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'})) city = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'})) country = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'})) message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control form-control-lg'})) file = forms.FileField(widget=forms.FileInput()) class Meta: model = Candidate exclude = ['position', 'seen'] models.py This is model that need to be saved when form is filled with data class Applicant(models.Model): date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) surname = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) city = models.CharField(max_length=100) country = models.CharField(max_length=100) position = models.ForeignKey( Position, on_delete=models.CASCADE, related_name='applicants') cover_letter = models.TextField() file = models.FileField(upload_to='files/applications') seen = models.BooleanField(default=False, editable=False) ADMIN_DISPLAY = ['get_name', 'position', 'city', 'country', 'get_file', 'date'] def get_name(self): return "%s %s" % … -
MSSQL server 2013 Built in method which Returns the location point of the Earth given its latitude and longitude
I'm new in MSSQL server, I've changed my db from postgres to mssql server 2013. Prior I have used raw query in my Django(python) application and after changing my db to mssql, the buit in function of postgres does not exits in mssql sevrer. So is there any buitin function in mssql server similar to ll_to_earth and earth_distance. My GenericViewSet in django, in which I have added raw query with ORM def list(self, request): '''docstring''' params = request.data distance_range = params['range'] * 1609.34 if 'range' in params and params['range'] else 2 * 1609.34 queryset = ValetAt.objects.raw(''' SELECT valetat.id, earth_distance(ll_to_earth({},{}), ll_to_earth(valetat.latitude, valetat.longitude)) as distance FROM valetat WHERE earth_box(ll_to_earth({},{}),{}) @> ll_to_earth(valetat.latitude, valetat.longitude) ORDER BY distance ASC; '''.format(params["latitude"], params["longitude"], params["latitude"], params["longitude"], distance_range)) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) -
Django: Maintaining a counter in a field (race condition)
I have a model similar to this example class Foo(models.Model): a = models.ForeignKey(...) number = models.IntegerField() @transaction.atomic def save(self, commit=True): if self.pk is None: current_max = ( Foo.objects .filter(a=self.a) .order_by('-number') .first() ) current_max = 0 if current_max is None else current_max.number self.number = current_max + 1 return super().save(commit) The idea is that for each a, there will be a series of Foos numbered from 1 and then onwards. The issue is that, even though we have @transaction.atomic, there is a race condition, because the transaction isolation level that Django expects will allow the transactions to run simultaneously, i.e. A -> Get max -> 42 B -> Get max -> 42 A -> Set max + 1 A -> save B -> Set max + 1 B -> save Both will be 43 So how would I go about solving that? Is there a way to atomically setting the counter so I don't get the race condition between retrieving the current max and inserting the new value? This question is similar to this one, but different enough that that question did not provide an answer to my specific example -
Django and owl carousel public slider on 1 month
I have project on django==1.11.2 i need publish slider page only for a certain period of time.How can i add this function in admin panel, for example only on 1 month. When 1 month past page will deletes automatically. -
how to customize validation in django admin panel for list_editable
I want to make a validation like, 'at least 2 fields needed to filled among 6 fields from the form' in list view page when updating the table with the 'Save' button below. In my admin.py I have register MyCustomAdmin like following, class MyCustomAdmin(admin.ModelAdmin): list_display= ('id', 'created_at', 'question1', 'answer1', 'question2', 'answer2', 'question3', 'answer3') search_fields = ('question1', 'answer1', 'question2', 'answer2', 'question3', 'answer3') list_editable = ('question1', 'answer1', 'question2', 'answer2', 'question3', 'answer3') actions = None list_per_page = 10 list_display_links = None contributor_site.register(ModelClass, MyCustomAdmin) Now, I was trying a validation that, minimum 2 fields must be filled, otherwise form will not be submitted, some alert text/ validation error will be shown up.(like if question1, answer1, question2, answer2, question3, answer3 all are blank it'll raise an error text, but if any 2 of those fields are filled, form will be submitted successfully) Can anyone help me regarding this please or any way, how can I achieve my required validation! -
How do I specify filters for bleach - python
I would like to not convert '&' and keep it as it is while sanitizing a text. Currently, it's converted to "&amp" import bleach bleach.clean('&') Out[6]: u'&amp;' -
edit PostgreSQL database from django
i've created my database in postgresql using models in django . Now i need to add some columns in my tables ,so i edited my models but it keeps showing me errors in my admin interface -
Passing information between web pages in Django
I have an Image Gallery System where I'm building a feature to edit the attributes of an uploaded image. @login_required def edit(request): if request.method == 'POST': ZSN = request.POST['ZSN'] ZSN = 'images/' + ZSN + '.' image = Images.objects.filter(file__startswith=ZSN) if image: return HttpResponseRedirect('/home/photo-edit', {'image':image}) else: return HttpResponse("Invalid ZSN.") else: return render(request, 'cms/edit.html') This is my edit method in views.py. Notice that I am getting the image object as the image whose attributes has to be edited. If the image is found then I'm redirecting to home/photo-edit where I want to display a HTML page containing a form with image attributes, pre-filled with existing attributes. My views.py method for home/photo-edit/ URL is @login_required def photoedit(request): return render(request, 'cms/photo-edit.html', {'image':image}) But image here isn't getting recognised even though I am sending it from home/edit to home/photo-edit. How do I do this? Is he syntax wrong? -
How to get this function using Django in building a website?
python 2.7 Django 1.11.14 win7 I want to build a Django form submission site. Upon form submitted by user, the backend compare the data X with (A+B),(C+D),(E+F).....in SQLite database, if X agrees with A in(A+B), A+B should be passed as parameters to an .exe file, to generate a zip file and return a site with an url link to the zip for downloading. -
Django-parler: type object 'BookImage' has no attribute '_parler_meta'
This error is raised by django-parler when I'm trying to add a new Book using django admin interface. models.py from django.db import models from django.urls import reverse from isbn_field import ISBNField from django.core.validators import MinValueValidator from parler.models import TranslatableModel, TranslatedFields class Genre(TranslatableModel): translations = TranslatedFields( title=models.CharField(max_length=200, db_index=True), slug=models.SlugField(max_length=200, db_index=True, unique=True, help_text='Unique value for book page URL, created from name.'), description=models.TextField(blank=True, db_index=True), ) class Meta: db_table = 'genres' verbose_name_plural = 'Genres' def __str__(self): return self.title def get_absolute_url(self): return reverse('bookstore:book_list_by_genre', args=[self.slug]) class Book(TranslatableModel): translations = TranslatedFields( title=models.CharField(max_length=200, db_index=True), slug=models.SlugField(max_length=200, db_index=True, unique=True), author=models.CharField(max_length=100, db_index=True, blank=True, null=True, default=None), edition_language=models.CharField(max_length=100, db_index=True, blank=True, null=True, default=None), description=models.TextField(blank=True, db_index=True), binding=models.CharField(max_length=100, db_index=True, blank=True, null=True, default=None), ) genres = models.ManyToManyField(Genre, related_name='books', default=None, blank=True) isbn = ISBNField(unique=True, blank=True, null=True, help_text='ISBN is a ten or thirteen digit number used to ' 'identify books and book-like resources.') price = models.DecimalField(max_digits=9, decimal_places=2, default=0.00, validators=[MinValueValidator(0.00)]) old_price = models.DecimalField(max_digits=9, decimal_places=2, default=0.00, validators=[MinValueValidator(0.00)]) discount = models.DecimalField(max_digits=4, decimal_places=2, default=0, max_length=4) quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)]) publisher = models.CharField(max_length=100, blank=True, null=True, default=None) pub_year = models.CharField(max_length=4, blank=True, null=True, default=None) bestseller = models.BooleanField(default=False) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'books' ordering = ['-created'] def __str__(self): return self.title def save(self, *args, **kwargs): if self.discount == 0 and … -
How to decode celery message in SQS
Some of celery tasks in sqs are pending forever, I want to read those messages (tasks) before deleting. On going to sqs console, I am able to see the encoded message I tried decoding it with value = base64.b64decode(value.encode('utf-8')).decode('utf-8') This gives me dict dump with keys ['body', 'headers', 'content-type', 'properties', 'content-encoding'] In this dict body lookes like encoded I tried to decode it with same value = base64.b64decode(value.encode('utf-8')).decode('utf-8') but it gives error saying UnicodeDecodeError: 'utf8' codec can't decode byte 0x87 in position 1: invalid start byte Am I missing something? How to decode this messages? Is there is any way to decode it? -
page with unique url and users content per user
I'm trying to build a app in which every user has his own database content, but on one page/url some (chosen) database content is listed and publicly visible. I did a lot of research, but cannot come up with the logic how this works. I have a username in the URL, but when I change it to other users names, the content is not changing... What step do I miss here? views.py def public_view(request, username): if request.user.is_authenticated(): info = Profile.objects.filter(user=request.user) instance = Parent.objects.filter(user=request.user) childs = Child.objects.filter(user=request.user) u = MyUser.objects.get(username=username) context = { 'info': info, 'instance': instance, 'childs': childs, 'u': u, } return render(request, 'public/public_home.html', context) else: raise Http404 urls.py from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^user/(?P<username>\w+)/$', views.public_view, name='public_view'), ] -
Django: how to have a while loop that runs in the background process?
How would I be able to use a while loop in the background process of my django project? I want my project to run a while loop even when the web app is not on. How would I be able to do that? Command Line management? or Celery? or Cron job? Thanks in advance. -
Django 2.1 View Permission
The Django Doc states that the new View Permission is added to Django 2.1 but without further clarifications on how this will be used especially on the Django Admin Site. It is my understanding this will be kind of ReadOnly Permission, but I will appreciate more clarifications from any one with better understanding on this new permission and its behavior on the Admin Site -
Remove 'Delete selected model' button from related model fields in Django admin form
In my models I have Document model with foreign key to the Library model. When I am in Django admin site I want to disable editing and deleting Library instances when I am creating new Document. What I tried was to remove delete and edit permissions by subclassing django.contrib.admin.ModelAdmin and removing change/delete permissions @admin.register(Library) class LibraryAdmin(admin.ModelAdmin): def has_delete_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return False But this approach blocks possibility of editing and removing Libraries entirely, which is not what I want. Is there a way to disable these actions only in model edit form? -
Django auth and import auth.User
Hi i follow djangogirls tutorial for learning django in the tutorial they use author = models.ForeignKey('auth.User', on_delete=models.CASCADE) But they import nothing for auth.User Why? i see in many tutorials this code: from django.contrib.auth.models import User whats diffrent beetween calling without import and calling with import Thanks. -
Django function redirects back to class
I am trying to get it so anytime my function 'delete_curricula_info' is activated it then redirects to 'CurriculumClasses' url class CurriculumClasses(TemplateView): template_name = 'architect/assignclasses.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AssignClassForm(self.request.GET or None) context['classes'] = Classes.objects.all() context['curricula_infos'] = CurriculaInfo.objects.all() context['course_abbr'] = self.kwargs.get('course_abbr') context['year'] = self.kwargs.get('year') context['semester'] = self.kwargs.get('semester') context['module_abbr'] = self.kwargs.get('module_abbr') context['curricula'] = Curricula.objects.get( course_period__course__course_abbreviation=self.kwargs.get('course_abbr'), module_period__module__module_abbreviation=self.kwargs.get('module_abbr'), course_period__period__academic_year=self.kwargs.get('year'), course_period__period__semester=self.kwargs.get('semester')).pk return context def delete_curricula_info(request, pk): curricula_info = get_object_or_404(CurriculaInfo, pk=pk) curricula_info.delete() return redirect('curriculum_classes') Heres my urls.py path('courses/<str:course_abbr>/<str:module_abbr>/<int:year>/<int:semester>/classes/', views.CurriculumClasses.as_view(), name='curriculum_classes'), path('delete-curricula-info/<int:pk>/', views.delete_curricula_info, name='delete_curricula_info') The url for my 'CurriculumClasses' is using a dynamic one so i could not hardcode the url to the return redirect of my function. So how do i redirect as my current method does not work. Thanks. -
How can I create a Django REST Framework API that connects to an already existing MySQL tables instead of creating them through models.py
instead of this i need to take data directly from table in db i tried using inspectdb but i'm not getting response in the webpage class Snippet(models.Model): created =models.DateTimeFiled(auto_now_add=True) title=models.CharField(max_length=100,blank=True,default='0') code=models.TextFiled() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python') style = models.CharField(choices=STYLE_CHOICES, default='friendly') class Meta: ordering = ('created',) -
Editing the values while changing Django model field type
I have a field in my Django model: state = models.BooleanField(default=False) I want to change the field type to: STATUS_CHOICES = ( (Enabled, 'Enabled'), (Disabled, 'Disabled'), (PENDING, 'Pending'), ) models.CharField(max_length=8, choices=STATUS_CHOICES, default=Pending) Currently there is content in my model table with boolean values (1 or 0). How can I migrate this change and also transforming the existing values 1 to Enabled and 0 to Disabled?