Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django-constance?
I use django-constance and have several questions about it's functions. 1) How can I set upload path for mediafiles? I want to upload files in folder MEDIA_ROOT/constance_upload 2) How can I mark field as not required? image-, file-, html- fields are required as default. CONSTANCE_ADDITIONAL_FIELDS = { 'image_field': ['django.forms.ImageField', {}], 'file_field': ['django.forms.FileField', {}], 'email_field': ['django.forms.EmailField', {}], 'html_field': ['ckeditor.fields.RichTextFormField'] } 3) How can I collapse fieldset when I am using OrderedDict? CONSTANCE_CONFIG_FIELDSETS = OrderedDict([ ('Seo', ('ROBOTS',)), ('Page 404', ('ERROR_TITLE', 'ERROR_DESCRIPTION', 'ERROR_PREVIEW')), ]) Thank you for your attention and help! -
Django parent form with child inlineformset won't exclude fields when rendering
I have a Parent model and Child model with one-to-many relation. In my /manage/ URL for parent, I am displaying the form for the Parent model and then formset for the Child model. When I render the form and formset, I am getting all the fields although I have mentioned the necessary fields in my fields variable. forms.py class ParentForm(ModelForm): title = forms.CharField( widget=forms.TextInput( attrs={ 'class': "input", }), label='Parent title' ) slug = forms.SlugField( widget=forms.TextInput( attrs={ 'class': "input", }), label='Slug' ) description = forms.CharField( widget=forms.Textarea( attrs={ 'class': 'textarea', }), label='Description' ) class Meta: model = Parent fields = ['title', 'slug', 'description'] class ChildForm(ModelForm): title = forms.CharField( widget=forms.TextInput( attrs={ 'class': "input", }), label='Child title' ) slug = forms.SlugField( widget=forms.TextInput( attrs={ 'class': "input", }), label='Slug' ) order = forms.IntegerField( widget=forms.TextInput( attrs={ 'class': "input", 'placeholder' :"0" }), label='Order' ) class Meta: model = Child fields = ['title', 'slug', 'order'] class ParentManageForm(ParentForm): def __init__(self, *args, **kwargs): super(ParentManageForm, self).__init__(*args, **kwargs) class Meta(ParentForm.Meta): fields = ['title',] class ChildManageForm(ChildForm): def __init__(self, *args, **kwargs): super(ChildManageForm, self).__init__(*args, **kwargs) class Meta(ChildForm.Meta): fields = ['title', 'order'] ChildFormset = inlineformset_factory( Parent, Child, form=(ChildManageForm) ) views.py class ParentManage(LoginRequiredMixin, UpdateView): login_url = reverse_lazy('login') model = Parent form_class = ParentManageForm slug_url_kwarg = 'parent_slug' template_name_suffix = … -
Why use the function of form_valid to add created by logic?
I was able to configure creating a form which automatically uses the logged in user to populate the author/created-by field. The way I understood form_valid is if form is valid, a redirect is called to the success_url. My question is why put the logic (form.instance.created_by=self.request.user) inside of form_valid. I want to understand why I would want to do it. You can see the code below: def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) For background purposes, I used a generic view found below: class PostQuestionView(LoginRequiredMixin, CreateView): model = Question template_name = 'post_question.html' fields = [ 'subject', 'description', ] success_url = reverse_lazy('questions:home') Current environment is Django 3.0.3 and Python 3.7. -
Django_filter incorrectly filters array in object
I have ManyToMany field in my model "Product" which is called combinations and it includes some objects, that have slug and name field. I tried to filter by slug field, but if the product contains 2 slugs (for example red_wine and white_wine), django returns this product twice, but i need it to return only once. Models.py: class Combination(models.Model): name = models.CharField(max_length=120) slug = models.CharField(max_length=120) class Product(models.Model): collection = models.ForeignKey('Collection', on_delete=models.CASCADE) combination = models.ManyToManyField('Combination', blank=True) Views.py: class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter): pass class CollectionFilter(django_filters.FilterSet): collection = CharInFilter(field_name='collection__slug', lookup_expr='in') combination = CharInFilter(field_name='combination__slug', lookup_expr='in') class Meta: model = Product fields = ['collection', 'combination'] class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = CollectionFilter -
Django SECRET_KEY error due to containing "!" in secret key
I'm trying to deploy my django application in heroku. While deploying it seems that i need to set DJANGO_SECRET_KEY manually in heroku config:set DJANGO_SECRET_KEY=secretekey instead environment variablele file. But i'm getting the error bash event not found . I know this is due to exclamation mark in SECRET_KEY. I've tried using single and double quotes but that too didn't work. This is the part of my SECRET_KEY causing error, (+9=!sbeh************** -
How to Import Models from one app to another App model?
I am trying to reference a model People from my users app, in the models-file of botschaft app. Unfortunately, I get an ModuleNotFoundError while doing make migrations. here is my botschaft-models.py: from django.db import models from loginSite.users.models import People class Botschaft(models.Model): from_person = models.ForeignKey(People, related_name='from_person',on_delete= models.CASCADE) to_person = models.ForeignKey(People,related_name='to_person',on_delete= models.CASCADE) msg = models.TextField() And directory structure of my project is as: directory structure of my project While doing migrations , I am getting error as: from loginSite.users.models import People ModuleNotFoundError: No module named 'loginSite.users' I have tried using - from ..users.models import People , but getting error as, from ..users.models import People ValueError: attempted relative import beyond top-level package Little help will be appreciated. -
Change Django-Notifications Delete Redirect
Im using django-notifications and am displaying notifications at two urls, /inbox/notifications/ and /admin/. By default when a notification is deleted the user is redirected to /inbox/notifications/, which works well when a user deletes the notification from this page. However, seeing as I am also displaying notifications on the admin page, whenever I delete a notification from there, the delete works successfully but redirects the admin to /inbox/notifications/, which is really annoying. My question is how can I change the redirect so that it either redirects to the calling page, or has logic that dicides where to redirect after success. This would be easy enough if this was my own view, but the logic for this is in the django-notifications app. Thank you. -
How to add links dynamically in html files in django?
For my project, I'm searching for articles on google news based on keyword input by the user, I want to display these links obtained from the search on my results page. this is my result.html {% extends 'base.html' %} {% block title %}Result{% endblock %} {% block content %} <h2><a href="{{link_to_post}}" target="_blank">Reported Url</a></h2> <div>Post Content: <br>{{content}}</div> <ul> {% for i in range(5) %} <li><a href="links[i]">headlines[i]</a></li> {% endfor %} </ul> <div> <a href="{% url 'home' %}">Back to Home Page</a> </div> {% endblock %} First question can I attach links in this way, without adding them to urls.py, if not how do I attach these dynamically generated links in my html file. Second, this is the error I'm getting on running this page: Could not parse the remainder: '(5)' from 'range(5)' But in the debug section inside local variables I can see that "links" and "headlines" are correct. So the problem in in this file only. I also tried enclosing "links" and "headlines" inside "{{}}" thank you -
how can i store the data input from the registration form in both User model and Profile model
I want to save the username from User model to the Profile model. // models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,blank=True,null=True) username = models.CharField(max_length=150,null=True,blank=True) image = models.ImageField(default='/pics/default.jpg',upload_to='profile_pics',blank=True) def __str__(self): return f'{self.user.username}.Profile' @property def get_image_url(self): if self.image and hasattr(self.image,'url'): return self.image.url else: return "/static/pics/default.jpg" -
How can one get a video thumbnail in Django with InMemoryUploadedFile?
Use case: mobile clients upload videos via mulitiPart/Form and my Django app stores the file on Google Cloud Storage as well as creates a model instance that points to that video. As Django's request.FILES returns a dictionary of InMemoryUploadedFiles, it makes using mainstream python video processing libraries difficult. All these libraries (ie. CV2, MoviePy etc) expect file paths to a video in order to extract frames but I do not have a file paths, Django only provides InMemoryUploadedFiles. Does anyone have any solutions in mind to create a video thumbnail given the time in the video? Please steer clear of solutions that involve saving the InMemoryUploadedFile to a temporary file as the uploaded videos may be quite large. The file already lives in memory, there must be a way to do this. -
Sending data to two diffrent fields using foreign key
I am using foreign key of a model person using both its field in other other model company.But while inserting data in company i am not getting last name,output is employee and last bothe same class Person(models.Model): first_name = models.CharField(max_length=30,null=True) last_name = models.CharField(max_length=30,null=True) def __str__(self): return str(self.first_name) class Company(models.Model): name=models.CharField(max_length=20,null=True) employee=models.ForeignKey(Person,on_delete=models.CASCADE,related_name='first',null=True) last=models.ForeignKey(Person,on_delete=models.CASCADE,related_name='second',null=True) def __str__(self): return str(self.name) ViewSet class CompanyViewset(viewsets.ViewSet): def create(self,request): name=request.data.get('name') employee=request.data.get('employee') last=request.data.get('last') user=Company() user.name=name user.employee=Person.objects.get(first_name=employee) user.last=Person.objects.get(last_name=last) #print(user.last) #user.last=use.last_name print(user.last.last_name) user.save() return Response({'succesfully saved'}) -
Beginner Level Question Django 3.0: Class based views
I am stuck at some beginner level concept of django. I am so much unable to understand documentation of TemplateView. In following sample of code: class ProductView(TemplateView): template_name = "product.html" Form just template_name how django render html page. I mean is template_name is reserved keyword? What if I write template_name1 instead of it will it work? And I am not returning anything how this single doing all things. -
How to reverse to a View class?
This is my views.py file. I want to reverse into PollView in the end of vote function but I am getting an error. ERROR: views.py from django.shortcuts import render, reverse, redirect from django.views import View from .models import Question, Choice # Create your views here. class PollView(View): def get(self, request): questions = Question.objects.all() return render(request, "app/poll.html", {'questions': questions}) def vote(request, pk): choice = Choice.objects.get(pk=pk) choice.votes += 1 choice.save() return reverse('poll:index') urls.py from django.urls import path from .views import PollView, vote app_name = 'poll' urlpatterns = [ path('', PollView.as_view(), name='index'), path('vote/<int:pk>', vote) ] -
Django Auth : How are many-to-many relationship models are created?
django.contrib.auth.models have only 3 models, User, Group, Permission, as per the doc and code. Doc does say groups and permissions are many-to-many relationships. But when we migrate how come other relations user_group, user_permissions, group_permissions are created? -
Nginx Docker Static File Permission Issue in Centos with Default nginx user in new version of NGINX
I am facing static files access issue using nginx as the proxy server inside docker container .I a getting permission issue .I am using Nginx+Django+Gunicorn+Docker . I am able to access the website in the URL ,but not able to access the static files.I googled more on that and followed many steps which mentioned there.But nothing works. Even i had given read write permission to that particular folder of static files for nginx. -
Migrate tables in django from a read-only database
Is there a way to migrate all tables from an oracle read-only database to django? So basically I don't want to make any modification to my database. I just want to extract information from it. From what I found till now, is a way by using routers but I don't know how exactly to use it. Thanks, any help will be appreciated DB: oracle Django version: 2.2.12 python: 3.6 cx-Oracle: 7.3.0 -
Automatically update user_id and date fields at django into database
I'm new to Python and Django and there are some things I would like to achieve in models.py: After a user submits a form I would like to safe both the current date and the current user_id of the user into the database. I know django offers to use @property decorators for those, but the problem with that is that I would like to make SQL queries using user_id and that doesn't work with decorators. Another related question is how to establish calc fields like an automatic calculation of two values in the form before submitting. -
Django How to pass str value from link a href to view without modifying urls.py?
I wanted to ask you for your help with passing a STR value from a href link to my views.py but without modifying urls.py I am not sure if it possible, but it sounds useful I think, so maybe it is doable? Right now in order to work I have to use urls.py like this: path('my_notes/', views.my_notes, {'category': 'Python'}, name='my_notes'), But I would like to go completely "DRY" and do something like this: <a class="dropdown-item" href="{% url 'my_notes' %}" category="Python">Python</a> And in views.py: def my_notes(request): category = request.GET['category'] notes = Note.objects.filter(category__category=category, sub_category__sub_category="Notes") snippets = Note.objects.filter(category__category=category, sub_category__sub_category="Code_Snippets") context = { 'notes': notes, 'snippets': snippets, 'category': category } return render(request, 'my_notes.html', context) But with this solution i get "MultiValueDictKeyError". I googled it and I tried to convert it to dict, try to add additional "false" arguments but I can't get it to work. I am not even sure if it's right approach? Thanks and Cheers! -
Seach_fields for all models including foreign keys fields and many to many fields in django admin
class DemoModelAdmin(admin.ModelAdmin): def init(self,*args,**kwargs): self.model = args[0] self.admin_site = args[1] self.list_display = self.list_filter = list(map(lambda field:field.name,self.model._meta.fields))[1:] -
DRF : how to add user permissions to user detail api?
So I am writing a UserDetails view as follows. class UserDetailsView(RetrieveUpdateAPIView): serializer_class = AuthUserSerializer def get_object(self): return self.request.user My Serializers are as follows. class PermissionSerializer(serializers.ModelSerializer): class Meta: model = Permission fields = ('id', 'name', 'codename') class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name') class AuthUserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) # permissions = PermissionSerializer(many=True) # permissions = serializers.PrimaryKeyRelatedField(many=True, queryset=Permission.objects.all()) class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'groups', 'user_permissions') groups = GroupSerializer(many=True) gives me following. "groups": [ { "id": 2, "name": "A" }, { "id": 1, "name": "B" }, { "id": 3, "name": "C" } ], I expect the similar from permissions = PermissionSerializer(many=True) but I get the following error. Got AttributeError when attempting to get a value for field `permissions` on serializer `AuthUserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'permissions'. but instead, if add user_permissions to the fields directly without adding related reference it gives me all ids of permissions. I want to have id, name, codename also. And, Of course, UserPermissions model is not found. ;-( How … -
Django model not using another model via a foreign key relationship
I'm trying to create a web app that will allow booking onto training sessions in a running club. I've got my users app and a training_sessions app where coaches can post sessions. They include location, date, the coach taking the session and some details on what the session entails. I now want to add a facility where a logged in user can click on the session and have them booked onto it. I've a ClubSession model: class ClubSession(models.Model): location = models.CharField(max_length=200) coach = models.ForeignKey(CustomUser, on_delete=models.CASCADE) date = models.DateTimeField(default=now) details = models.TextField() def __str__(self): return self.location def get_absolute_url(self): return reverse('session_detail', args=[str(self.id)]) From it's used in several views to create, edit, delete, view and list all sessions: class SessionListView(ListView): model = ClubSession template_name = 'club_sessions.html' context_object_name = 'all_club_sessions_list' class SessionDetailView(DetailView): model = ClubSession template_name = 'session_detail.html' context_object_name = 'club_session' class SessionCreateView(CreateView): model = ClubSession template_name = 'session_new.html' fields = ['location', 'coach', 'date', 'details'] class SessionUpdateView(UpdateView): model = ClubSession template_name = 'session_edit.html' fields = ['location', 'coach', 'date', 'details'] class SessionDeleteView(DeleteView): model = ClubSession template_name = 'session_delete.html' success_url = reverse_lazy('home') I'm now trying to create a booking model with a foreign key to my user and ClubSessions models. This is what I've got: class … -
Django - How to include all possible months / quarters / year within range in queryset
I am trying to get the sum of the estimated revenue of projects within a varying range of months, but the issue I am facing right now is that the queryset I receive would leave out the months where no data exists, but I would like to receive data about that month too (with estimated revenue sum 0) so that my data visualisation would be proportional and include all months within the selected range. Here is my code: start = datetime.strptime(self.request.query_params.get('start'), '%Y-%m-%d') end = datetime.strptime(self.request.query_params.get('end'), '%Y-%m-%d') qs = SalesProject.objects.filter(sales_department=d).filter(creation_date__range=(start,end)) qs = qs.annotate(date=TruncMonth('creation_date')).values('date').annotate(est_rev_sum=Sum('sales_project_est_rev')) start and end are parameters passed in through the api call and the parameters dictate the range of months to get. Hence, for example, if start is April 2020 and end is June 2020, and there are only SalesProject instances with 'creation_date' in April and June 2020, but none in May 2020, the qs returned would only have: [{ 'date': April 2020, 'est_rev_sum': 300 }, { 'date': June 2020, 'est_rev_sum': 600 }] but what I would want is for May 2020 to be included as well (even if the sum is 0 and no instances of SalesProject exists in May2020) [{ 'date': April 2020, 'est_rev_sum': 300 }, { … -
How to run celery periodic task to some specific date only based on some fields?
I want to run my task till the task.scraping_end_date every task.search_frequency hrs if task.status is either 0 or 1. If the current date passes the scraping end date then I want to change the status as completed and stops the task. How can I do it with celery ? models class Task(models.Model): INITIAL = 0 STARTED = 1 COMPLETED = 2 ERROR = 3 task_status = ( (INITIAL, 'running'), (STARTED, 'running'), (COMPLETED, 'completed'), (ERROR, 'error') ) FREQUENCY = ( ('1', '1 hrs'), ('2', '2 hrs'), ('3', '3 hrs'), ) name = models.CharField(max_length=255) scraping_end_date = models.DateField(null=True, blank=True) status = models.IntegerField(choices=task_status) search_frequency = models.CharField(max_length=5, null=True, blank=True, choices=FREQUENCY) tasks.py scrapyd = ScrapydAPI('http://localhost:6800') @periodic_task(run_every=crontab(minute=1), ignore_result=False) def schedule_task(pk): task = Task.objects.get(pk=pk) if task.status == 0 or task.status == 1 and not datetime.date.today() >= task.scraping_end_date: # do something else: task.status = 2 task.save() -
Pass input from django-ploly-dash app to other apps of the same django template
I am using django-plotly-dash to insert a set of dash apps, representing each an individual graph, into a django template. Each app or graph has their own input fields to select data and plot it for a given time-frame. Now I would like to move the date-select/input field to one separate dash app, in order to select the data for all apps within the template but I struggle to find a a solution. I consulted the documentation at https://django-plotly-dash.readthedocs.io as well as the examples at https://djangoplotlydash.com/. Any hints on how to move forward are highly appreciated! -
Passing value(0) to empty json response in django
When a null response is sent to ajax there is no change in the chart or table.So, if there is null data sent I want the ajax response.So, for that when json data is sent,I want the output 0 instead of empty JSON response. Example: Problem:{"time_chart": {}, "pie_chart": {"super": 0, "staff": 0, "active": 0, "inactive": 0}, "table_chart": []} Note: How the time_chart responses is null and so is table_chart.I want my output something like this. Expected Output: {"time_chart": {"datetime": [8, 7, 6, 5, 4, 3, 2, 1],count": [0, 0, 0, 0, 0, 0, 0, 0]}, "pie_chart": {"super": 0, "staff": 0, "active": 0, "inactive": 0}, "table_chart": [{"username": "", "email": "", "date_joined": ""}]} The view is used to filter certain number of user in given time period.It also distingushes the type of user(Super,Staff or Active). def get_user_type(user): if user.is_superuser and user.is_staff and user.is_active: return "super" elif not user.is_superuser and user.is_staff and user.is_active: return "staff" elif not user.is_superuser and not user.is_staff and user.is_active: return "active" else: return "inactive" def midnight_time(): today = date.today() midnight = datetime.combine(today, datetime.min.time()) return midnight def midnight_yesterday_time(): today = date.today()-timedelta(days=1) midnight = datetime.combine(today, datetime.min.time()) return midnight def hits_in_yesterday(self): today = date.today() midnight = datetime.combine(today, datetime.min.time()) yesterday_hits=midnight-timedelta(days=1) return self.hit_set.filter(created__gte=yesterday_hits,created__lte=midnight).count() def …