Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Formset validation errors not fired
I created a custom validation error and it worked just fine before abstracting my class based views. For some reason, whenever there's an error, the error is just blank, e.g [{}] Validation Error logic: class BaseFormSetValidation(BaseModelFormSet): def clean(self): super().clean() days = ['day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7'] for form in self.forms: for day in days: current_day = form.cleaned_data.get(day) if current_day is not None and current_day > 24: raise ValidationError([{day: ["Submitted hours per day cannot exceed 24 hours"]}]) class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return '%s' % ''.join([e for e in self]) TimesheetModelFormSet = modelformset_factory(Timesheet, formset=BaseFormSetValidation, exclude=("year", "week", "project", "user"), extra=0) TemplateView Class class TimesheetEditorView(BaseTimesheet, TemplateView): form_class = TimesheetModelFormSet template_name = "timesheets/timesheet.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) timesheet = Timesheet.objects.filter(year=context["year"], week=context["week"], user=self.request.user).order_by("project_id") timesheet_formset = self.form_class(queryset=timesheet, error_class=DivErrorList) create_timesheet_form = TimesheetModelForm(self.request.user) context.update( timesheet=timesheet, timesheet_formset=timesheet_formset, create_timesheet_form=create_timesheet_form ) return context def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) timesheet_formset = self.form_class(request.POST) if timesheet_formset.is_valid(): messages.info(request, "Weekly timesheet updated", extra_tags='timesheet') timesheet_formset.save() success_url = reverse("timesheets:current-week", args=(context["year"], context["week"])) return HttpResponseRedirect(success_url) return render(request, "timesheets/timesheet.html", self.get_context_data(**kwargs)) Which inherits from class BaseTimesheet(object): ... def get_context_data(self, **kwargs): context = super(BaseTimesheet, self).get_context_data(**kwargs) year = kwargs.get("year") or datetime.datetime.now().year week = kwargs.get("week") or Week.thisweek().week user = self.request.user … -
Changing css to a tag depending of the content inside it
I would like to know if there is a way in which using css i would be able to change the css properties, i was thinking if there is any way such as when working with input types, you indicate input[type='submit'] for example, and set your css for that specifical input, or the correct way of doing it. HTML <td><div class="perform"><a href="{%url 'appointmentupdate' consult.id %}">{%if consult.Medicamento%}Modificar{%else%}Realizar{%endif%}</a></div></td> This is the tag i want to apply this on. I would like to set some border above with some color, but specific for each word. -
How to fix no reverse match error in Ajax
I am trying to use Ajax to submit a like button without getting the page refreshing, I have been getting several errors previously but now I am getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['score/like/(?P<pk>[0-9]+)$'] I am not sure what is the reason. Need help to identify the error. Here is the view: class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked return context def LikeView(request, pk): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) like = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) like = False else: post.likes.add(request.user) like = True context["total_likes"] = total_likes context["liked"] = liked if request.is_ajax: html = render_to_string('like_section.html', context, request=request) return JsonResponse({'form': html}) Here is the url.py updated: urlpatterns = [ path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('', PostListView.as_view(), name='score'), path('who_we_Are/', who_we_are, name='who_we_are'), path('<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('like/<int:pk>', LikeView, name='like_post'), path('new/', PostCreateView.as_view(), name='post-create'), path('<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete') ] Here is the template: <form class="mt-0" action="{% url 'score:like_post' post.pk %}" method='POST'> {% csrf_token %} <strong> Likes: {{total_likes}} </strong> {% if user.is_authenticated %} {% if … -
Query only once with Django Rest Framework
I'm obtaining data from database and display on table via jQuery and Django Rest Framework(DRF). Also, I'm using pagination. The problem is that every time I click "next" or "previous" button on table, get_queryset() is called and DRF make the query again and again which slows down pagination. How can I save/cache this query result so pagination doesn't query every time I use pagination? DRF Implementation in view class SomeListing(generics.ListAPIView): pagination_class = ResultsSetPagination serializer_class = ResultSerializer def get_queryset(self): param = self.request.query_params.get('param', None) query = some_function_to_get_data(self.request, param) return query -
Django - models.ForeignKey
Thanks for checking this out. Silly doubt of mine: I have the following models defined in Django: class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() # positive integer only accepts positives school = models.ForeignKey("School", related_name='students', on_delete=models.CASCADE) def __str__(self): return self.name My question is: How does Django knows to pick the School.name field as a match for the foreign key school? As when I check on the Admin page and add a student, I can select the name of the school (as the foreign key). Name: Age: School = (drop down with the name of the schools) Is it the order of the elements or something else? Thanks again! -
How can i add a marker on an image (similar to markers on google map) using django's reportlab?
I would like to know is there a way that I can add a marker to an image on reportlab(pdf) document for reporting purpose. I have attached the web version of my marker and image. I achieved that using jquery (https://www.jqueryscript.net/zoom/Image-Zoom-Annotation-Plugin-jQuery-ZoomMarker.html) floorplan with marker Basically, x and y position of the marker has been saved in the database, while the floorplan image is always 500px x 500px. Now, how can i do it on reportlab? Thank you for help -
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
I have hosted a webapp on a linux server using django-uwsgi,I was trying to directly call the --ini file from uwsgi as uwsgi --ini .ini file but I'm getting a weird error like this. [uWSGI] getting INI configuration from /etc/uwsgi/sites/salesproject.ini *** Starting uWSGI 2.0.18 (64bit) on [Tue May 19 23:37:24 2020] *** compiled with version: 9.3.0 on 18 May 2020 16:02:04 os: Linux-5.4.0-26-generic #30-Ubuntu SMP Mon Apr 20 16:58:30 UTC 2020 nodename: django-server machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 2 current working directory: /var/uwsgi detected binary path: /home/ubaid/.local/bin/uwsgi chdir() to /home/ubaid/salesproject your processes number limit is 15402 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to UNIX address /var/uwsgi/salesproject.sock fd 3 Python version: 3.8.2 (default, Apr 27 2020, 15:53:34) [GCC 9.3.0] !!! Python Home is not a directory: /home/ubaid/Env/salesproject !!! Set PythonHome to /home/ubaid/Env/salesproject Python path configuration: PYTHONHOME = '/home/ubaid/Env/salesproject' PYTHONPATH = (not set) program name = '/home/ubaid/Env/salesproject/bin/python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/home/ubaid/Env/salesproject/bin/python' sys.base_prefix = '/home/ubaid/Env/salesproject' sys.base_exec_prefix = … -
django rest framework structure a nested model serializer and update values in another serialier
Here is the models class Poll(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question_text class Choice(models.Model): poll = models.ForeignKey(Poll, null=True, blank=True) choice_text = models.CharField(max_length=200) vote_count = models.IntegerField(default=0) class Vote(models.Model): selected_choice = models.ForeignKey(Choice) responder = models.ForeignKey(UserProfile) Here are my serializers class PollSerializer(serializers.ModelSerializer): class Meta: model = Poll fields = ('id', 'question_text', 'pub_date', 'choice_set') def get_votes(self, obj): votes = Vote.objects.filter(selected_choice = obj.choice_set) return votes Is there a better way to structure the poll serializer? Additionally, when we create a new vote object, how can we auto-increment the vote_count in Choice model? -
Get current user in model's clean() method
I have product add/edit form. I have the following scenario: Each user can have up to 2 posts Now, i want to implement checks for how many products user currently has. I temporary implemented this in form_valid in class that is a child of CreateView class: def form_valid(self, form): max_prod = 2 form.instance.author = self.request.user prod = len(User.objects.get(id=self.request.user.id).product_set.all()) if prod > max_prod: form.add_error(error=f"You have reached product limit ({max_prod})", field="name") return super().form_invalid(form) else: return super().form_valid(form) However, I have read that the best way to do this is by adding conditions in clean() method for specific model. However, in my case, I would need to somehow get current user. How can I do this? Edit: I have tried by adding the following: prod = len(User.objects.get(id=self.author.id).product_set.all()) However, it looks like author is not saved at the moment this method is executed: products.models.Product.author.RelatedObjectDoesNotExist: Product has no author. -
Should we create chat application with Flutter and Django if we want good performance and efficiency?
I am a newbie in the chat application world but I am not new in the IT world! I want to create a chat application that may have a large user base in the future. I have researched that now days flutter is a very good option to create cross-platform apps and it is good in terms of performance. So to create that chat app in android and ios I will use flutter in front-end for sure! But for backend, I am not so sure. I have 3 years of experience in python and Django and that's why I wanted to use Django as backend in my chat app. I have searched that there is one package of Django named Django-channels which I can use to build a chat app! But I have concerned like will django-channels be a good option to build a large chat application like Instagram or WhatsApp? -
How can I deploy my Django Project into Apache in Windows with no WAMP Installation
I know this may be kind of a stretch but I had already installed Apache manually since I started learning Django, I just want to host a Django Project to my Web Server in order for me to use locally. I already hosted some other files in Apache like some PHP files and so but I really want to make this work also. -
Graphene Django getting items
I have a Query: class Query(object): all_articles = graphene.List(ArticleType) category_articles = graphene.List(ArticleType, category = graphene.String()) def resolve_all_articles(self, info, **kwargs): return Article.objects.all() def resolve_article_by_category(self, info, **kwargs): category = kwargs.get('category') return Article.objects.get(category = category) And I want to get all articles by specific category. I try to make such a request: query { categoryArticles(category: "SPORT") { title } } But it returns me: { "data": { "categoryArticles": null } } Does somebody know what I do wrong or how to get articles by specific category? I will be very grateful if somebody can help. Thanks! -
Building a django queryset with primary keys in JSON array field
Suppose we have a model like, class Table1(models.Model): name = models.CharField() class Table2(models.Model): name = models.CharField() table1_pks = ArrayField(models.IntegerField()) with the entries, Table1 id | name ---------- 1 | hydrogen 2 | helium 3 | lithium 4 | berylium Table2 id | name | table1_pks Mapping to table1 ----------------------- 3 | fe | {2, 3} -> Multiple 6 | br | {1, 3, 4} -> Multiple 7 | cr | {2} -> Single 10 | be | {2, 4} -> Multiple 12 | sn | {1, 2, 3, 4} -> All 15 | ra | {1} -> Single 17 | pu | {1, 2, 3, 4} -> All 19 | ti | {2, 5} -> Single How to create a queryset on Table2 so that the results are ordered/grouped in the sequence of All, Multiple and Single. Note that the last entry 19 in Table2 is called Single because the entry for 5 doesn't exists in Table1. So any consideration to compare the length of each entry in table1_pks against the total rows in Table1 might not work. -
i want to post somthing in django but view not working good
hello i want to post choice(radio button field) but my view is not working and my query is something.objects.all , i can post it with pk but in my project i want to to post it without pk,thanks a lot enter image description here enter image description here enter image description here -
Significance of Django in a django-react application
Well, i am creating an app, with reactjs in frontend and Django in the backend. I have everything setup, like the Django REST API, CORS, everything. I am successfully exchanging data from both the platforms efficiently through Axios. But one question haunts me, that is, what if someone asks, "Why did you choose Django only, for the backend?" Currently, I am using django only for the mere get data and post data purposes. So is there anything else from the list of Django-powers, that I can include in the frontend, other than using it just as a database? I want to utilize Django's features to the fullest. -
Call Django API internally using relative URL path and request body
I'm migrating to GKE from GAE. Due to a number of reasons, I've to switch from Cloud Tasks to Cloud Pub/Sub. Using supervisord, I've set up a service that listens to newly published messages. The messages contain HTTP method, relative URL and payload. Using the following code, I'm able to get a ResolverMatch object for the relative URL: from django.core.urlresolvers import resolve # django.urls for Django>=2.0 task = { 'http_method': 'PUT', 'relative_uri': '/accounts/1/', 'body': '{"name": "John Doe"}', 'headers': {'Content-Type': 'application/json'}, } match = resolve(task['relative_uri']) print(match.func, match.kwargs) Unfortunately, I'm using both ViewSets and individual methods for defining routes. So I can't just invoke the create method for a viewset if the HTTP method is POST, as it might not exist. Is there a way to call an API in the same Django app internally using just relative URL path, HTTP method and request body? -
Saving user input in Django table
So I've made a table in my Django program using HTML and js. The table takes can take in user input. When I refresh the webpage, the input still shows. But when I close the webpage, the user input disappears. I want the input to stay intact even when I close the page. I've tried writing some js code but it still doesn't work. How can I make the user input stay on the page even when I close the page. Either through a database or the local storage. You can find my code here. https://gofile.io/d/VZ9dxP. If anyone can help, I'll appreciate it. -
How do I add specific headers before each form in a model formset?
I have a model Question and another called Answer. The website will display all these questions (44 of them) and the user has to answer each of them. Here is what I want: What is your name? <--form input for name--> What is your age? <--form input for age--> ... and so on. But since they are part of different models, I'm having difficulty in rendering the relevant html since I can't display the question and take the user's input from a form at the same time. So far I have tried using the modelformset_factory but that doesn't allow me to add a question before every form. How can do I proceed? -
<select> element is displayed with default value with dashes (---------), how to change it?
models.py class City(models.Model): name = models.CharField(max_length=20) def __str__(self): return f"{self.name}" class Venue(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, blank=False) forms.py: class VenueForm(forms.ModelForm): class Meta: model = Venue fields = [ 'city', ] def __init__(self, *args, **kwargs): super(VenueForm, self).__init__(*args, **kwargs) self.fields['city'].label = 'Град' views.py: form = VenueForm(request.POST or None) context = { 'form': form, } return render(request, "add_venue.html", context) html render: {% for field in form %} <div class="fieldWrapper"> {{ field.label_tag }} <div class="errorcode{{field.html_name}}"> {{ field.errors }} </div> {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} How it looks in browser: <select name="city" required id="id_city"> <option value="" selected>---------</option> <option value="1">Пловдив</option> <option value="2">София</option> </select> So the problem is this default value with dashed <option value="" selected>---------</option>. Is there a way to remove / change it ? There is solution in docs but it is for ModelChoiceField which is not my case, it is ForeighKey reference. -
Djano first project errors
I am following this https://docs.djangoproject.com/en/3.0/intro/tutorial01/ I have seen many post referring to problems with getting djano and virtualenv set up. I have tried a lot of solutions to get everything working properly. However, I have been going in circles and i'm not sure why I cant proceed past: python manage.py runserver. OS: macos version: 10.15.4 and have python 3.7.7 / Python version : 3.7.7 python -m django --version : 3.0.6 I used homebrew to install python I have virtualenv working properly. Below is the error I keep getting. (env) user@Shadow-Keeper mysite % python manage.py runserver /usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'manage.py': [Errno 2] No such file or directory Below are the file contents im working in (env) user@Shadow-Keeper mysite % ls manage.py mysite (env) user@Shadow-Keeper mysite % ls init.py asgi.py settings.py urls.py wsgi.py -
Django static images aren't loading with variable
My static images are loading as <img src="/static/.png"> in the loaded HTML. I've looked at a bunch of Stackoverflow answers and I this is the best solution I found but it's still not working: {% if post.score %} {% load static %} {% with 'images/score/'|add:post.score|add:'.png' as image %} <img src="{% static image %}"> {% endwith %} {% else %} <img src="{% static 'images/blog/blog-img-1.jpg" alt=""> {% endif %} The web page loads but the images are blank. What am I missing? Thanks! -
Django Rest Framework: not showing latest records unless i restart the server
I'm using django rest framework, to create and retrieve records, but I noticed that when I create a new record and then try to fetch the list of records it doesn't show in the list of records even after 24h, unless I restart the gunicorn server. I think it has something to do with caching, but I didn't find anything intresting in the documentation about caching. I want to keep the caching as it is good for performance... but I want the new records to show, is there anyway to refresh the cache after a record is added? or anything similar? -
How can I set permission for seperate request methods in DRF ModelViewSet?
I'm fairly new to Django and Django Rest Framework and I can't figure out why my code isn't working. I have a Biz model that has a few fields: class Biz(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) description = models.TextField() address = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=100) phone = PhoneNumberField() which I serializer using ModelSerializer: class BizSerializer(serializers.ModelSerializer): class Meta: model = Biz fields = "__all__" And I use ModelViewSet to have an endpoint for it: class BizViewSet(viewsets.ModelViewSet): queryset = Biz.objects.all() authentication_classes = (authentication.TokenAuthentication,) permission_classes = [HasGroupPermission] required_groups = { "GET": ["__all__"], "POST": ["member", "biz_post"], "PUT": ["member", "biz_edit"], "PATCH": ["member", "biz_edit"], } serializer_class = BizSerializer You probably noticed HasGroupPermission. It is a custom permission I made to confirm the requesting user is in required group(s) the code is: def is_in_group(user, group_name): """ Takes a user and a group name, and returns `True` if the user is in that group. """ try: return Group.objects.get(name=group_name).user_set.filter(id=user.id).exists() except Group.DoesNotExist: return None class HasGroupPermission(permissions.BasePermission): """ Ensure user is in required groups. """ def has_permission(self, request, view): # Get a mapping of methods -> required group. required_groups_mapping = getattr(view, "required_groups", {}) # Determine the required groups for this particular request method. required_groups = required_groups_mapping.get(request.method, []) # … -
Not entirely sure how my two CBVs should inherit from a base
I have realized that I've got two CBV's with 99% identical code, so I figured I'd abstract it and use a mixin where I can put all the "generic" code. The only real difference between the views are the templates they are rendering. I'm having a hard time figuring out what should be put in what class. Here's the original two CBV's Class 1 @method_decorator(login_required, name='dispatch') class TimesheetEditorView(View): form_class = TimesheetModelFormSet def get(self, request, *args, **kwargs): year = kwargs.get("year") or datetime.datetime.now().year week = kwargs.get("week") or Week.thisweek().week user = request.user if invalid_week(week, year): raise Http404("Invalid week / year") next_year, next_week = calc_next(year, week) previous_year, previous_week = calc_previous(year, week) timesheet = Timesheet.objects.filter(year=year, week=week, user=user).order_by("project_id") # only show timesheet rows that belongs to logged in user timesheet_formset = self.form_class(queryset=timesheet) create_timesheet_form = TimesheetModelForm(user) context = { "create_timesheet_form": create_timesheet_form, "timesheet_formset": timesheet_formset, "week": week, "year": year, "next_week": next_week, "next_year": next_year, "previous_week": previous_week, "previous_year": previous_year, } return render(request, "timesheets/timesheet.html", context) Class 2 class TimesheetApproveView(TimesheetEditorView, View): def get(self, request, *args, **kwargs): year = kwargs.get("year") or datetime.datetime.now().year week = kwargs.get("week") or Week.thisweek().week next_year, next_week = calc_next(year, week) previous_year, previous_week = calc_previous(year, week) timesheets = Timesheet.objects.timesheets_to_approve(request.user).filter(year=year, week=week) context = { "timesheets": timesheets, "year": year, "week": week, "next_week": next_week, "next_year": next_year, … -
Modelviewset delete method override
I have User view and when I try to delete User, I want to to delete Invite which use same email. How to use destroy method to delete user{id} and Invite model in same email My models: class User(AbstractBaseUser): first_name = models.CharField(max_length=254) last_name = models.CharField(max_length=254) class Invite(models.Model): email = models.EmailField(unique=True) My viewset: class ActiveUserView(ModelViewSet): queryset = User.objects.all() permission_classes = [IsAuthenticated] http_method_names = ['get', 'delete'] serializer_class = SomeUserSerializer def destroy(self, request, *args, **kwargs): user = request.user for user in users: Invite.objects.filter(email=user.email) invite = Invite.objects.get(email=user.email) invite.delete() return Response(status=status.HTTP_204_NO_CONTENT)