Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        How total amount on cart be added to paystack/flatterwave paymentsso I want to add the total amount on my shopping cart to the Paystack Inline and flutterwave inline module as well as the user email. How can I do this? I do not want a fixed amount like in the documentation.. Which is easier to do, in flutterwave inline or paystack inline? And how can I do it?
- 
        Error With Django URL When Passing ParameterI am setting up a new URL path but I keep getting a page not found. This is my URL that isn't working: url(r'^collections/(?P<collection_name>\d+)$', collections.home, name='collections'), This is the function in my view: def home(request, collection_name, slug=None): collection_data = Collections.objects.get(collection_name=collection_name) try: logged_id = request.GET.get('admin_id') except: logged_id = "" return render(request, 'collections.html', {'collection_data':collection_data,'logged_id':logged_id}) If I turn it into a simple URL and remove the parameter from the URL and view function as follows, it works fine so I know I'm pointing to the right view: url(r'^collections$', collections.home, name='collections'), In the same file I have another URL as follows, and it also works fine: url(r'^store/(?P<seller_id>\d+)$', store.home, name='store'), This leads me to believe that I have a simple typo or something really basic that I am overlooking. Can anyone help me spot the error here? Thank you!
- 
        Using Celery/RabbitMQ/Flower in deployment with Django WebsiteI have a django website that utilizes celery scheduling async tasks. When I am in development mode, I run the commands: celery -A proj worker --pool=solo -l INFO flower -A proj --port:5555 celery -A proj beat -l info for my project to work. How can I run these commands on a cloud based hosting service such as pythonanywhere. In development I would go to localhost and port number to view rabbitmq and flower. How will this work in deployment?
- 
        Interacting with Django/Flask backend from web appI would like to ask if there is any documentation which covers interaction between a javascript-based front end with python packages running in the backend in django. So for example, if I want to display the amount of followers for a certain twitter account (obtained using e.g Tweepy), I can pre-code that twitter account in the back end and have the information displayed in the front end and use jinja2 to insert the data where I need into a Javascript-based UI (e.g Chart JS). However, if I want the user to specify the twitter account using an input text box, how can I best configure an input box, which will send the data back to the view, that would update the data based on that input, and return the new input to the template? For example entering 'Joe Biden' would send that information into the tweepy function, and then in my view, I would return the results of that function back into the template. I am currently creating the dashboards using Dash, but the dash UI feels a bit out of place with the UI for the dashboard. I cannot find any documentation that shows more than the hard-coding back-end …
