Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - return authorizatuin token expiry time after registration
I want to return expiry time of auth token after registration. How can i do this? I am also using djano rest knox. serializers.py class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( validated_data['username'], validated_data['email'], validated_data['password'], first_name=self.validated_data['first_name'], last_name=self.validated_data['last_name'],) return user views.py class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) -
Invoke wrapper for tasks to run with prefixes
I am just starting to look at Invoke and I am having some trouble understanding how the context works and what the task decorator is really doing. My issue is that I am trying to create a wrapper for tasks that tells them prefixes needed. The specific example is I am using this to create a local web app deployment framework with stages. Each stage has its own virtual environment. I am attempting to create a process that allows you to select the stage (done), but then every process that uses that virtualenv and directory needs to be wrapped in context.prefix(f"workon {venv}"). this is where I am having trouble and like any good programmer I am lazy and don't want to be stuck typing this for every commmand. Thanks -
Django: redirecting a view and using include()
I'm essentially trying to make my URLs more readable by incorporating a slug that is not used for lookup purposes in my views. Previously, I had this in my main URLconf: urls.py path('<int:team_pk>/', TeamDetails.as_view(), name='team_details'), path('<int:team_pk>/', include('tracker.urls', namespace='tracker')), So I had urls like mysite/1/stuff and mysite/1/more/stuff. Then I added a slug field to my Team model. The behavior I want is for any url that only includes a team_pk to be redirected to an expanded URL that incorporates the slug. For example, mysite/1/ should redirect to mysite/1/team_1_slug and mysite/1/stuff should redirect to mysite/1/team_1_slug/stuff. It's this latter behavior that I'm having trouble with. I modified my URLconf to this: path('<int:team_pk>/', TeamRedirectView.as_view(), name='team_details'), path('<int:team_pk>/<slug:team_slug>/', TeamDetails.as_view(), name='team_details_redirected'), path('<int:team_pk>/<slug:team_slug>/', include('tracker.urls', namespace='tracker')), Then I have a simple view to redirect: # views.py class TeamRedirectView(generic.RedirectView): def get_redirect_url(self, *args, **kwargs): team = get_object_or_404(models.Team, pk=self.kwargs['team_pk']) return reverse('team_details_redirected', kwargs={'team_pk': team.pk, 'team_slug': team.slug}) This works for redirecting mysite/1/ to mysite/1/team_1_slug, but any url tag that points to a url inside the tracker app throws a reverse error because I'm not supplying team_slug to the url tag. So I'm basically trying to get my RedirectView to be a little more universal and add this slug to any url without having to … -
Django: how to use helper function to get model object if exists?
I am having this model which is conversations related to ads in classified ads website: class Conversation(models.Model): ad = models.ForeignKey(Ad, on_delete=models.CASCADE) starter = models.ForeignKey(User, related_name='starter', on_delete=models.SET_NULL, null=True) participants = models.ManyToManyField(User) def get_absolute_url(self): return reverse('messages-conversation', kwargs={'pk':self.pk}) def get_if_exists(self, **kwargs): try: return self.objects.get(**kwargs) except self.DoesNotExist: return None in the view I want to check if conversation about that ad already exists with get_if_exists, but I get the errors: If use conversation = Conversation.get_if_exists(ad=ad, starter=request.user) I get Exception Value: name 'self' is not defined If use conversation = Conversation().get_if_exists(ad=ad, starter=request.user) gets: Exception Value: Manager isn't accessible via Conversation instances What I am doing wrong? How to make it so I can use one line in the view to get object if exist and None if doesnt exist? -
Problem in uploading content written using Tiny MCE in Django
I am using Tiny MCE as my Rich Text Editor in my blogging website. But my posts are not getting uploaded when I try to write articles using TinyMCE but getting uploaded while I use a normal text editor. I didn't get suitable answers from google. An error shows up saying 'content.css' is missing whereas I don't have any such CSS in my static folder. My code: models.py: class Post(models.Model): title = models.CharField(max_length=100) cover = models.ImageField(upload_to='Blog Image') content = models.TextField() forms.py: class PostForm(ModelForm): class Meta: model = Post fields = '__all__' class Media: js = ('js/tinyInject.js',) def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['content'].widget.attrs = {'class': 'form-control', 'id': 'id_content'} tinyInject.js var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"; document.head.appendChild(script); script.onload = function () { tinymce.init({ selector: '#id_content', width: 1200, height: 300, plugins: [ 'advlist autolink link image lists charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking', 'table emoticons template paste help' ], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | link image | print preview media fullpage | ' + 'forecolor backcolor emoticons | help', menu: { favs: … -
Django DRF Post with files and data works in Postman, not Python. No TemporaryUploadedFile
Running a Django App locally, i can use Postman to upload a zip file along with some dict data. Breaking the application in 'def Post()' i can see that Postman's successful upload: request.data = <QueryDict: {'request_id': ['44'], 'status': [' Ready For Review'], 'is_analyzed': ['True'], 'project': ['test value'], 'plate': ['Plate_R0'], 'antigen': ['tuna'], 'experiment_type': ['test'], 'raw_file': [<TemporaryUploadedFile: testfile.zip (application/zip)>]}> Postman offers the following python code to replicate these results in my python script: import requests url = "http://127.0.0.1:8000/api/upload/" payload = {'request_id': '44', 'status': ' Ready For Review', 'is_analyzed': 'True', 'project': 'test value', 'plate': 'Plate_R0', 'antigen': 'tuna', 'experiment_type': 'test'} files = [ ('raw_file', open(r'C:/testfile.zip','rb')) ] headers = { 'Content-Type': 'application/x-www-form-urlencoded' } response = requests.request("POST", url, headers=headers, data = payload, files = files) print(response.text.encode('utf8')) running this code directly and retrieving the request.data (server side) i see the binary representation of the xlsx file is in the object and the payload data is not there (this is the error in the response). How do i get my python script to produce the same server-side object as postman? Specifically how do i upload my data such that the file is represented as: <TemporaryUploadedFile: testfile.zip (application/zip)> Thanks. -
Accessing folders present inside media folder in django
I am new to django. I have created application using it where user can see the videos of their undergoing subjects. I have uploaded multiple videos inside folder name uploadcbse and uploadncert which is present inside media directory. Now I want to display this video in html page but can't access it using {{Media_URL}}{{videofile}}. I am sure it's an error in mentioning path properly because other text fields have been displayed correctly. -
Dashboard using Django or DjangoRestFramework
I was looking at https://robinhood.com/ (they use Django) and noticed that most of their requests are going to https://api.robinhood.com/... I wanted to know the benefits of using an external endpoint like api.robinhood.com instead of just putting all of the methods in one Django project. Does this make sense? Thanks! -
Errors in post Django testing procedure
I'm trying to make a test for incrementig votes in Django polls tutorial application. I made two identical tests in django shell and in test.py. None of them working and results are different. The app is working well. In the 1st case response of post request is 200 , no incrementing value. In the 2nd case a '404' ! for same command as the 1st case and error for Choice object. These are the two situations: *1) django shell: Code: #python manage.py shell < 1.py #>>> exec(open('1.py').read()) from django.test.utils import setup_test_environment setup_test_environment() from django.test import Client client = Client() from polls.models import Choice print("votes before",Choice.objects.get(id=7).votes) response = client.post('/polls/3/vote/', {'name':'choice','value':'7'} ) print(response.status_code) response = client.get('/polls/3/results/') print(response.content) print("votes after",Choice.objects.get(id=7).votes) Result: votes before 5 200 b'<h1>What do you like?</h1>\n\n<ul>\n\n <li>Coffee -- 5 votes</li>\n\n <li>Coca Cola -- 4 votes</li>\n\n</ul>\n\n<a href="/polls/3/">Vote again?</a>\n' votes after 5 *2) django test: Code: from .models import Choice class TestVote(TestCase): def test_if_vote_is_incrementing1(self): response = self.client.post( '/polls/3/vote/', data = {'name':'choice','value':'7'} ) self.assertEqual(response.status_code, 200) def test_if_vote_is_incrementing2(self): votes0 = Choice.objects.get(id=7).votes response = self.client.post( '/polls/3/vote/', data = {'name':'choice','value':'7'} ) votes1 = Choice.objects.get(id=7).votes self.assertEqual(votes1, votes0+1) Result: Creating test database for alias 'default'... System check identified no issues (0 silenced). FE ====================================================================== ERROR: test_if_vote_is_incrementing2 (polls.tests.TestVote) ---------------------------------------------------------------------- … -
Cannot modify pandas DataFrame saved in Django model
in models.py, i created this model: from django.db import models from Data.DataFrame import df #df is the DataFrame # Create your models here. class Custumer(models.Model): ip = models.CharField(max_length=100) products = df in the python shell, i did this: In [1]: from app.models import Custumer as C In [2]: new = C.objects.create(ip='1') In [3]: new.products Out[3]: B000JMLBHU B002AJ7X2C B002D48NBO B0031Y9CPG B0032YXH2E B00359FHZ6 ... B00LDD8NDO B00LF56Y3Q B00LKQNFVE B00LKS5WUY B00LLWDUDK B00LMTLV24 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 [1 rows x 1000 columns] In [4]: new.products['B000JMLBHU'] =1 In [5]: new.products Out[5]: B000JMLBHU B002AJ7X2C B002D48NBO B0031Y9CPG B0032YXH2E B00359FHZ6 ... B00LDD8NDO B00LF56Y3Q B00LKQNFVE B00LKS5WUY B00LLWDUDK B00LMTLV24 0 1 0 0 0 0 0 ... 0 0 0 0 0 0 [1 rows x 1000 columns] In [6]: new.save() But, when i do quit() in shell and open it again, the 1 that i wrote in the first column disappears. How can i modify DataFrames saved in the model -
Blueimp Jquery FileUpload - Django-jQuery-File-Uploader-Integration Demo in Django version 3.0.8
As part of a learning process, I'm trying to implement https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo. I fully expect bugs as this was written in a much earlier version of django. I am running django version 3.0.8. When I attempt to upload a file, I get the following error. I am unable to figure out from research how to fix this bug. I'm sure there are other bugs with this code, but one step at a time :) error File "C:\Users\antho\Developer Apps\PyCharmProjects\EGHub\esr_submit\views.py", line 101, in esr_submit if not request.POST[u"uuid"]: File "C:\Users\antho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'uuid' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.esr_submit, name='esr_submit'), views.py from django.shortcuts import render, redirect, reverse from .models import RequestAttachment, ServiceRequest from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest, HttpResponseRedirect from django.conf import settings import os def esr_submit(request): # used to generate random unique id import uuid # settings for the file upload # you can define other parameters here and check validity late in the code options = { # maximum file size (must be in bytes) "maxfilesize": 10 * 2 ** 20, # 10 mb # minimum file size (must be in bytes) "minfilesize": 1 * 2 ** 10, # … -
Django unique_for_date with DateField(editable=False)
Django documentation says: If any unique_for_date constraint involves fields that are not part of a ModelForm (for example, if one of the fields is listed in exclude or has editable=False), Model.validate_unique() will skip validation for that particular constraint. The model below sets unique_for_date for a DateField with editable=False, as mentioned above. Based on the excerpt from the documentation above, I would expect the unique_for_date constraint to be skipped during validation. However, the test below passes, showing that validate_unique() does raise a ValidationError due to unique_for_date (using Django 3.0). What am I missing? from django.db import models from django.utils import timezone from django.core.exceptions import ValidationError from django.test import TransactionTestCase class MyModel(models.Model): name = models.CharField(max_length=10, unique_for_date='date') date = models.DateField(editable=False) class MyModelTests(TransactionTestCase): def test_unique_for_date(self): name = 'bird' today = timezone.now().date() MyModel.objects.create(name=name, date=today) my_model_with_duplicate_name_date = MyModel.objects.create( name=name, date=today) with self.assertRaises(ValidationError) as a: my_model_with_duplicate_name_date.validate_unique() self.assertIn('Name must be unique for Date date.', a.exception.messages) -
Django throws an exception when it stops
When I stop my django server by pressing ctrl + break as django says (or it restarts itself when the code changes), but not every time, it throw this exception: Exception ignored in: <function Local.__del__ at 0x00000195D172EEA0> Traceback (most recent call last): File "C:\Users\Max\AppData\Local\Programs\Python\Python37\lib\site-packages\asgiref\local.py", line 90, in __del__ File "C:\Users\Max\AppData\Local\Programs\Python\Python37\lib\_weakrefset.py", line 59, in __iter__ TypeError: 'NoneType' object is not callable -
How do I create content previews of 3rd-party links (in a similar way to Twitter and FB)?
I want my users to be able to add 3rd-party links to a page and on that page I want to display a preview of each link, just like Twitter and FB does with their users' links. I know this uses the og and twitter meta tags, but I want to know exactly how to do this. I am using Django. This image is an example of the type of preview I want to create. -
Heroku build succeeded but failed to deploy
My Django website is running as expected on my machine but the Heroku logs saying Python can't open file 'manage.py' however my manage.py is working on my local machine. I'm running my Django project locally in a docker container. Below is a screenshot of the Heroku log. How do I make Heroku find "manage.py"? -
How to include in django template a reverse url in translation
I have the following block of code, And I want to include a url to the login page, after the user logs out, in a translatable text. Unfortunately, translation blocks cannot include tags, and I get the following error: SyntaxError: Translation blocks must not include other block tags: url "account:login" {% blocktrans %} You have been successfully logged out. You can <a href="{% url "account:login" %}">log-in again</a>. {% endblocktrans %} What would be the right way to achieve something like this? -
Displaying image urls during iteration without using the url method
I'm trying to deploy a Django Blog I built to Heroku, but I'm having some issues displaying the thumbnail images of blog posts when rendering my templates. When I first developed the app I was using {{ post.thumbnail.url }} to render the images, and everything was working fine. Now that I've deployed to Heroku I'm swimming in broken links. From [this post][1] I've learned that The "image.url" format in the html does not work on staticfiles/Heroku. That means I would need to use {% static "image url" %} to display the images. The problem is: I'm rendering these posts and their images by iterating over a queryset of posts I'm passing to my templates. Eg: {% for post in most_recent %} <a href="{{ post.get_absolute_url }}"> <div class="item d-flex align-items-center"> <div class="image"><img src="{{ post.thumbnail.url }}" alt="..." class="img-fluid"></div> <div class="title"><strong>{{ post.title }}</strong> <div class="d-flex align-items-center"> <div class="views"><i class="icon-eye"></i>{{ post.view_count }} </div> <div class="comments"><i class="icon-comment"></i>{{ post.comment_count }}</div> </div> </div> </div></a> {% endfor %} How can I get the url of the post's thumbnail image without using the url method? This is what the model looks like: class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) #comment_count = models.IntegerField(default=0) #view_count = models.IntegerField(default=0) … -
I am facing mapping user and profile in django
I am facing a problem with django profile mapping with user.There is coming None in admin view this is my model.py profile_of = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) session = models.CharField(max_length=20, blank=False, null=False ) batch = models.IntegerField() # batch = models.IntegerField(blank=False, null=False) iit_program = models.CharField(blank=True, choices=IIT_PROGRAM, max_length=10) college = models.CharField(max_length=50) graduate_university = models.CharField(max_length=50, default='Dhaka University') graduate_department = models.CharField(max_length=50, default='Software Engineering') photo = models.ImageField(blank=True) is_current = models.BooleanField(default=True) This is my views.py from django.shortcuts import render from .forms import UserProfile from django.contrib.auth.decorators import login_required @login_required(login_url= '/accounts/login/') def userProfileview(request): form = UserProfile(request.POST or None) if form.is_valid(): form.save() context = {'form':form} return render(request,'userprofile.html', context) This is my forms.py from django import forms from .models import Profile class UserProfile(forms.ModelForm): class Meta: model = Profile fields = ['iit_program','batch','session','graduate_university','graduate_department','photo'] -
Windows 10, Docker with Django can can createsuperuser but cannot log in site admin?
I'm following along a book, but I'm on window 10. I'm not sure why the createsuperuser is not affecting the website that gets generated. From the dockerfile: #pull base image FROM python:3.7 #set env vars ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 #set workdir WORKDIR /code #install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pip install --system #copy over rest of project file COPY . /code/ and my docker-compose.yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 I use the command without any error docker-compose up -d And the website (default http://127.0.0.1:8000) loads without an issue, TO create a superuser, following the instructions, I do: docker-compose exec web python manage.py createsuperuser and follow the prompt, and it says I successfully created the superuser, but every time when I try to log in through the admin panel (http://127.0.0.1:8000/admin/) it tells me Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. If I go back and try to create the superuser it again, it says the username is already taken. If I run docker-compose down the website goes down, so docker is … -
displaying the render response on the javascript on HTML
here is the view.py here is the data that I try to use it in javascript on the script me trying to reach the data here is the urls -
Django 'WSGIRequest' object has no attribute 'completed_todo'
I get an error 'WSGIRequest' object has no attribute 'completed_todo' when I go to a link in my Django project Here it is my code: My models.py: class Todo(models.Model): text = models.CharField(max_length=300) date = models.DateTimeField(auto_now=True) def __str__(self): return self.text class Meta: verbose_name = "Todo" verbose_name_plural = "Todos" class CompletedTodo(models.Model): text = models.CharField(max_length=300) date = models.DateTimeField(auto_now=True) def __str__(self): return self.text My views.py: class Comp: def complete_todo(self, todo_id): self.todo_id = todo_id completed_text = Todo.objects.get(id=todo_id).text completed_date = Todo.objects.get(id=todo_id) completed_todo = CompletedTodo.objects.create(text=completed_text, date=completed_date) self.completed_todo = completed_todo return HttpResponseRedirect('/') def completed_tasks(self): context = {'todo': self.request.completed_todo} return render(self, 'main/completed_tasks.html', context) My urls.py: path('completed_tasks', views.Comp.completed_tasks, name='completed_tasks'), path('complete_todo/<int:todo_id>', views.Comp.complete_todo, name='complete_todo') The error that I get: WSGIRequest' object has no attribute 'request' Request Method: GET Request URL: http://localhost:8000/completed_tasks Django Version: 3.0.8 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'request' Exception Location: D:\Edgar\IT\Programming\django\projects\Todo App\todo\main\views.py in completed_tasks, line 49 Python Executable: D:\Edgar\IT\Programming\django\projects\Todo App\venv\Scripts\python.exe Python Version: 3.8.3 -
Is there a way to unitary test the arguments passed to Model or Q object?
In my unit tests, I understand how I can mock objects per context, to avoid interacting with any kind of persistent datastore. I can even mock the Q object to test how many times it has been called, which is really useful. But I'm still uncomfortable with the fact that while I'm mocking my interaction with the datastores, I'm still assuming that my code works©, that the datastore (or the ORM in this case) is receiving the data correctly, through the "proper channels" so to speak. Case in point: # code to test def related_stuff(): return Stuff.objects.filter( parent__user__city_name="Las Vegas" ) # more code... # testing above @mock.patch(f"{path_to}.Stuff.objects") def test_related_stuff(stuff_mock): stuff_mock.filter.return_value = stuff_mock stuff_mock.filter.assert_called_once_with(parent__user__city_name="Las Vegas") How can I actually test that the parent__user__city_name lookup pattern is actually correct and wont result in an error? I'm assuming there's no way to test this without touching the datastore, but any opinions are appreciated. -
How do I create three checkouts for subscriptions using Stripe in Python?
I am having a really hard time figuring out Stripe. I created a checkout session using a subscription that I created in the dashboard and have been able to direct towards the checkout. However, I want to have three different buttons that lead to different checkout session, but they all lead to the same checkout (because I don't know how to edit my views.py). I am aware that I also still need to add code to create a costumer - I suppose that would be the next step. I you could help me out that would be great. Thanks! subscribe.html <HTML> <head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" /> <script src="https://js.stripe.com/v3/"></script> </head> <body> <button href='#' id='subscribe_monthly_button'>Monthly</button> <button href='#' id='subscribe_three_months_button'>Three Months</button> <button href='#' id='subscribe_six_months_button'>Six Months</button> <script> var stripe = Stripe('{{ stripe_public_key }}') const subscribe_monthly_button = document.querySelector('#subscribe_monthly_button') subscribe_monthly_button.addEventListener('click', event =>{ stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as argument here // instead of the {{CHECKOUT_SESSION_ID}} placeholder. sessionId: '{{ session_id }}' }).then(function (result) { // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `result.error.message`. … -
Open source solution for developing freelance application in django
Is there any open source framework for developing a freelance application using Django? If so then please let me know. -
Django - retrieve data for extend template
I have a base template in my app, and a Profile template with the user data, with a bunch of other pages that they can navigate through. Every user has a market. I want to display the market name on every profile page, not bypassing every page a block tag. base.html <span class="title navbar-item"> {% block market_name %}{% endblock %} </span> every-profile-page.html {% block market_name %}{{market.name}}{% endblock market_name %}