Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i can't install mysqlclient and pillow in python
i want to install mysqlclient but it returns me (venv)amir@amg76:~/Documents/Computer/Python/Django/vira/virasciencecom$ pip3 install mysqlclient==1.3.7 Collecting mysqlclient==1.3.7 Using cached mysqlclient-1.3.7.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-c5i8m5ok/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-c5i8m5ok/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-c5i8m5ok/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-c5i8m5ok/mysqlclient/ the same thing happen when i try to install pillow and i use python 3.6 and ubuntu 17.10 can any body help me? -
Django Rest Framework Invalid serialization
I am trying to serialize a dictionary into Relationship Serializer, the data gets serialized fine but the validator returns false RelationshipSerializer: class RelationshipSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=False) related_user = UserSerializer(read_only=False) class Meta: model = models.Relationship fields = ( 'user', 'related_user', ) View: related_user_id = body["related_user"] related_user = models.User.objects.get(id=related_user_id) user = self.get_object() user_serializer = serializers.UserSerializer(user).data related_user_serializer = serializers.UserSerializer(related_user).data # user_serializer and related_user_serializer return valid data. data = {"user": user_serializer, "related_user": related_user_serializer} serializer = serializers.RelationshipSerializer(data=data) # Serializer works fine, it prints out data correctly serializer.is_valid() # Returns false return Response(serializer.data) When I log serializer.errors I get { "required": "This field is required.", "null": "This field may not be null.", "invalid": "Invalid data. Expected a dictionary, but got {datatype}." } I tried setting my serializer fields to null = True and required = False but still no luck -
Django using admin features for frontend
I am building out a Django application and so naturally followed the Django tutorials found in the docs. What I realized was that the admin app really offers a great deal of frontend support. Take a look at the following: And all that I needed was to create a short couple of classes in admin.py within the polls app (specified in tutorial 7). from django.contrib import admin from .models import Question, Choice class ChoiceInLine(admin.TabularInline): model = Choice extra = 3 # customize form for question class QuestionAdmin(admin.ModelAdmin): # display more than just string on "change list" page list_display = ('question_text', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question_text'] # title, field : Model.var fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] # add 3 Choice Models after fieldsets inlines = [ChoiceInLine] admin.site.register(Question, QuestionAdmin) admin.site.site_header = "Other Name" Most developers would appreciate the simplicity of the above script. I didn't need to write a single line of HTML, CSS, or Javascript. I was able to embed a list of my class Question into a viewer friendly format and I am able to use the search bar to filter for specific results. Now only one problem. I … -
Django 2.0 error in urls.py relating to views.py
I have the following code that seeks to load a page localhost/music/1 ...I have been following a tutorial that uses Django 1.9. The code that is throwing up the error is: music/urls.py # this is matching /music/1 where 1 is the album id path('(?P<album_id>)[0-9]+)/', views.detail, name='detail'), #note album_id is the variable being stored which can be passed music/views.py def detail(request,album_id): return HttpResponse("<h2>Details for Album id:" + str(album_id) + "</h2>") The error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/music/2 Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: admin/ music/ [name='index'] music/ (?P<album_id>)[0-9]+)/ [name='detail'] videos/ The current path, music/2, didn't match any of these. Can anyone post a fix/answer that will solve the problem. Thanks -
Django QuerySet union operator is not commutative after intersection
I use python 3.4.2 and django 2.0. My models.py class Solution(models.Model): name = models.CharField(max_length=200) Then in python console I do this: >>>a = Solution.objects.all().filter(id="1") >>>b = Solution.objects.all().filter(id__in=["1","2"]) >>>c = Solution.objects.all().filter(id="3") >>>ab = a.intersection(b) >>>abc = ab.union(c) >>>cab = c.union(ab) >>>abc <QuerySet [<Solution: Solution-id1>, <Solution: Solution-id3>]> >>>cab <QuerySet [<Solution: Solution-id1>]> Why abc != bca?? -
How to test sending mails in Django celery?
We use Django version 1.6, I came across this GitHub repo but their version required is 1.8+. Is there any other thing you guys have used. Kindly let me know. -
Include many-to-many field in admin page for reverse related model
For the model below I want to create an admin page where I directly can edit the user_permissions for the related django_user. How would I do that? from django.contrib.auth.models import User from django.db import models class MyModel(models.Model): django_user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) -
500 error when posting django rest
I am trying to post data using DRF modelviewsets and Axios. I have tried a couple different options so far with the same result, 500. I am able to get data using axios.get but not able to post data. I am new to rest and using ajax so I apologize if it is something obvious. Axios call var csrftoken = Cookies.get('csrftoken'); axios({ method: 'post', url: "/api/schedules/create", data: { "emp": this.emp.emp, 'start_time': this.startTime, "end_time": this.endTime, "date": this.today, "location": this.location }, headers : {"X-CSRFToken" : csrftoken } }) }, Serializer class SchedSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = ( 'location', 'emp', 'date', 'start_time', 'end_time' ) View class SchedViewSet(viewsets.ModelViewSet): queryset = Schedule.objects.all() serializer_class = serializers.SchedSerializer -
Associating a python social account with multiple django users
I want to connect the same (google-oauth2) account with multiple Django users using this credentials model: class CredentialsModel(models.Model): id = models.OneToOneField(User, primary_key=True) credential = CredentialsField() However, when I do so I get the error This google-oauth2 account is already in use. in social_core/pipeline/social_auth.py in associate_user. So I modified the pipeline with custom associate_user and social_user methods and removed the if user and social.user != user check in social_user: def social_user(backend, uid, user=None, *args, **kwargs): provider = backend.name social = backend.strategy.storage.user.get_social_auth(provider, uid) if social: # no `AuthAlreadyAssociated` when `user and social.user != user` user = social.user return {'social': social, 'user': user, 'is_new': user is None, 'new_association': social is None} Now the error is gone, but the (second) Django user did not get associated. The first user's association did not change. -
Datepicker covers the input field within a modal
The datepicker element is not created correctly within a modal, it covers the input field and I can not visualize the data html: <div id="datepicker" class="input-append date col-md-12" > <input type="text" class="form-control"> <span class="add-on"> <span class="arrow"></span> <i class="fa fa-th"></i> </span> </div> js: <script src="{% static 'assets/plugins/bootstrapv3/js/bootstrap.min.js' %}" type="text/javascript"></script> $("#datepicker").datepicker({ format: "dd/mm/yyyy", startDate: "01-01-2015", endDate: "01-01-2020", todayBtn: "linked", autoclose: true, todayHighlight: true, container: '#myModal modal-body', zIndex: 2048, }); -
Difference between named urls in Django?
What is the difference between these two named urls in Django? re_path('articles/(?P<year>[0-9]{4})/', views.year_archive), path('articles/<int:year>/', views.year_archive), They appear to do the same? -
Django - getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
I am learning django framework from last 4 days. Today I was trying to retrieve a URL in HTML template by using {% url "music:fav" %} where I set the namespace in music/urls.py as app_name= "music" and also I have a function named fav(). Here is the codes: music/urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ path("", views.index, name="index"), path("<album_id>/", views.detail, name="detail"), path("<album_id>/fav/", views.fav, name="fav"), ] music/views.py def fav(request): song = Song.objects.get(id=1) song.is_favorite = True return render(request, "detail.html") in detail.html I used {% url 'music:detail' %} But I dont know why this is showing this error: NoReverseMatch at /music/1/ Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['music\/(?P[^/]+)\/$'] -
How to pass a date (year) parameter to my url?
This is a huge rookie mistake but I can't figure it out. This is what I wanna do: I have a page displaying a list a years where an objects is available. I want that, when I click on a year, it takes me to the corresponding YearArchiveView. I just don't succeed in passing the right parameter to the URL. Passing a template tag obviously doesnt work so what is the right way to do it ? I get this error: TemplateSyntaxError at /receipts/ Could not parse some characters: |{{y||date:"Y"}} My template: <ul> {% for y in years_available %} <li><a href="{% url 'receipt_year_archive' year={{y|date:"Y"}} %}">{{y|date:"Y"}}</a></li> {% empty %} <p>No Receipt Yet</p> {% endfor %} </ul> My view: class ReceiptListView(LoginRequiredMixin, ListView): model = Receipt template_name = 'receipts.html' def get_queryset(self): queryset = Receipt.objects.dates('date_created','year',order="DESC") return queryset def get_context_data(self, *args, **kwargs): context = super(ReceiptListView, self).get_context_data(**kwargs) context['years_available'] = Receipt.objects.dates('date_created', 'year', order="DESC") return context My urls.py: url(r'receipts/(?P<year>[0-9]{4}/$)',views.ReceiptYearArchiveView.as_view(), name='receipt_year_archive'), -
How to use Django Rest API in Django normal project for autocomplete using Select2?
In my project, I have a model named Product. The model consists of products which have following entities: name, id, price .... and so on. In my project, an admin can add a new/old product anytime. Now, for searching, I want to add autocomplete. I want to use Select2. So users don't have to memorize the name of the products. To do that I found out here in the Select2 doc that : Select2 comes with AJAX support built in, using jQuery's AJAX methods With this, I can search an API and fetch the data to show the users in autocomplete search field. My Question: Should I create a Django rest API and use that API to store products and fetch the data? 1.1 Would it be wise? 1.2 Is it possible to make a rest API within a normal Django project? If not then how to do that? Or should I just use a normal urls.py and querying the result from Select2 ajax function to that urls.py and to a custom query.py and fetch the data directly from the database? -
Searching for django_celery_beat alternative
I wasted a lot of time trying to install django_celery_beat with no results, with the following error: error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2 I'm searching for an alternative: package or do it myself if is not very complex and if I have a tutorial/start code. -
Django ForeignKey and OneToOneField query speed
I've seen this : https://groups.google.com/forum/#!topic/django-users/VEDZtuND2XM But on that answer, Ronaldo said just about convenience not the speed of query speed. Is there speed or performance difference between ForeignKey(unique=true) and OneToOneField? Or is there any other advantages on using OneToOneField than ForeignKey(unique=true) ? -
where to check for conditions in generic UpdateView in Django
I'm using Django 2.0 I have a model Note and using generic update view to update the note object. The URL configuration is like app_name = 'notes' urlpatterns = [ path('<int:pk>/', NoteUpdate.as_view(), name='update'), ] which is accessbile via it's namespace setup in app.urls /notes/<pk> I want to make some condition check in the view before loading the view or saving updated value. Since, a note can be shared with any user and there is single template to view and update the note. I want to check for whether the user is owner of the note or whether the note has been shared with the user and has write permission granted. class NoteUpdate(UpdateView): template_name = 'notes/new_note.html' model = Note fields = ['title', 'content', 'tags'] def get_context_data(self, **kwargs): context = super(NoteUpdate, self).get_context_data(**kwargs) """ check if note is shared or is owned by user """ note = Note.objects.get(pk=kwargs['pk']) if note and note.user is self.request.user: shared = False else: shared_note = Shared.objects.filter(user=self.request.user, note=note).first() if shared_note is not None: shared = True else: raise Http404 context['note_shared'] = shared_note context['shared'] = shared return context @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) This is what I tried in get_context_data() but it is giving … -
After set Setting Cache Headers in NGINX, (django) all images disappeared, how to solve?
this is my cahe settings, when i delete this lines, image come back, if i set this, images are disappeared, help someone!) location ~* \.(?:jpg|css|js|html|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ { expires 365d; access_log off; add_header Cache-Control "public"; } -
limit choices in drop downs in django rest browsable api
Is there a way to limit what fields are populated (such as in dropdown selectors or list selectors) in the DRF browsable API? It would be really useful if there was a way to link the objects populated in these fields to be set according to a get_queryset() function. This page seems to hint that it might be possible, I just can't find an example of how to do it: http://www.django-rest-framework.org/api-guide/filtering/ -
when i gave command "python manage.py startapp foodblog" does not work and give the error.Please share solution. Thank in advanced
enter image description hereError screenshot is showed below -
How to setup a simple Open EDX site in Django?
Hello I have searched for this, and found no answer. I recently downloaded: https://github.com/edx/edx-platform I want to setup django to use it. But I found no docs. What I found is this Bitnany Installer: https://bitnami.com/stack/edx +1 Gb And the docs does not appear to exits: https://openedx.atlassian.net/wiki/display/OpenOPS/Open+edX+Installation+Options But is there a simple way I can setup Opem EDX; without 1 Gb download, which I can not aford right now? Thank you in advance. Rodolfo -
Get status of all objects of model
models.py class Room(models.Model): # Default all rooms are Free number = models.ForeignKey(RoomNumber) class Reserved(models.Model): visitor = models.ForeignKey(Visitor, on_delete=models.PROTECT) room = models.OneToOneField(Room) reserved_date = models.DateTimeField() begin_date = models.DateTimeField() end_date = models.DateTimeField() How to get status of all Rooms in a List. In status of all rooms are in : Reserved Free Rooms Busy Rooms I myself tried to do this: ListView reserved = Reserved.objects\ .filter(room=OuterRef('pk'))\ .filter(begin_date=timezone.now())\ .values(count=Count('pk')) Room.objects.annotate(reserved=Subquery(reserved[:1])) but no result :( And how to get in template status of rooms? Through if else condition? Thanks you all in advance -
What should I learn to build a website that receives a file from user?
I am new to web design and I need to know what topics I should learn in order to build a website that receives a file from user, processes it and gives an output in a different page. I use python, so it would be nice if this was possible using Django. I would appreciate if someone guided me. -
relation does not exist(postgresql, django)
I'm using django with postgresql. But when I run the app, I get the following error: relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... I searched for this error, but the only situation people talked about was when the name of the table had mixed case characters. But the table name in my case is all in small letters so this shouldn't happen. What is wrong here? Thanks p.s. This is the project I'm working with. https://github.com/mirumee/saleor -
Deploying Web Application built with django(DRF) and Vue(Frontend) in aws
How to deploy an web application with Separate Frontend(Vue) and Backend(Django-DRF) Servers in AWS ?