- 
        Django: No post found matching the query when creating a postI just got slugs to work for my Post model using django-autoslug. But i'm now experiencing this error when i try to create a new post: Page not found (404) Request Method: GET Request URL: http://localhost:8000/post/new/ Raised by: blog.views.PostDetailView No post found matching the query Post Model class Post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = AutoSlugField(populate_from='title', null=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug, 'author': self.author}) views.py class PostDetailView(DetailView): model = Post def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(author__username=self.kwargs['author']) urls.py urlpatterns = [ path('', views.home, name='blog-home'), path('<str:author>/<slug:slug>/', PostDetailView.as_view(), name='post-detail') path('post/new/', PostCreateView.as_view(), name='post-create'), path('<str:author>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('<str:author>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- 
        How to use session key to authenticate/track users in djagno channelsHow can i use session key to authenticate/track users and save chats in database. consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.scope['session']['user_identifier']= self.room_name self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() ..........
- 
        freeze_time doesn't work inside invoked functions# test.py from freezegun import freeze_time from actual import DummyClass class DummyClassMock(DummyClass): def some_function(self): # does something class TestClass(): def setUp(self): self.dummy = DummyClassMock() @freeze_time('2021-01-01') def test_dummy_function(self): self.assertTrue((self.dummy.dummy_function - datetime.utcnow()).total_seconds() >= 1) # actual.py from datetime import datetime class DummyClass(): def dummy_function(self): return datetime.utcnow() My code goes along the above structure. With this, if I am executing the test_dummy_function individually, dummy_function is returning 2021-01-01 and test case is a pass. However, when I running this along with all the other test cases in the project, it is failing. Content is not dependent either.
- 
        IntegrityError at /music/4/music_create/ NOT NULL constraint failed: music_artist.as_pro_idI'm trying to make a create view for a user to make an object list of their favourite artists but I keep getting an integrity error and I'm not sure what's the source of the problem. heres my model.py class Artist(models.Model): artist_name = models.CharField(default='', max_length=200) artist_name2 = models.CharField(default='', max_length=200) artist_name3 = models.CharField(default='', max_length=200) artist_name4 = models.CharField(default='', max_length=200) artist_name5 = models.CharField(default='', max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) as_pro = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='artist') and here is my class based create view class MusicCreateView(CreateView): form_class = ArtistForm model = Artist template_name = 'music/music_create.html' success_url = reverse_lazy('accounts:profile') def get_object(self, *args, **kwargs): pk =self.kwargs.get('pk') obj = Artist.objects.get(pk=pk) instance = form.save(commit=False) instance.save() if not obj.as_pro.user == self.request.user: messages.warning(self.request, 'You need to be the associated profile to edit this') super(MusicCreateView, self).form_valid(form)
- 
        Display objects of a model using a dropdown menu, Django DetailView and get_context_data()I'm trying to display a model's information using the generic DetailView from Django, where there will also be a dropdown menu below to allow users choose a specific object of the Location model. I'm actually stuck with two problems, where the first one is that the Location.objects.all in the template doesn't show the objects currently in my database, the second problem is that the get_context_data doesn't seem to do what it is expected. How can I fix it or is there actually an easier way to implement it without overriding the context data? Thanks a lot for any help. urls.py path('show/<int:pk>', views.ShowsView.as_view(), name = 'show'), views.py class ShowsView(generic.DetailView): model = Location template_name = 'showlocation.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pk'] = self.request.GET['location'] return context <h1>Location: {{ location.location_name }}</h1> <ul> <li> As of Date: {{location.as_of_date}}</li> <li> Population: {{location.population}}</li> <li> Total Case: {{location.total_case}}</li> ... </ul> <form action="" method = "get"> <label for="locations">Choose a location:</label> <select id="locations" name="location"> <option value=1>trial</option> {% for Location in Location.objects.all%} <option value="{{Location.pk}}">{{Location.location_name}}</option> {% endfor %} </select> <input type="submit" value="Go"> </form>
- 
        Users have to request access to view post which are set to private DjangoI created a simple Post model with heading and body and other basic fields having a foreign key relationship with user model to get the author of model class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField() type_choices = models.CharField(choices=TYPE_CHOICES, max_length=15) author = models.ForeignKey(user_models.User, on_delete=models.CASCADE) Here TYPE_CHOICES are Private and Public I want to show all posts in my homepage but when any user (other than author of that post) click on post which is set to private they have to request access to view that post. And that request would be sent to the author of that post and they can then either accept or decline the request for that user to view their post. I tried to search this but I am not getting what I am trying to search instead some other results are shown . If anyone can help me out on this it would be very much helpful
- 
        Django - How do I limit the amount of objects returned per row?I have a page with a bootstrap card for every item like {% for item in item %} create a card with some content.... How do I limit the amount of cards created per row until it jumps to the row below it?
- 
        Django form error - cannot validate as input field is requiredi'm trying to pass html5 date input (start and end dates) into django forms, the main goal being to query for orders according to the start/end dates specified by the user on the front-end. the user indicates the start and ends dates on the front-end, which are then passed into my django model and into an AJAX call. my current error is this: i can't append the start/end date to my form or enter the if form.is_valid() portion of my code. when i print(form.error), i get: <ul class="errorlist"><li>start_time<ul class="errorlist"><li>This field is required.</li></ul></li><li>end_time<ul class="errorlist"><li>This field is required.</li></ul></li></ul> i don't understand why i'm getting this error - a POST request was made and managed to retrieve my start and end dates: <QueryDict: {u'csrfmiddlewaretoken': [u'FDRiqkYiP6j8yOAMLfb0sMe8wC8Z0K57'], u'start_date': [u'2018-12-17'], u'end_date': [u'2018-12-20']}> - the specified fields clearly aren't empty. is it something wrong with my forms.py? would really appreciate some assistance. thanks! views.py method from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from django.contrib import messages from django.utils import simplejson # JsonResponse from django.middleware.csrf import get_token from django.db.models import Count from django.views.generic import View from .forms import DateInput, DateForm from .models import Member, Driver, Order, Distance from collections import OrderedDict def date_input(request): if request.method …
- 
        Django Rest Framework "NoReverseMatch at /" Error When Visiting HomepageThis error only happens when I add an argument to the RetrieveAPIView url like so: urlpatterns = [ path('newgame/', newGame, name='newgame'), path('gameboard<int:pk>/', GameBoardView.as_view(), name='gameboard'), path('findgame/', findGame, name='findgame') ] If I go to the gameboard URL with a valid ID everything works, but if I go to http://127.0.0.1:8000/ I get this: NoReverseMatch at / Reverse for 'gameboard' with no arguments not found. 1 pattern(s) tried: ['api/gameboard(?P<pk>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'gameboard' with no arguments not found. 1 pattern(s) tried: ['api/gameboard(?P<pk>[0-9]+)/$'] Exception Location: /home/calvin/.local/share/virtualenvs/Online-Chess-UxyP2_C1/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /home/calvin/.local/share/virtualenvs/Online-Chess-UxyP2_C1/bin/python3 Python Version: 3.8.5 Python Path: ['/home/calvin/Online-Chess/chess', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/calvin/.local/share/virtualenvs/Online-Chess-UxyP2_C1/lib/python3.8/site-packages'] Error during template rendering In template /home/calvin/Online-Chess/chess/templates/base.html, error at line 0 Reverse for 'gameboard' with no arguments not found. 1 pattern(s) tried: ['api/gameboard(?P<pk>[0-9]+)/$'] If I take out the <int:pk> from the gameboard URL everything works again. Here is the View: class GameBoardView(generics.RetrieveUpdateAPIView): permission_classes = ([IsAuthenticated]) serializer_class = GameBoardSerializer queryset = GameBoard.objects.all() Here are my main URLs, incase that is useful: urlpatterns = [ path('', home, name="home"), path('<int:game_id>', game, name="game"), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('api/', include('api.urls')), path('rest-auth/', include('rest_auth.urls')) ] All of the errors I have found from other people seem …
- 
        Application labels aren't uniqueHas anybody encountered the following error? Building simple django python blog application. traceback Any ideas as to what it correlates to would be appreciated. Have not found a solution as of yet.
- 
        DjangoREST/React - Why is my frontend/backend token authentication system inconsistent?Every API call sent to my API has a header with a Bearer token auth, this is verified when I look through my browsers network panel. The authentication system works, however, whenever I spin up my dev server and try to carry on from my previously logged-in session, my system blocks every request as a 401 Unauthorized with: "Invalid token header. No credentials provided." as a response. Which is false because I'm sending over a header with the access token? I can only get it working if I logout and log back in as a user. Here is my axios instance that I used to make calls to my API. import axios from 'axios'; const baseURL = 'http://127.0.0.1:8000/api/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 9000, headers: { Authorization: 'Bearer ' + localStorage.getItem('access_token'), 'Content-Type': 'application/json', accept: 'application/json',}, }); axiosInstance.interceptors.response.use( (response) => { return response; }, async function (error) { const originalRequest = error.config; if (typeof error.response === 'undefined') { alert( 'A server/network error occurred. ' + 'Looks like CORS might be the problem. ' + 'Sorry about this - we will get it fixed shortly.' ); return Promise.reject(error); } if ( error.response.status === 401 && originalRequest.url === baseURL + 'auth/token/' …
- 
        How does the html button tag work with Django template?This is a Django template where the user submits some data through a django form to create a new "topic". I want to ask why does the html button work and submit the data I want even though I didn't specify it's type (submit, reset, or button)? {% extends "learning_logs/base.html" %} {% block content %} <form action ="{% url 'learning_logs:new_topic' %}" method="post"> {% csrf_token %} {{form.as_p}} <button>Add Topic</button> <comment><-- why does this button still work?</comment> </form> {% endblock %} Heres the views.py, if you need it. def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(data = request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topic') context = {'form':form} return render(request, 'learning_logs/new_topic.html',context)
- 
        error while using sys.exit() in a django template with iframeI am using a django based web application in python3. The logout method will redirect me to a different view and it will also call sys.exit("str") def logout(request): try: logger.info("Logging Out") del request.session['role'] del request.session['email'] del request.session['fullname'] del request.session["token"] session.close() sys.exit("bye") return redirect("/login") except Exception as e: logger.info("Exception : {}".format(e)) the above code was redirecting me as expected. Recently i introduced iframes in the template html, so that the pages are rendered in iframe when clicked from a side menu navigation <div class="sidenav"> <a href="lkpview" target="iframe1">About</a> <a href="logout" >Sign out</a> </div> <div class="main"> <iframe width="90%" height="300" name="iframe1"> </iframe> </div> Now if click on Sign out i am getting this error: A server error occurred. Please contact the administrator. [![enter image description here][1]][1] Not sure of this, and it did not occur before i introduced the iframe to the django template. Can anyone please help me here? Thanks
- 
        Could not aquire lock for task using cron job + uwsgi + DjangoThis is my uwsgi.ini file, and also there are other parameters in this uwsgi.ini file. [uwsgi] unique-cron = 0 -2 -1 -1 -1 python manage.py custom-command1 unique-cron = 5 0 -1 -1 -1 python manage.py custom-command2 unique-cron = 10 -2 -1 -1 -1 python manage.py custom-command3 unique-cron = 20 -3 -1 -1 -1 python manage.py custom-command4 While the application is running perfectly everyday, but from the above jobs, 3rd cron job is getting failed everyday with below error, and the job runs every 3 hours per day Could not aquire lock for task. Exiting... kindly advise what could be the reason ?
- 
        The view pages.views.contact didn't return an HttpResponse object. It returned None insteadplease I'd really appreciate that anyone in the forum can give to me a hint with this issue in my app "pages" I do not know where is the issue, I have this error The view pages.views.contact didn't return an HttpResponse object. It returned None instead. Thanks in advance. ├── PagesProject │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── Pipfile ├── Pipfile.lock ├── db.sqlite3 ├── manage.py ├── pages │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── static │ ├── logo.jpg │ ├── main.css │ └── top_banner.png └── templates ├── 404.html ├── base.html ├── contact.html └── page.html views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from .models import Page from .forms import ContactForm def contact(request): submitted = False if request.method == 'POST': form: ContactForm = ContactForm(request.Post) if form.is_valid(): cd = form.cleaned_data # assert False return HttpResponseRedirect('/contact?submitted=True') else: form = ContactForm() if 'submitted' in request.GET: submitted = True return render(request, 'contact.html', {'form': form, 'page_list': Page.objects.all(), 'submitted': submitted}) contact.html {% extends "page.html" %} {% block …
- 
        Django: Exclude users in M2MI want to exclude the Users that are inside the DocumentUsers table: from django.contrib.auth.models import User class DocumentUsers(models.Model): pnr = models.TextField() users = models.ManyToManyField(User) users = User.objects.exclude(username__in=[user for user in DocumentUsers.objects.all()]) Thank you for any suggestions
- 
        django imageField returns False when I delete the imageI am using three imageFields in a form. It works well but when I use the (built-in) delete function("effacer") as shown is this image below and I save my form, I get "False" in my database... How can I remove totaly the path ("uploads/...") of the deleted image instead of getting "False" ? Thanks, Here is my model: class Announce(models.Model): photo1 = models.ImageField(upload_to='uploads/', blank=True) photo2 = models.ImageField(upload_to='uploads/', blank=True) photo3 = models.ImageField(upload_to='uploads/', blank=True)
- 
        I am getting a None type for my request in serializer after PatchI am making a test that partial updates or patch some fields in my Product model. I should be enable to update any fields in my Product model. In my serializer, I have a url builder from the request object. However, request is not passed on my serializer or it is a None type. Thus, I am getting an error: AttributeError: 'NoneType' object has no attribute 'build_absolute_uri' How do I pass a request to my serializer? def test_patch_products(self): data = { 'description': 'This is an updated description.', 'type': 'New' } ... ... response = self.client.patch('/data/products/1/', data=data, format='json') In my view: def partial_update(self, request, pk=None): product= get_object_or_404(Product, pk=pk) serializer = ProductSerializer(product, data=self.request.data, partial=True, ) if serializer.is_valid(): serializer.save(uploaded_by=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In my serializer: class ProductSerializer(serializers.ModelSerializer): uploaded_by= serializers.StringRelatedField() thumbnail = serializers.SerializerMethodField() class Meta: model = CaptureGroup fields = ('__all__') def get_thumbnail(self, object): request = self.context.get('request') # request is None here thumbnail = object.thumbnail.url return request.build_absolute_uri(thumbnail) # here is the url builder
- 
        Scrapy Help: How can I get medical Centre data which medical are selected before make a payment.? this web automatically assign medical centerhttps://v2.gcchmc.org/book-appointment/ This is the website when I select country Bangladesh & city any one of this (Dhaka, Chittagong or sylhel) 3 cities are included this website, I currently trying to see which medical centre is selected.. when I fill up all information and submit then redirect the payment option after payment completed, automatically generates a pdf where is showing whose medical centre is appointed. Before making a payment how can I see which medical centre is selected..? Country Traveling To <select name="traveled_country" required="" id="id_traveled_country"> Select GCC country Bahrain Kuwait Oman Qatar Saudi Arabia UAE Yemen Success <div class="field medical-center-field medical-center-field-js disabled" style="display: block;"> Medical Center <select name="medical_center" id="id_medical_center" style="display: none;"> Select Medical CenterAuto assign <span class="info-icon"><i class="info circle icon"></i> Medical center has been assigned automatically</span></div> </div>
- 
        Django: You are trying to add a non-nullable field 'slug' to post without a default; we can't do thatI'm trying to add slug so that the title of a post appears in the url but i get this message on console: You are trying to add a non-nullable field 'slug' to post without a default; we can't do that Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py models.py class Post(models.Model): title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs)
- 
        Having trouble setting Many-to-one relationships in djangoI'm trying to rewrite my django models in order to solve some problems I found. I have 4 models: a Task, a Request, a Product and a Location. models.py class Location(models.Model): name = models.CharField(max_length = 255, unique = True) lat = models.FloatField() lon = models.FloatField() class Product(models.Model): name = models.CharField(max_length = 50, unique = True) class Request(models.Model): product = models.ForeignKey(to = Product, related_name = "product", on_delete = models.CASCADE) quantity = models.FloatField() task = models.ForeignKey(to = Task, related_name = "task", on_delete = models.CASCADE) class Task(models.Model): name = models.CharField(max_length = 50) priority = models.IntegerField() service_time = models.FloatField() start_location = models.ForeignKey(to = Location, related_name = "start_location", on_delete = models.CASCADE) end_location = models.ForeignKey(to = Location, related_name = "end_location", on_delete = models.CASCADE) task_type = models.CharField(max_length = 30) I'm currently strugling with the relationships. My main goal is to be able to make a POST request. Just like this one { "name": "task1", "priority": 1, "service_time": 1200, "start_location": { "name": "loc1", "lat": 1, "long": 1 }, "end_location": { "name": "loc2", "lat": 1, "long": 1 }, "task_type": "pickup & delivery", "requests": [ { "product": { "name":"Apples" }, "quantity": 1000 }, { "product": { "name":"Kiwis" }, "quantity": 2000 } ] } Some important points: I want to able …