Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : add CreateView to DetailedView of related model
I am really really new to Django and trying to build a job posting site. I have now hit a hard spot. I want to add the JobsAppliedCreateView inside a JobsDetailedView, so that they show up on the same template and such that when the form from the jobsapplied templated gets saved, the data gets saved in the database. My view looks like this I have tried the include tags but no luck from django.contrib.auth.mixins import PermissionRequiredMixin from django.views.generic.edit import CreateView from django.views.generic import DetailView, ListView from job_post.models import JobPost, JobsApplied class JobsCreateView(PermissionRequiredMixin, CreateView): model = JobPost template_name = 'job_post.html' fields = '__all__' permission_required = 'job_post.view_jobpost' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class JobsDetailView(DetailView): model = JobPost template_name = 'job_post-detail.html' class JobsListView(ListView): model = JobPost template_name = 'job_post-list.html' class JobAppliedCreateView(CreateView): model = JobsApplied template_name = 'job_post_jobapplied.html' fields = '__all__' def form_valid(self, form): form.instance.customuser = self.request.user return super().form_valid(form) -
Create a filter to show objects excluded from the primary queryset
Today I discovered "django-filter" and I wanted to use it to create filters for my Django application. On the home page there is a table displaying all the objects of the "Tasks" model with a status other than "CL" (which corresponds to Closed). I was able to create a filter to sort tasks by location. However I can't create a filter that would display all "Tasks" objects including those with "Closed" status. How can I make this filter? Thank you for your help ! models.py class Task(models.Model): title = models.CharField(null=True, max_length=60) description = models.TextField(blank=True, max_length=5000) location = models.CharField(max_length=7, null=False, choices=LOCATION_CHOICES, default='MAOVHFR') STATUS_CHOICES = ( ('PL', 'Planned'), ('IP', 'In Progress'), ('CL', 'Closed'), ) status = models.CharField(max_length=2, choices=STATUS_CHOICES, default='PL') filters.py from tasks.models import Task import django_filters class TaskFilter(django_filters.FilterSet): location = django_filters.ChoiceFilter(choices=Task.LOCATION_CHOICES) class Meta: model = Task fields = ['location', ] @property def qs(self): parent = super(TaskFilter, self).qs return parent.exclude(status="CL") views.py def index(request): task_list = Task.objects.all() task_filter = TaskFilter(request.GET, queryset=task_list) return render(request, 'tasks/index.html', {'task_list_filtered': task_filter}) index.html( <form method="get"> <div class="col-lg-3"> Location : {% render_field task_list_filtered.form.location class="form-control" %} </div> <button type="submit" class="btn btn-primary pull-right" data-dismiss="modal">Apply filter</button> </form> ... ... ... {% for task in task_list_filtered.qs %} <tr> <td>{{ task.id }}</td> <td>{{ task.title }}</td> </tr> … -
Django Formset issue - POST doesn't seems to work
I'm trying to use django formset for the first time in order to combine both forms on the same page. My form is well displayed but I don't overvome to save data in my database. When I click on submit button, nothing happens. This is my model.py file : class Publication(models.Model): title = models.CharField(max_length=512, verbose_name=_('title'), null=False) category = models.ForeignKey(Category, verbose_name=_('category'), null=False) creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False) modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False) class Meta: verbose_name = _('publication') verbose_name_plural = _('publication') def __str__(self): return f"{self.title}" class Document(models.Model): FORMAT_CHOICES = ( ('pdf', 'pdf'), ('epub', 'epub'), ) format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False) title = models.CharField(max_length=512, verbose_name=_('title'), null=False) publication = models.ForeignKey(Publication, verbose_name=_('publication'), null=False) upload = models.FileField(upload_to='media/', default="") creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False) modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False) class Meta: verbose_name = _('document') verbose_name_plural = _('document') def __str__(self): return f"{self.edqm_id} : {self.title}" My form file is very simple too with defined Formset : class PublicationForm(forms.ModelForm): class Meta: model = Publication fields = ('title', 'category') class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['publication', 'format', 'title', 'upload'] DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1) My view is a bit more complicated : class PublicationCreateUpdateView(EdqmPermissionRequiredMixin, UpdateView): """ Display a form to create or … -
XYZ is an invalid keyword argument for this function
I've defined and created the following model: class Links(models.Model): id = models.AutoField(primary_key=True, unique=True), longlink = models.CharField(max_length=100), shortlink = models.CharField(max_length=15), createdate = models.DateField(default=timezone.now) def __str__(self): return self.longlink My code: from appointments.models import Links def shortlinkgen(): import secrets return secrets.token_urlsafe(4) def DateToday(): from datetime import datetime, date, time now = datetime.now() return now.strftime("%Y-%m-%d") link = Links(longlink='https://mail.google.com/mail/u/0/#inbox/FMfcgxvzKQmmrZMGFJVWvsLlFPxQKhJG', shortlink=shortlinkgen(), createdate=DateToday()) link.save() print(link) I'm getting the error: TypeError Traceback (most recent call last) <ipython-input-2-66d347994058> in <module>() 9 return now.strftime("%Y-%m-%d") 10 ---> 11 link = Links(longlink='https://mail.google.com/mail/u/0/#inbox/FMfcgxvzKQmmrZMGFJVWvsLlFPxQKhJG', shortlink=shortlinkgen(), createdate=DateToday()) 12 link.save() 13 print(link) ~/.local/lib/python3.6/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs) 482 pass 483 for kwarg in kwargs: --> 484 raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) 485 super().__init__() 486 post_init.send(sender=cls, instance=self) TypeError: 'longlink' is an invalid keyword argument for this function What's wrong? -
How can I get Django Absolute url without "www" in domain?
I try to add valid canonical tag to my Django site. So I must add canonical url without query parameter. I find pretty solution, but I have trouble that I could not resolve. My tag is looks like this: {% if request.GET %} <link rel="canonical" href="https://{{ request.get_host }}{{ request.path }}"> {% endif %} This is good solution, but in real site in page with url https://example.com/about-us?page=3 I get this canonical url https://www.example.com/about-us Why i get canonical url with www before site domain This is my ALLOWED_HOST in settings.py: ALLOWED_HOSTS = [ '127.0.0.1', 'www.example.com', 'example.com', 'localhost', ] How can i get valid canonical url without www? -
Django 1.11 python3 syntax error:EOL while scanning string literal in __init__ when migrating manage.py
I have been following Django installation tutorials and I have followed them exactly but when I have been trying to do: python manage.py migrate I get the following error: File "/.../settings/__init__.py", line 1 echo"from .base import * ^ SyntaxError: EOL while scanning string literal My __init__.py file is as follows, created as instructed by the Django documentation: echo "from .base import * from .production import * try: from .local import * except: pass " > __init__.py I am using Python 3.7 and Django 1.11 in a virtual env. I have tried using """ instead of " but it does not fix it. -
Which certification is best for python?
I came across many courses for python, but I want to know that is there any certification for python which is valuable in industry?? -
Django Testing: avoid copied test cases
I have a lot of views which are restricted to the logged in user. For example User1 has access to /cars/1/edit but User2 does not have access to this url. For this reason I need a lot of similar tests for every view but also custom tests for the views. My solution is the following code: class TestPermission: def setUp(self): self.user = Mock(User) self.car = Mock(Car, user=self.user) self.url = self.get_url() def get_url(self): raise NotImplementedError("get_url() is missing") def test_permission_denied(self): other_user = Mock(User) self.client.force_login(other_user) response = self.client.get(self.url) self.assertEqual(response.status_code, 403) class TestHome(TestPermission, TestCase): def get_url(self): return reverse('car:home', kwargs={ 'car': self.car.slug }) # ... custom tests for this view class TestUpdate(TestPermission, TestCase): def get_url(self): return reverse('car:update', kwargs={ 'car': self.car.slug }) # ... custom tests for this view I am not sure if this is the best solutioin or if you should avoid inheritance in tests? -
Exclude Endpoint HTTP methods from Django REST Swagger
Is there a way to hide just some of the methods of an endpoint and not the whole endpoint? (e.g. show the POST method but hide the DELETE one) where I have tried to customize the documentation using the AutoSchema For example an endpoint like router.register(r'audittrial', AuditTrialViewSet, 'AuditTrial') would have the following schema defined class AuditTrialCustomView(AutoSchema): @staticmethod def get_field(name, required, location, schema, description): return coreapi.Field( name=name, required=required, location=location, schema=schema, description=description ) def get_manual_fields(self, path, method): extra_fields = [] if method == 'GET': extra_fields = [ self.get_field("from", False, "query", coreschema.String(), "Date of the start of the Audit Trial"), .... ] return extra_fields Is there any method I would be able to achieve this? -
NoReverseMatch at /post/
I want to create a comment part. I did but there is an error in my detail page. The error is *NoReverseMatch at /post/123/ Reverse for 'blog_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P\d+)/comment/$']* Here is my codes. models.py class BlogComment(models.Model): description = models.TextField(max_length=1000, help_text="Enter comment about blog here.") author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) post_date = models.DateTimeField(auto_now_add=True) blog = models.ForeignKey(Post, on_delete=models.CASCADE) class Meta: ordering = ["post_date"] def __str__(self): len_title = 75 if len(self.description) > len_title: titlestring = self.description[:len_title] + '...' else: titlestring = self.description return titlestring views.py class BlogCommentCreate(LoginRequiredMixin, CreateView): model = BlogComment fields = ['description', ] def get_context_data(self, **kwargs): context = super(BlogCommentCreate, self).get_context_data(**kwargs) context['blog'] = get_object_or_404(Post, pk=self.kwargs['pk']) return context def form_valid(self, form): form.instance.author = self.request.user form.instance.blog = get_object_or_404(Post, pk=self.kwargs['pk']) return super(BlogCommentCreate, self).form_valid(form) def get_success_url(self): return reverse('blog-detail', kwargs={'pk': self.kwargs['pk'], }) urls.py url(r'^post/(?P<pk>\d+)/comment/$', views.BlogCommentCreate.as_view, name='blog_comment'), postcomment_form.html {% extends 'blog/base.html' %} {% block content %} <p>Post your comment for: <a href="{% url 'post_detail' Post.pk %}">{{post.name}}</a></p> <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit" /> </form> {% endblock %} post_detail.html </div> <div style="margin-left:20px;margin-top:20px"> <h4>Comments</h4> {% for comment in blog.blogcomment_set.all %} <hr> <p>{{ comment.author }} ({{ comment.post_date }}) - {{ comment.description }}</p> {% endfor %} <hr> … -
Problem with loading modal forms using django-fm
Based on the example given here: https://github.com/django-fm/django-fm I can not upload successfully the modal window based on the form-view-model .py appropriate file provided. Here is my code in models.py: from django.db import models class Test(models.Model): test_one = models.CharField(max_length=200) test_two = models.CharField(max_length=200) def __str__(self): '''this function returns the name of the instance''' return self.test_one+self.test_two Here is my code in forms.py: from django import forms from .models import Test class TestForm(forms.ModelForm): class Meta: model = Test fields = ['test_one', 'test_two',] Here is my code in views.py: from fm.views import AjaxCreateView from .forms import TestForm from .models import Test class TestCreateView(AjaxCreateView): model = Test form_class = TestForm template_name = 'form_example/test.html' Here is my code in urls.py: from django.contrib import admin from django.conf.urls import url,include from form_example.views import TestCreateView urlpatterns =[ url(r'^create/$',TestCreateView.as_view(),name="test_create"), ] and finally the code in test.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> {% include "fm/modal.html" %} {% block content %}{% endblock %} <a class="fm-create" href="{% url 'test_create' %}" data-fm-head="Creating new User" data-fm-callback="appendWithAlert" > <button class="btn btn-primary btn-sm" type="">Create new User</button></a> <script type="text/javascript"> $(function() { $.fm({debug: true}); }); </script> <script type="text/javascript"> $(function() { $.fm({ debug: true, custom_callbacks: { … -
Python : somebody help me how can I upload pic? /admin [on hold]
https://gist.github.com/atlantis2568/0ff2aa36220e5814683e32037b43073c I am currently studying api. <div id="expansion"> <p> You're seeing this error because you have▁<code>DEBUG▁= True</code> in your Django settings file. display a standard page generated by the handler for this status code </p> </div> </body> </html> The following error occurred and I put models.py and views.py in the currently attached link. Currently, I expect post.photo.save(img_name, File(req.raw)) this code is in trouble. Is there anyone who can help? -
Transaction management in Django - Atomicity
I try to apply atomicity property of transaction management but couldn't figure it out in Django. I have two methods basically, each of them making database operations and I want it to all-or-nothing. Either both will execute successfully or none. How can I be able to rollback send_comment_twitter if second "with transaction.atomic()" block fails? Thanks in advance for your help. @transaction.atomic() @ajax_login_required def send_comment(request, interaction_mention_id): interaction = interaction_object try: with transaction.atomic(): mention, mention_created = send_comment_twitter() # this method returns get_or_create result and does not contain any try/except block except Exception: return error_message try: with transaction.atomic(): interaction.save() message, message_created = Message.objects.get_or_create() except Exception: transaction.set_rollback(True) return error_message return some_thing -
Django Testing: avoid copied test cases
I have a lot of views which are restricted to the logged in user. For example User1 has access to /cars/1/edit but User2 does not have access to this url. For this reason I need a lot of similar tests for every view but also custom tests for the views. My solution is the following code. class TestPermission: def setUp(self): self.user = Mock(User) self.car = Mock(Car, user=self.user) self.url = self.get_url() def get_url(self): raise NotImplementedError("get_url() is missing") def test_permission_denied(self): other_user = Mock(User) self.client.force_login(other_user) response = self.client.get(self.url) self.assertEqual(response.status_code, 403) class TestHome(TestPermission, TestCase): def get_url(self): return reverse('car:home', kwargs={ 'car': self.car.slug }) # ... custom tests for this view class TestUpdate(TestPermission, TestCase): def get_url(self): return reverse('car:update', kwargs={ 'car': self.car.slug }) # ... custom tests for this view I am not sure if this is the best solutioin or if you should avoid inheritance in tests? -
How do I cleanly refer either to the instance or to the initial data, depending on what's provided?
I have a model Report, which is a foreign key for ReportEntry, for which I have a formset. I want to implement the following logic: when a new report is created, a non-adjustable set of entries is automatically created, one for every Customer object (though every individual entry can be adjusted). Obviously, when an existing report is viewed, it should show the entries for which it is a foreign key, and they still cannot be added or deleted. For reference, I'm using django-extra-forms, which provides some wrappers around inline formsets for easier usage (inlines[0] below is referring to the formset it attaches to the parent view). Also, I use merged create-update views. The problem I'm having is that when I create a new report, the information about all customers is stored in the initial property of the formset: customer_entries = [{'customer':x} for x in Customer.objects.all()] context['inlines'][0].initial = customer_entries context['inlines'][0].extra = len(customer_entries) However, if I'm viewing an existing object, this data is instead stored in formset's instance, but I want to universally refer to the customer's data provided with a report, regardless of whether it's new or existing. The best way I found to do this is by putting this fairly … -
Get Sum of amount fields result in djagno rest
Here is my serializer class MySerializer(serializers.Serializer): amount1 = serializers.SerializerMethodField(read_only=True) amount2 = serializers.SerializerMethodField(read_only=True) amount3 = serializers.SerializerMethodField(read_only=True) total = serializers.SerializerMethodField(read_only=True) class Meta: model = Amount fields = "__all__" def get_amount1(self,obj): """very large calculation here""" return 5 def get_amount2(self,obj): """very large calculation here""" return 10 def get_amount3(self,obj): """very large calculation here""" return 15 def get_total(self,obj): return self.get_amount1 +self.get_amount2+self.get_amount3 Now i want to show sum of all the three amount in 'total' field. but it is taking too much time because of large calculation in above methods and they are calculating twice only for getting total. How can i get sum of amount1, amount2,amount3, without calculating get_amount1,get_amount2,get_amount3 twice. -
Matching list of UK postcodes to the correct county
What is the most efficient way to match a list of postcodes to their correct county and then county to a region? I have three models one for Region, County, and location. I have a list of around 500 postcodes and I will have the information of the counties and regions of UK stored (This will come from an API as these locations may change based on data pulled in API) but I have no way that I can think of, of connecting the three together. End Result I'm wanting this web application to display drop-down boxes (This bit i can handle fine issue is with next bit) and when a user selects the region/county it lists the relevant postcodes/locations. -
Django template variable NoReverseMatch
I am not sure what I am doing wrong. A page uploads to a folder (media/uploads/) and the folder is read. Along with the files being read, there are other functions. The 'delete' function, in particular, is not working. It keeps giving me this NoReverseMatch error. NoReverseMatch at / Reverse for 'delete' with arguments '('example.txt',)' not found. 1 pattern(s) tried: ['$'] urls.py url(r'^$', views.model_form_upload, name='form'), url(r'^$', views.delete, name='delete'), form.html {% for doc in docs %} <i class="glyphicon glyphicon-download" onclick="download();"></i> <div class="file_list">{{ doc }}</div> <i class="glyphicon glyphicon-trash" onclick="trash();"></i> <div id="delete-assure"> <div class="delete-assure-content"> <p>Are you sure that you wish to delete this file?</p> <hr> <div id="yes"><a href="{% url 'delete' doc %}">Yes</a></div> <div id="no">No</div> </div> </div> {% endfor %} views.py def model_form_upload(request): path = "media/uploads/" docs = sorted(os.listdir(path)) if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('form') else: form = DocumentForm() return render(request, 'mapapp/form.html', { 'form': form, 'docs': docs }) def delete(request, doc): os.remove(doc) return redirect('form') -
django (rest) for model.all() get field from foreign key relation
I have a Report model which has a relation to the Currency model as below: class Currency(models.Model): name = models.CharField(max_length=48) symbol = models.CharField(max_length=4) code = models.CharField(max_length=3) class Meta: db_table = 'currency' verbose_name = 'currency' verbose_name_plural = 'currencies' class Report(models.Model): path = models.CharField(max_length=256, null=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) class Meta: db_table = 'dsr' I'd like to get all the currency codes for every report in my views.py. I've tried using reverse lookups, but they don't seem to work with 'all' My serializer: class CurrencySerializer(serializers.ModelSerializer): class Meta: model = models.Currency fields = '__all__' and the same for the Report Serializer. My views.py: @api_view(['GET']) def rep_currencies(request): all_reports = models.Report.objects.all() report_currencies = all_reports.currency_set.all() data = serializers.CurrencySerializer(report_currencies, many=True).data return Response(data) which returns 'QuerySet' object has no attribute 'currency_set'. -
Django checkbox-database connection
Recently i started to learn Django and i am trying to access a BooleanField in my database via browser this is my form class NewTopicForm(forms.ModelForm): slot1 = forms.BooleanField(required=False) slot2 = forms.BooleanField(required=False) slot3 = forms.BooleanField(required=False) message = forms.CharField( widget=forms.Textarea( attrs={'rows': 5, 'placeholder': 'explanation'} ), max_length=4000, help_text='The max length of the text is 4000.' ) class Meta: model = Topic fields = ['subject', 'message', 'slot1', 'slot2', 'slot3']` this is my view. when i say "board.slot2 = True" it changes my slot2 False to True. but how can i change slot2 in my browser @login_required def new_topic(request, pk): board = get_object_or_404(Board, pk=pk) if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): topic = form.save(commit=False) topic.board = board topic.starter = request.user board.slot2 = True board.save() # board.slot3 = False # board.save() topic.save() Post.objects.create( message=form.cleaned_data.get('message'), topic=topic, created_by=request.user ) return redirect('topic_posts', pk=pk, topic_pk=topic.pk) else: form = NewTopicForm() return render(request, 'new_topic.html', {'board': board, 'form': form})` this is my model class Board(models.Model): name = models.CharField(max_length=30, unique=True) slot1 = models.BooleanField() slot2 = models.BooleanField() slot3 = models.BooleanField() def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(topic__board=self).count() def get_last_post(self): return Post.objects.filter(topic__board=self).order_by('-created_at').first()` -
Modify results of django queryset
I have two models Event and Shift. class Event(models.Model): start = models.DateTimeField() end = models.DateTimeField(blank=True, null=True) class Shift(models.Model): name = models.CharField(max_length=20) start = models.TimeField() end = models.TimeField() Now on some view I have to filter out Events that occur in the interval of a Shift. And I did this. queryset = Event.objects.all() queryset = queryset.filter(start__time__range=(s.start, s.end)) | queryset.filter(end__time__range=(s.start, s.end)) And now I want to trim start and end of events in the queryset to be in the rage of the start and end of the Shift I'm filtering on. Also, some events may cross a Shift more than once. In that case, I have to split the Event to the number of times it crosses a Shift. How can I achieve this? -
Django Rest Framework - Replicate data for given parent Model and related entries in its child model
I have 2 models Paper and Question. User can select any paper and can create a copy of that paper (including its questions). How to implement this in Django Rest Framework? models.py class Paper(models.Model): paper_name = models.CharField(max_length=128) class Question(models.Model): question_text = models.CharField(max_length=1024) paper_id = models.ForeignKey(Paper, related_name='questions_paper') serializer.py class PaperSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'paper_name') model = Paper def create(self, validated_data): source_pape = ?? # paper whose copy to be made paper = Paper.objects.create(**validated_data) questions = Question.objects.filter(paper=source_paper) Question.objects.bulk_create([Question(paper=paper, question_text=question.question_text) for question in questions]) return paper class QuestionSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'question_text', 'paper_id') model = Question How to get input source_paper (paper which needs to be copied) from user and replicate its data? Thank you in Advance. -
How to make input like SO in Django Model
Hello is it possible in models.py to create a field like this one I have a blog where people can create their articles trough the admin panel so I want to give them freedom to choose the style place pictures and etc... -
Is a URL prefix a feasible i18n signal in Django?
Users need to acces a Django site and see pages in the supported language if their choice (e.g. en or fr). Mechanisms to support language-switching include: Setting a cookie flag via stored preference and/or JavaScript. Returning content based on flag. Encoding the language in the subdomain, like en.wikipedia.org Encoding the language in the URL, something like example.com/en/stub For various reasons, options 1 and 2 are not possible. Is option 3 viable in Django? In other words, already an option with a built-in or third-party i18n module, or trivial to implement? -
Python pika stucks after some time
I have high loaded system built on message consuming and producing, but main part of system isn't working, because RabbitMQ stucks. Full system restart helps, while all workers redeployed. I search in google but don't find anything that could help. After some time workers just stops receive message, I see through logs that message was published, concumer acknowledge it, but do nothing, even not write in a log. In rabbitmq management I see that connections still alive. Maybe someone has the same issue and found a way how to fix it? P.S. System runs on docker swarm, use about 15 droplets on DigitalOcean for workers.