Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
aplicação django em desenvolvimento tudo certo mas em produção o banco de dados esta sem dados
Crie uma aplicação web em django com banco de dados postgres e fiz o deploy no heroku, esta tudo funcionando corretamente mas os dados que foram salvos em desenvolvimento não estão aparecendo em produção, tipo quando entro no adminstrador da aplicação se eu salvar fica ok, mas os dados que salvei quando em desenvolvimento não. Fiz o heroku run tanto makemigration e migrate tbm. -
Cross origin file download in Django
I wrote a small website using django. The website is hosted on pythonanywhere while the media files are aws s3. How can I create a link to download these files since they're not from the same origin. -
Django doesn't generate auto ID (MongoDB)
Django doesn't generate auto ID for the new class (People). Django Admin allows me to add a new People, but when I click on it it throws the error: People with ID “None” doesn’t exist. Perhaps it was deleted? People/models.py from django.db import models from django.contrib.auth.models import User class People(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) image = models.ImageField(upload_to='image/', blank=True, null=True) address = models.TextField() creation_timestamp = models.DateTimeField(auto_now_add=True) I use MongoDB and I can see a new entry has been added to the database, all data seems to stored correctly. But when I compare People with another table, I notice People hasn't got id. -
Django - filter posts by author using a string pk?
I'm building a blog and am trying to give the user the possibility to view posts by a single author. So far I've tried different filters to return a view that works. This is the closest I've gotten (I think), but the site comes back empty. Does anyone know what I'm missing? My models.py class Author(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) username = user.name first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) def get_absolute_url(self): return reverse("author", args=[str(self.id)]) def __str__(self): return self.user.username class Post(models.Model): author = models.ForeignKey(Author, related_name="user_name",on_delete=models.CASCADE) title = models.CharField(max_length=250) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateField(blank=True,null=True) My view class PostListAuthor(ListView): model = Post, Author paginate_by = 5 context_object_name = 'author_posts' template_name="blog/post_author_list.html" def get_queryset(self): return Post.objects.filter(author = Author.username, published_date__lte=timezone.now()).order_by("-published_date") And my urls.py has this: path("author/<str:pk>",views.PostListAuthor.as_view(),name="author"), -
How to unit test a simple scheduled celerybeat healthcheck task with Django?
Good day everyone. I hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development and other tools that work together, like Celery. Thanks to its very complete documentation, I've had the ability to create the tasks that I needed to run on the background. However, given some constraints and a high quantity of data, some of these tasks are getting so far behind, that the workers tend to die. For that reason, I've begun a troubleshooting process, to see how far my workers go before they stop responding. I created a very simple task that's just trying to check the health of the celery workers every 2 minutes, and send those results to a django model that I could see in my webserver: from celery import app, shared_task from ..models.recommendation import HealthCheck import logging from django.utils import timezone @shared_task(bind=True) def health_check_monitor(self): celery_worker = self.request.hostname try: logging.info('Celery is alive') HealthCheck.objects.update_or_create( alive=True, timestamp=timezone.now(), defaults={'worker_id': celery_worker}) except TimeoutError: logging.info('Celery is dead') HealthCheck.objects.update_or_create( alive=False, timestamp=timezone.now(), defaults={'worker_id': celery_worker}) The HealthCheck model will only be made of one row that identifies the worker's name (worker@example.com), the timestamp it was run and its status (Dead or alive). The task's schedule is … -
How to use Django Rest serializers with dtos?
I am from Java background and I am getting a bit confused with the serialization in Django Let's say I have this requirement I need to fetch the results of stocks from an exchange. So the request will be like { "exchange" : ["exchange1", "exchange2"], "stock_name" : ["stock1", "stock2"] } In Spring I would write a RequestDto like this, class StockResultRequestDto{ List<String> exchange; List<String> stockName; } and In the controller method getMethod(@RequestBody StockResultRequestDto request) and Jackson library behind the scenes would take care of the serialization. In Django Rest as well, I was thinking to have it similar @dataclass class StockResultRequestDto: exchange: List[str] stock_name: List[str] But since we don't have a builtin serializer in python, I understand, I will need to write serializer as well. class StockMarketRequestSerializer(serializers.Serializer): exchange = serializers.CharField(max_length=100, many=True) stock_name = serializers.CharField(max_length=200, many=True) @api_view(['POST']) def get_stock_result(request): serializer = StockMarketRequestSerializer(data=request.data, many=True) serializer.is_valid(raiseException=False) stockMarketDto = StockResultRequestDto(**serializer.validated_data) <--- Is it advised to create a dto when I can pass around serializer.validated_data? Coming to output considering I don't have a database involved, I fetch the results from a different server class StockResult: stockName: str netProfit: float revenue: float I do business logic and finally, I will have something like stock_result_response = [list … -
JWT Token does not make me logged in Django
Hello Guys I am trying to log in with simpleJWT of django. When I log in it gives me access_token and refresh_token. But it is not making me logged in. My django-server still says 'AnonymousUser' object has no attribute ... when I try to view some api endpoints I am sending post request for login via axios in React. Here is my login.jsx import axiosInstance from "../../axios"; ... state = { username: "", password: "", loggedIn: false, }; handleLogin = () => { console.log(this.state); axiosInstance .post(`auth2/token/`, { username: this.state.username, password: this.state.password, }) .then((res) => { console.log(res); localStorage.getItem("access_token", res.data.access); localStorage.getItem("refresh_token", res.data.refresh); axiosInstance.defaults.headers["Authorization"] = "JWT " + localStorage.getItem("access_token"); this.setState({ loggedIn: true, }); }) .catch((err) => { console.log(err.message); }); }; ... this is my axios.js file from react project import axios from "axios"; const baseURL = "http://127.0.0.1:8000/api/v1/"; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem("access_token") ? "JWT " + localStorage.getItem("access_token") : null, "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 - … -
Executable file not found in $PATH when running dockerfile
I get runtime create failed when tryinf to set up a Production Django backend with Docker. I can't figure out why. This is my error ERROR: for backend Cannot start service backend: OCI runtime create failed: container_linux.go:367: starting container process caused: exec: "run.sh": executable file not found in $PATH: unknown My dockerfile: FROM python:3.9-alpine LABEL maintainer="my@mail.com" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./backend /backend COPY ./scripts /scripts WORKDIR /backend EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client jpeg-dev && \ apk add --update --no-cache --virtual .tmp-deps \ build-base gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ adduser --disabled-password --no-create-home user && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R user:user /vol && \ chmod -R 755 /vol && \ chmod -R -x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER user CMD ["run.sh"] Inside the run.sh file is inside /scripts I use windows 10. -
How decode base64 image PIL
I've some trouble with decode base64 image in my django project. I am passing the image to views like this (I've some form. I'm passing image to function from views.py through this form): {% extends "blog/base.html" %} {% block content %} <div id="content" class="container-fluid d-flex h-100 justify-content-center align-items-center p-0"> <div class="row bg-white shadow-sm"> <div class="col border rounded p-4"> <h3 class="text-center mb-4">Диагноз</h3> <form action="" id="post-form"> <div class="form-group"> <p align="center" style="font-weight:bold"><label for="exampleFormControlFile1">Снимок</label></p> <input type="file" class="form-control-file" id="image-selector"> </div> </form> <p align="center" style="font-weight:bold">Predictions</p> <p>Covid: <span id="covid-prediction"></span></p> <p>Health: <span id="health-prediction"></span></p> <table align="center"> <tr> <td> <img id="selected-image" class="img-thumbnail" width="300px" height="300px" src=""/> </td> </tr> <tr align="center"> <td> <button id="predict-button" type="submit" class="btn btn-primary">Predict</button> </td> </tr> </table> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script> let base64Image; $("#image-selector").change(function() { let reader = new FileReader(); reader.onload = function(e) { let dataURL = reader.result; $("#selected-image").attr("src", dataURL); base64Image = dataURL.replace("data:image/jpeg;base64,",""); console.log(base64Image); } reader.readAsDataURL($("#image-selector")[0].files[0]); $("#covid-prediction").text(""); $("#health-prediction").text(""); }); $("#predict-button").click(function(event){ let message = base64Image; console.log(message); $.post("{% url "diagnose:submit_prediction" %}", message, function(response){ $("#covid-prediction").text(response.prediction.covid.toFixed(3) * 100 + "%"); $("#health-prediction").text(response.prediction.health.toFixed(3) * 100 + "%"); console.log(response); }); }); </script> And in my views file I'm trying to decode this image like this: @csrf_exempt def predict_chances(request): myDict = request.POST.dict() encoded = 0 for k … -
I can't distinguish roles with my implementation in DRF+Angular
I've made an implementation of a login system using django as backend and angular as frontend. In the backend the authentication is implemented via the view associated to auth/signup from django.contrib import admin from django.urls import include, path from rest_framework import routers from shopping.views import listatodoseventos from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('events',listatodoseventos), path('auth/', include('rest_auth.urls')), path('auth/signup/', include('rest_auth.registration.urls')), path('auth/refresh-token/', refresh_jwt_token) ] In the frontend is done by this method signup(username:string, email:string, password1:string, password2:string){ //todo return this.http.post( this.apiRoot.concat('signup/'), {username, email, password1, password2} ).pipe( tap(response=>this.setSession(response)), shareReplay() ); } It generates me these tables related with users. I want to associate each user with a role. But I don't know how to do that cause I don't know how to create entries in auth_user_groups link to the tables -
Is there a way to display Django Foreign Key Relationship in Angular?
Basically this question. I have set up Django Rest Framework and the backend is already "connected" to my frontend in angular. I just can't figure out how do display a Foreign Key relationship, similar to how it works in Django. Any source or similar on this topic? Thanks in advance -
Error in set UUID field as Primary Key in PostgreSQL and Django
I decided to use UUID instead of default Django's Primary Key. Based on the the Django docs: class Student(TimeStampModel): ... id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... When I migrate I will get the error down below: django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: ...students_student" ALTER COLUMN "id" TYPE uuid USING "id"::uuid I checked the schema with DBeaver. the id saved as bigserial -
login() missing 1 required positional argument: 'request'
I am getting this error when I try to login using email with Django application. TypeError at /accounts/login login() missing 1 required positional argument: 'request' Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login Django Version: 2.2.4 Exception Type: TypeError Exception Value: login() missing 1 required positional argument: 'request' My code looks like this at the django views def login(request): if request.method == 'POST': #username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(request, email=email, password=password) if user is not None: auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('dashboard') else: messages.error(request, 'Invalid credentials') return redirect('login') else: return render(request, 'accounts/login.html') -
Error in set UUID as Primary key in PostgreSQL with Django
I decided to use UUID instead of default pk(or id) in Django models. So I did: class Student(TimeStampModel): class Gender(models.TextChoices): MALE = "M", "Male" FEMALE = "F", "Female" OTHER = "O", "Other" UNSET = "U", "Unset" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=100, blank=False, null=False) date_of_birth = models.DateField(blank=False, null=False) I've migrated and everything went OK. But When I want to add a new Student using the admin site I get the error down below: column "id" is of type bigint but expression is of type uuid Note: I checked the database schema using DBeaver. id saved as a bigserial. -
I want to merge pdf with httpresponse in django
I want to merge pdf file with httpresponse in python django. And another question is that how to merge multiple httpresponses in python django ? -
How to pass a JavaScript variable to a Django variable
In my Django app I want to allow an admin to edit all the users (change groups etc.) and I am passing form data that includes the selected users username with JavaScript to another template. I want to use this username to make a query on users to find the correct information required for to change things on the user object. How do I pass a JavaScript variable inside a template to a Django variable? In first template users.html: <form action="{% url 'app:edituser' %}" method="get" name="form"> <p> <b>Username: </b>{{ i.username }} <a class="btn btn-primary btn-sm btn-danger" style="float:right" href="{% url 'app:all_users' %}" onClick="deleteUser()">Delete</a> <input type="hidden" id="value" name="username" value="{{ i.username }}" /> <button class="btn btn-primary btn-sm btn-info" style="float:right" type="submit">Edit</button> </p> </form> In second template edituser.html: <h1>Edit user</h1> <p><b>Username: </b><span id="data"></span></p> <p><b>Groups: </b><span id="data1"></span></p> <a class="btn btn-primary btn-sm btn-danger" href="{% url 'authenticator_app:all_users' %}">Cancel</a> <script> // Get the wanted parameters from the previous page's form. function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } // Parameters var name = getParameterByName('username'); var group = getParameterByName('groups'); // … -
Converting request body to json Django Python
below is some python Django code and output it gives Code data = request.body print (data) Output b'{"Body":{"stkCallback":{"MerchantRequestID":"9088-17223944-1","CheckoutRequestID":"ws_CO_310520212138262746","ResultCode":1032,"ResultDesc":"Request cancelled by user"}}}' How do i convert the output to json and also how do i access the "ResultCode":1032 value for further processing? Regards. -
How to do aggregations on the serialised data (dictionaries or json)
In Django models you can say Model.objects.aggregate(...) But inside a view or serializer you'll get request.data. so can you do something like request.data.aggregate. -
django pre filled form
I want form data to be pre filled when rendered first time, the initial parameter does not affect the form at all. When user edits profile I want user data to be displayed in the form. def profile_update(request): if request.method == 'POST': form = UpdateProfile( initial={'username': 'Hi there!'}, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('profile')) else: form = UpdateProfile() return render(request, 'users/profile_update.html', {'form': form}) class UpdateProfile(forms.ModelForm): email = forms.EmailField() img = forms.ImageField(label='img', required=False) class Meta: model = TbUser fields = ['username', 'img', 'email', 'cellphone', 'empno', 'real_name', 'nfc_id', 'sex', 'role', 'department'] -
How to get_connect_redirect_url after SocialAccountSignUp?
Hi is there any working solution to get get_connect_redirect_url to work? I have tried multiple redirects, renders, resole_url, reverse etc. all with custom adapters but nothing is working. How is able to help? class MySocialAccountAdapter(DefaultSocialAccountAdapter): def get_connect_redirect_url(self, request, sociallogin): """ Returns the default URL to redirect to after successfully connecting a social account. """ assert request.user.is_authenticated return resolve_url('social_login_success') -
Building a complete multi-platform (android & web) chat app
I want to build a chat app platform for both web and android. I want the chats and contents in the same database (kind of like telegram I guess?). What tools I should use for creating such a project? -
How to use a choice model to filter out certain characters from a set
I'm fairly new at this so please keep that in mind. I'm creating a Django website where users (who are learning Chinese) can upload Chinese vocabulary lists and the site will return a list of just the unique characters (no duplicates) that the user can download. So far, it's working and doing everything I described above. But the part that I'm stuck on is that I want to add a filter functionality. I want to add the option to exclude some of the more common Chinese characters from the list that the user downloads (what I'm thinking of as a filter feature). I have created a dropdown menu where before the user presses upload, they first say whether they want to filter out the 100 most common characters, 500, none, etc. Then, they move to another page where it should take that into account when it's writing to the file that it presents for the user to download. models.py from django.db import models #This is supplying the options on the first page class FilterPreference(models.Model): NONE = 'NO' first_250 = 'F250' first_500 = 'F500' first_750 = 'F750' first_1000 = 'F1000' PREFERENCE_CHOICES = [ (NONE, 'None'), (first_250, 'First 250'), (first_500, 'First 500'), … -
Download data from ajax requests from multi-soruce web scraper
I am looking for help on adding a download feature to a web-app. The app takes a query from the user and then searches over 30 sources with the users query and returns it. The searching is done using ajax through a results.html. The below code is reduced as the code can be very long with essentially repeated work (slightly different depending on the website searched). The below code works in its current state where the 'example.com' is searched and returns the number of hits from the query. Results.html {% load custom_tags %} {% block content %} <!--Show user's query--> <div class="row"> <div class="col-md-12"> <table> <tbody> <tr> <td class="ps"><i id="spin" class="fa fa-fw fa-2x"></i></td> <td> <h4 style="margin-bottom:0px;">Your query: <a href="{% url 'search:result' %}?query={{query}}">{{query}}</a></h4> <span>Searching for: {{queries}}</span> </td> </tr> </tbody> </table> </div> </div> <hr> <!--Links to sections--> <div class="row"> <div class="col-md-12"> <ul class="nav nav-pills"> <li role="presentation"><a href="#identity">Identity</a></li> <li role="presentation"><a href="#phys-chem">Phys-chem</a></li> <li role="presentation"><a href="#other-info">Other Information</a></li> <li role="presentation"><a href="#synonyms-more">Synonyms</a></li> {% if next_query%} <a href="{% url 'search:result' %}?query={{next_query}}"><button class="btn btn-default">Next Query</button></a> {% endif %} </ul> </div> </div> <a href="{% url 'search:download_data' %}">Download Data</a> <div class="row"> <div class="col-md-12"> <span class="anchor" id="biomonitoring"></span> <h2>Biomonitoring</h2> <table class="table table-hover"> <thead> <tr><th class="text-center info" colspan="3">Tier 1</th></tr> <tr><th>Source</th><th>Status</th><th>Result</th></tr> </thead> <tbody> {% with … -
Need more explanation on Admin customisation of Django using fieldsets?
Ok, this is kind of a rookie question. While trying to build a polling app, I came across these concepts where they used TabularInline in models. py. Couldn't figure out a proper explanation for the below code and how they behave. Added my code below. (It's supposed to have multiple 'choices' for a question on the same page.) So whats fieldsets? classes? class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [(None,{'fields': ['question_text']}), ('Date published',{'fields': ['pub_date'], 'classes':['collapse']}),] inlines = [ChoiceInline] admin.site.register(Question,QuestionAdmin) -
How to customize JSON Field in django admin
I have a Postrges JSON field in my model which is used to store nested json data. I want to reformat it on django admin to either open in a editor or some reformatted json which is readable by someone having 0 knowledge of JSON I have tried using django_json_widget like this from django.contrib.postgres.fields.jsonb import JSONField from django.contrib import admin from django_json_widget.widgets import JSONEditorWidget class MyModel(admin.ModelAdmin): formfield_overrides = { JSONField: {'widget': JSONEditorWidget}, } But this is just showong me empty space in place of field content like this The data stored in context field is of this format: { "type":"product", "products":[ { "id":"b9757d05-1b33-4ce3-aaa4-4d20480253f3", "mrp":65000.0, "tax":null, "upc":null, "name":"Macobook Air", "isbn_number":null, "display_name":"Macobook air", "product_type":"goods", } ], "variant_detail":{ } } How can I show it in a proper way?