Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How use pagination and .filter in django
How use pagination and filtering together? I have problem because they dont want to work eachother, without filter pagination work but with filter my app have crashes. I know they are some examples how do this on stack overrflow, and it seems thaat problem is in html file but this examples arent fully understandable for me, i would be appreciate if someone would show me what i must change in my code then i would understand this better. I am currently learning Django and still i have problems with understanding someones else code, i understand very well what ive done in my code but when i see someone else code that looks diffrent than mine then i dont know whats going on. views.py def Product_list(request, category_slug=None): category=None categories=Category.objects.all() products=Product.objects.all() paginator=Paginator(products, 6) page=request.GET.get('page') products=paginator.get_page(page) if category_slug: category=get_object_or_404(Category, slug=category_slug) products=products.filter(category=category) return render(request, 'shop/product/Product_list.html', {'products':products, 'category':category, 'categories':categories,}) product_list.html <div class='paginator'> {% if products.has_previous %} <a href='?page1'><<</a> <a href='?page={{products.previous_page_number}}'><</a> {%endif%} {%for num in products.paginator.page_range%} {% if products.number == num %} <strong>{{num}}</strong> {%elif num > products.number|add:'-3' and num < products.number|add:'3' %} {{num}} {%endif%} {%endfor%} {% if products.has_next %} <a href='?page={{products.paginator.num_pages}}'>>></a> <a href='?page={{products.next_page_number}}'>></a> {%endif%} </div> -
How to check if a user has permission when looping through all permissions?
I have a model named Account, which is connected to the default User model. As of now, I'm looping through all permissions associated with the Account model, but I also want to check if the Account profile page's user has the one or more of the specific permissions that's being looped through. The purpose is just to create an easy overview. I have also tried checking perms.cms.get_permission_codename. models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) site = models.CharField(max_length=50, choices=(('all', 'all'), ('danielk', 'danielk'), ('flis', 'flis'), ('vmusic', 'vmusic')), blank=True) site_role = models.CharField(max_length=50, choices=(('Administrator', 'Administrator'), ('Moderator', 'Moderator'), ('Editor', 'Editor'))) phone_number = models.CharField(max_length=8) birth_date = models.DateField() street_adress = models.CharField(max_length=255) note = models.TextField(blank=True); zip_code = models.CharField(max_length=4) city = models.CharField(max_length=255) def formatedPhone(self, country=None): return phonenumbers.parse(Account.phone_number, "NO") """ def __str__(self): return "%s %s" % (self.User.first_name, self.user.last_name) """ def get_absolute_url(self): return reverse('account-detail', kwargs={'pk': self.pk}) class Meta: verbose_name = 'Account meta' verbose_name_plural = 'Accounts meta' permissions = ( ("has_user_hijack_permission", "Allows the user to log in as others"), ("has_user_management", "Allows a user to deactivate/delete other users"), ("has_user_site_edit", "Allows a user to edit site and role details"), ("has_user_takeout", "Can export user details"), ) views.py class cms_users_user_permissions(generic.DetailView): model = Account template_name = 'cms/users/cms-users-user-permissions.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["permissions"] = Permission.objects.filter(content_type=ContentType.objects.get_for_model(Account)) #context['permissions'] … -
Implementation of a football ground booking system in Django
I am currently working on my new project of booking system implementation of football grounds. However, currently I am stuck at the searching of football grounds on a specific "from date" "to date" and "time in" "time to". I want to get the details of the ground based upon the availability. ie., the grounds that are showing as available should not be already booked. I am confused with filtering those unbooked grounds from the corresponding models. I have two apps; turfs and booking. There is a Turf model in turfs app models.py which has the basic information about the ground. The booking app contains a model Booking which has info. about booking a ground. Both of them are attached. I am stuck at the views to get the available grounds to display after excluding the booked grounds when a user searches for. Please help me in this regard. HTML Form: <form> <div class="col-md-3 mb-3"> <div class="input-group date" id="datepicker1"> <label class="sr-only">Date From:</label> <input type="text" class="form-control rounded" required name="datein" placeholder="Date From"/> <span class="input-group-addon"> <i class="#"></i> </span> </div> </div> <div class="col-md-3 mb-3"> <div class="input-group date" id="datepicker2"> <label class="sr-only">Date To:</label> <input type="text" class="form-control rounded" required name="dateout" placeholder="Date To"/> <span class="input-group-addon"> <i class="#"></i> </span> </div> … -
django 502 bad gateway causes multiple email send
I've a running django app with uwsgi, served by nginx. The same env I use for many applications (https://github.com/abidibo/cookiecutter-django). I've postfix configured to receive on localhost and django configured to send email through it. I have a view which when receiving a POST request creates some files and sends an e-mail. What happened is that after processing the POST request, the server returned a 502 page, and multiple e-mail were sent (almost 60 e-mail). It doesn't happen every time, just a few, and I couldn't reproduce the bug in my local environment. I can't figure out what happened, I mean, if some timeout occurred between django and uwsgi or postfix itself, then why sending all this e-mail, why the code was executed multiple times? In the application logs I see that a worker died: - *** HARAKIRI ON WORKER 4 (pid: 8836, try: 1) *** - HARAKIRI !!! worker 4 status !!! - HARAKIRI [core 7] 188.92.61.228 - POST /xxx/xxx/xxx/4/ since 1549027535 - HARAKIRI !!! end of worker 4 status !!! DAMN ! worker 4 (pid: 8836) died, killed by signal 9 :( trying respawn ... Respawned uWSGI worker 4 (new pid: 21942) In the nginx erro log I see: … -
gcc error while building docker image for django on windows
I am trying to build a docker image using Visual Studio Code following this tutorial "https://code.visualstudio.com/docs/python/tutorial-deploy-containers". I created a django app with a connection to a MSSQLserver on azure with the package pyodbc. During the build of the docker image i receive the following error messages: unable to execute 'gcc': No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for pyodbc and unable to execute 'gcc': No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for typed-ast I read solutions for linux systems where one shoudl install python-dev, but since i am working on a windows machine this is no solution. Then i read that on windows all the needed files are in the 'include' directory of the python installation. But in a venv installation this directory is empty... so i created a directory junction to the original 'include'. The error still exists. My docker file is included below. # Python support can be specified down to the minor or micro version # (e.g. 3.6 or 3.6.3). # OS Support also exists for jessie & stretch (slim and full). # See https://hub.docker.com/r/library/python/ for all … -
React-Native with Django backend development - Error: Network Error on axios call
I'm getting the following error with a React-Native app in development, trying to access a django development server running on http://127.0.0.1:8000 Error: Login.js:27 Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87) at XMLHttpRequest.dispatchEvent (event-target.js:172) at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580) at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394) at XMLHttpRequest.js:507 at RCTDeviceEventEmitter.emit (EventEmitter.js:190) at MessageQueue.__callFunction (MessageQueue.js:366) at MessageQueue.js:106 at MessageQueue.__guard (MessageQueue.js:314) The React-Native code making the call is this: handleRequest() { const payload = { username: this.state.username, password: this.state.password } axios .post(`login/`, payload) .then(response => { const { token, user } = response.data; // We set the returned token as the default authorization header axios.defaults.headers.common.Authorization = `Token ${token}`; // Navigate to the home screen Actions.main(); }) .catch(error => { console.log(error) }); } And within my Component I have defined componentWillMount() { axios.defaults.baseURL = 'http://127.0.0.1:8000'; axios.defaults.timeout = 1500; } I do not believe CORS is the issue because within the Django application settings.py I have included MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', .... ] CORS_ORIGIN_ALLOW_ALL = True How do I get my Android-Studio emulator to run with the Django Development server? -
How to show custom Django form validation errors as standard pop-ups
I have the following custom form validation: forms.py import os from django.core.exceptions import ValidationError def validate_allegato(allegato): ext = os.path.splitext(allegato.name)[1] valid_extensions = [ '.pdf'] if not ext.lower() in valid_extensions: raise ValidationError(u'Unsupported file extension.') class MyForm(forms.Form): allegato = forms.FileField(required=False, validators=[validate_allegato]) In the template, I would like to show the ValidationError as the standard HTML popups (as "Please fill in this field"). Is it possible? Thank you in advance -
Where is the settings.py file located in a github project based on django?
My main motive is to store the inportant secret keys in a separate .env file. How can I do that? -
How do I access my model's custom manager in a Django data migration context?
I have a custom model manager used in several of my models. This manager helps speed up DB inserts. I need to perform a data migration, and it involves migrating several millions of records/objects. I need my custom manager in my data migration. Does anyone know how to get it. In the data migration context if I run model.objects this gives me back Django's model manager. -
Formatting text from a list in a Django Template
I'm trying to format a list of strings passed into a template from a django view. Basically, I am trying to add commas to each entry except the last entry. words = ['word', 'word', 'word', 'word', 'word', 'word', 'word'] Here is my current code. {% block content %} {% for words, exp in dictionary %} <p class="text-center h1"> {% for word in words %} {{ word|default:"" }} {% if not word.last %} ,&nbsp; {% endif %} {% endfor %} </p> {{ exp|safe }} {% endfor %} {% endblock %} Results: word, word, word, word, word, word, word, Desired results: word, word, word, word, word, word, word I've tried several variations of this but nothing seems to prevent a comma being inserted after the last entry. Where am I going wrong? -
How to remove unwanted stuff from ImageField - Django
I want to remove currently and clear field from my django form. forms.py class MyUserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['user_phone','user_dob','user_gender', 'user_image', ] I am using crispy_forms also -
Django query Select X from Table where Y = Z
It's just yet hard to me to clearly understand the way that Django makes queries. I have two tables: Table A: +----+-----+----+ | id |code |name| +----+-----+----+ Table B: +----+----+ | id |name| +----+----+ Value of name of both tables are equal. What I need to do is to get the value of Table A column code, by comparing both tables' name Example: Table A: +----+----+----+ | id |code|name| +----+----+----+ | 0 | A1 |John| +----+----+----+ Table B: +----+----+ | id |name| +----+----+ | 0 |John| +----+----+ So, by comparing John (B) with John (A), I need A1 to be returned, since it's the code result in the same row that matches on Table A. Take into account that I only know the value of table B, therefore I can't get the value of code by Table A's name. -
Check if combination of field data exist when submitting a form
I want my form to check if the same name and date already exists in the postgresql so it does not produce a duplicate. models.py: class Event(models.Model): week = models.DateField(blank=False) name = models.ForeignKey(Employee, default=None, on_delete=models.CASCADE) sunday = models.CharField(max_length=50, default=None, null=True) monday = models.CharField(max_length=50) tuesday = models.CharField(max_length=50) wednesday = models.CharField(max_length=50) thursday = models.CharField(max_length=50) friday = models.CharField(max_length=50) saturday = models.CharField(max_length=50, default=None, null=True) def __str__(self): return self.week views.py: def test2(request): locationList = Location.objects.all().order_by('name') #Pulls location data from location table clientList = Client.objects.all().order_by('name') #Pull client data from client table if request.method == 'POST': form1 = EventForm2(request.POST) #Displays form to be filled out by user if form1.is_valid(): event = form1.save() #Saves form if valid data is entered messages.info(request, 'Successfully added') return HttpResponseRedirect(reverse('test2')) #Refreshes page to default else: form1 = EventForm2() #Form remains the same until valid data has been entered eventList = Event.objects.all().order_by('week', 'name') return render(request, 'app/test2.html', { # brings all the data into selected html "form": form1, "locationList": locationList, "clientList": clientList, "eventList": eventList, }) So if e.g. 27-01-2019; Bob Dylan already exists in the db, the form would not be valid to submit -
how to implement Django-Private-Chat in Django 2
I'm working on a project in which I need to implement private chat for user, so one user can communicate with another user privately, for that purpose I'm using django-private-chat but I'm confused in how to implement this in my application? Here's what I have done so far: 1): Install websockets 2): Install django-private-chat 3): Add it in INSTALLED_APPS 4): Then add in main urls.py like: From project.urls.py: path('', include('jobexpertapp.urls')), url(r'', include('django_private_chat.urls')), From myapp.urls.py: re_path(r'^users/$', views.UserListView.as_view(), name='user_list'), 5): Add a view for that: class UserListView(LoginRequiredMixin, generic.ListView): model = get_user_model() # These next two lines tell the view to index lookups by username slug_field = 'username' slug_url_kwarg = 'username' template_name = 'jobexpertapp/users.html' login_url = '/login' 6): Then add two templates: (a): users.html (b): dialogs.html From users.html: {% extends "base.html" %} {% block content %} <h3>Here you can see users avaliable for chat, excluding yourself (chat with yourself is possible thought):</h3> <div class="container"> {% for user in object_list %} {% if user != request.user %} <p>{{ user.get_full_name }}</p> <a href="{% url 'dialogs_detail' user.username %}" class="btn btn-primary"> Chat with {{ user.username }} </a> {% endif %} {% endfor %} </div> {% endblock %} From dialogs.html: {# This template is here just to demonstrate … -
StringRelatedField does not working as shown in the official tutorial
I went through the "Serializer relations" at https://www.django-rest-framework.org/api-guide/relations/ and got some problems with StringRelatedField relational field. So, in that tutorial they had given the models.py and serializers.py. I added the views.py and the urls.py. My views.py: # views.py from django.shortcuts import render from music.models import Album, Track from music.serializers import AlbumSerializer from rest_framework import generics class AlbumList(generics.ListCreateAPIView): queryset = Album.objects.all() serializer_class = AlbumSerializer class AlbumDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Album.objects.all() serializer_class = AlbumSerializer My urls.py: # urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from music import views urlpatterns = [ path('music/', views.AlbumList.as_view()), path('music/<int:pk>/', views.AlbumDetail.as_view(), name='track-detail'), ] urlpatterns = format_suffix_patterns(urlpatterns) Using the python manage.py shell command, I created an album and track object like the following: >>> from music.models import Album, Track >>> from music.serializers import AlbumSerializer >>> album = Album(album_name="Desert", artist="Beduin") >>> album.save() >>> track = Track(album=album, order=1, title="Finding Water", duration="2" ) >>> track.save() >>> track = Track(album=album, order=2, title="My Camel", duration="2" ) >>> track.save() But when I run the server, then I get this: { ... "album_name": "Desert", "artist": "Beduin", "tracks": [ "Track object (2)", "Track object (3)" ] ... } I thought that the StringRelatedField uses the unicode method to show the object representation. But in my case, … -
Django error when rendering form build_attrs got multiple values for keyword argument extra_attrs
I am trying to render a form in Django 1.11 and I get the following error: build_attrs() got multiple values for keyword argument 'extra_attrs' In my development env (with sqlite db) everything works fine but in my production env with a postgresql db (and apache) I get the above error. This is how I render my form in the template: <div class="col-md-6"> <form id="upload_form" method="post" enctype="multipart/form-data" action=""> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}" /> {{ form | as_bootstrap }} <button type="submit" id="upload-button" class="btn btn-danger">Upload</button> </form> </div> And this is how the form class is: class WFPDocumentForm(TranslationModelForm): """ For to upload Static Maps. """ permissions = forms.CharField( widget=HiddenInput( attrs={ 'name': 'permissions', 'id': 'permissions'}), required=True) _date_widget_options = { "icon_attrs": {"class": "fa fa-calendar"}, "attrs": {"class": "form-control input-sm"}, "format": "%Y-%m-%d %H:%M", # Options for the datetimepickers are not set here on purpose. # They are set in the metadata_form_js.html template because # bootstrap-datetimepicker uses jquery for its initialization # and we need to ensure it is available before trying to # instantiate a new datetimepicker. This could probably be improved. "options": False, } date = forms.DateTimeField( localize=True, widget=DateTimePicker(**_date_widget_options) ) #keywords = TaggitField( # required=False, # help_text=_("A space or comma-separated list of keywords"), # widget=TaggitWidget('TagAutocomplete')) … -
UnboundLocalError: local variable 'form' referenced before assignment
I want to create a new project creation page, the goal is that the user can validate his form, I have an error in the code below views.py @login_required def createproject(request): if request.method == 'POST': form = forms.CreateProject(request.POST) if form.is_valid(): return redirect('dashboard:dashboard-createproject') else: form = forms.CreateProject return render(request, 'dashboard/createproject.html', {'form': form}) urls.py urlpatterns = [ path('createproject/', views.createproject, name='dashboard-createproject'), ] This is the message error : local variable 'form' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/createproject/ Django Version: 2.1.4 Exception Type: UnboundLocalError Exception Value: local variable 'form' referenced before assignment -
403 Forbidden csrfmiddlewaretoken not working ajax/django
I want to make POST Request whenever user slides down content in html I found that csrfmiddlewaretoken: '{{ csrf_token }}' migth fix problem but it doesn't function handler() { $.ajax({ type: 'POST', url: 'open/' + identifier, data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(msg){ alert('wow' + msg); }, error: function (data) { alert('Failed ' + data); } }); } $( ".row" ).click(handler) -
How close am I to achieve my goal and what kind of techniques do I need to learn and apply to do that?
I am creating a database-driven website using the Django framework. The website is the front-end for a database that contains different Physics' questions and answers. The purpose of the database is to organize these questions according to topic and retrieve them on the website according to input made by the user. The first input is a selection form with 16 topics. The second input is a selection form with two types of questions (problem solving and multiple choices). The third input is radio checkboxes to have the questions with answers or without answers. The forth input is a selection form with different numbers 10 to 50 (10 steps between each) to determine the number of questions wanted. I have already created the website and the database. What is causing me a problem is the forms and model forms. I have been reading and summarizing the Django Documentation to understand the functionality of Django. I would like to have the opinion of experts where I am in the process and what kind of sources I can read to achieve my goal. I have been trying different sources but because I haven't been focusing on learning but focusing on building the project, … -
Constant data stream with Django channels
I am trying to get familiar with Django channels and web-sockets. I have a task - constantly stream data to whoever connects to the channel. Currently this is a pice of code from official tutorial with some improvements. And t class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' if not hasattr(self, 'vehicle'): # this produses constant data stream self.vehicle = connect('/dev/ttyACM0', wait_ready=True, rate=4) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # this part does not work! await self.send(text_data=json.dumps({ 'message': { 'mess': "Hi", 'yaw': self.vehicle._yaw, 'pitch': self.vehicle._pitch, 'roll': self.vehicle._roll, } })) async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) But now this code disconnects without showing anything in the front. I have found this answer, but that loop also does not work. If I move that while loop to the separate method and call it from receive method (which I don't show here for now to be short) - it works, but new user when enteres the channel - does not see messages from that while loop, but after restart the loop - messages go to all users. How can I make the data stream to be available for any user at any … -
Datatable multi search filter is not updated skipping table tabs
I am using Datatables on with Django rest_framework_datatables. The table is created with its search field that work perfectly. I added the multi search filter too, but when I skip between the pagination links these filters show always the same data (obviously the table show different data) I would to show in these filters all the "keywords" at disposal for the relative column, otherwise upgrade them with the data that the table shows. var table = $('reportsTable').DataTable({ "ajax": { 'ajax': '/api/myreports/?format=datatables', }, "columns": [ { "data": "id" }, { "data": "title" }, { "data": "subtitle" }, { "data": "description" }, ], initComplete: function () { this.api().columns().every( function () { var column = this; var select = $('<select><option value="">All</option></select>') .appendTo( $(column.footer()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option value="'+d+'">'+d+'</option>' ) } ); } ); } }); -
string indices must be integers django rest framework
I have a big serialized json field from which I'm trying to extract multiple keys then construct another json and send that via requests. Example: class ACtionViewSet(viewsets.ModelViewSet): logger = logging.getLogger('django') """ API endpoint """ queryset = Action.objects.all() serializer_class = ActionSerializer filter_backends = (filters.OrderingFilter, filters.SearchFilter, DjangoFilterBackend) filterset_class = ActionFilter # create new action for this workflow def create(self, request, *args, **kwargs): serializer = ActionSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() encode_data = json.dumps(serializer.data) wanted_key = ['task', 'task_default', 'slug'] new_action = {x: encode_data[x] for x in wanted_key if x in encode_data} print(new_action) workflow = json.dumps(new_action) response = requests.post( url='{}/workflows'.format(MISTRAL_URL), json=workflow, headers=headers ) # logging.debug(f"{self.response}") return Response({'response': response}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The error is string indices must be integers I'm a bit confused why is this happening, so can someone please explain what is happening here, thanks -
django allauth setting EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL doesn't work
I'm trying to change where the user is redirected to after they've confirmed their email address by clicking the link in the confirmation email. I'm using Django 2.0.10 with allauth, rest-auth and rest-framework. For the email verification, I'm using the default allauth view. In my settings.py I have set the following: EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' print('EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL') print(EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL) urls.py from allauth.account.views import confirm_email urlpatterns = [ re_path(r'^rest-auth/registration/account-confirm-email/(?P<key>[-:\w]+)/$', confirm_email, name='account_confirm_email'), ... ] My setting '/' is indeed printed in the console, so I think it is being picked up by the app. But when I follow the link in the email to the page (http://localhost:8000/api/v1/rest-auth/registration/account-confirm-email/MTQ:1gpYgM:_KpNYl-nd2iiG0qLIRRdVrmF8SM/) and then click the 'confirm' button, I am redirected to the default page /accounts/profile instead of the home page as specified by EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL. What am I doing wrong, how can I customise where the user is redirected after confirming their email address? Many thanks for any help! -
Django many to many fields
My django model looks like this: class A(models.Model): field1 = models.ForeignKey('UserProfile', default=None, null=True, blank=True) field2 = models.ForeignKey('test.A', default=None, null=True, blank=True) field3 = models.ForeignKey('test.B', default=None, null=True, blank=True) field4 = models.ManyToManyField('test.C', default=None, null=True, blank=True) field5 = models.ForeignKey('test.D', default=None, null=True, blank=True) field6 = models.ManyToManyField('test.E', default=None, null=True, blank=True) field7 = models.ManyToManyField('test.F', default=None, null=True, blank=True) Let's say I want to fetch an object A along with its list of field4, field6 and field7 ids. Once I fetch onject A , I do a.field4.values_list('id', flat=True) for all the manytomany fields. This creates additional request to db. Isn't it possible to fetch all the ids in single request? For eg: we use select_related for foreign key, don't we have similar thing for ManytoManyField? -
Django Rest Framework: How can I create endpoint for logging via Gmail (Google)?
I am trying to create API and I'm wondering how I can create an endpoint for authenticating via Gmail account. Seems like django-rest-auth supports only Facebook and Twitter. Anyone could give me tips?