Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
403 Forbidden in Xcode Simulator but works fine with Xcode Canvas Preview
I'm wrote a Login page with SwiftUI, and a backend with Django(both running in my laptop) the login api works fine no matter using Postman or in Xcode Canvas Preview but when I run the Xcode Project with Simulator, the Login func would fail the backend returns 403 forbidden Funny thing is, it works fine until yesterday, and I didn't change the code, just suddenly it won't work in the simulator Can anyone tell me what's going on here? and how can I fix it? Thanks! I tried to disable the csrf middleware in Django setting.py, and it didn't work -
Cannot pass CSRF token in post request from react to django rest framework api
I am making a django/react website. I am trying to make a post request to my backend api using a CSRF token in the header of the request. Genre.js // I have an endpoint that is supplying the CSRF token, and I am fetching that on the frontend, and then making the post request. import React, { useState, useEffect } from "react"; function Genres() { const [genres, setGenres] = useState([]); useEffect(() => { fetch("/api/genres/") .then((response) => response.json()) .then((data) => setGenres(data.genres)) .catch((error) => console.log(error)); }, []); function handleClick(genre) { const query_params = { genre: genre, }; console.log(query_params); fetch('/api/get_csrf_token/') .then(response => response.json()) .then(data=> {fetch("/api/search/", { method: "POST", headers: { "Content-Type": "application/json", 'X-CSRFToken': data.csrftoken, }, body: JSON.stringify(query_params), }) .then((response) => response.json()) .then((data) => console.log(data))}) .catch((error) => console.log(error)); } return ( <div> <div className="genre-list-container"> <ul className="genre-list"> {genres.map((genre) => ( <li className="genre" onClick={() => handleClick(genre)} key={genre} > {genre} </li> ))} </ul> </div> </div> ); } export default Genres; views.py // I have a view to get the token def get_csrf_token(request): return JsonResponse({'csrfToken': request.COOKIES['csrftoken']}) settings.py // These are the lines I've added MIDDLEWARE =[ 'corsheaders.middleware.CorsMiddleware', ... 'django.middleware.csrf.CsrfViewMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True API_ALLOWED_HOSTS = ['http://localhost:3000'] CSRF_TRUSTED_ORIGINS = ['http://localhost:3000'] My error: [18/Mar/2023 22:36:14] "GET /api/get_csrf_token/ HTTP/1.1" 200 … -
Django models, How do you pass datetime instead of a Datefield to validators?
I realize that validators need to be simple, however, I still rather use them instead of using the "clean/save functions" for this case. What I have is a model called user (aka an employee) that has a joinDate and an exitDate. exitDate can be empty, however, when they are filled they need to be AFTER the joinDate (obviously). class user(models.Model): joinDate = models.DateField() exitDate = models.DateField(null=True, blank=True, default=None, validators=[secondDateAfterFirstDateValidator(joinDate)]) And the validator is a function that returns a function, just like it was recommended by this post Is it possible to have validators with parameters? def secondDateAfterFirstDateValidator(joinDate): def innerfn(value): if value < joinDate: raise ValidationError("The exitDate must be after the joinDate") return innerfn The error I get is: '<' not supported between instances of 'datetime.date' and 'DateField' Now, the value that is being passed is what the validator is passing, which is the value of the DateField that the validator is being passed to (which is the exitDate). And this gets automatically converted from models.Datefield to 'datetime.date'. However, it seems that when you pass to the validator the joinDate, it does not convert it to an instance of 'datetime.date' and keeps it as a models.Datefield. How do I resolve this … -
How can I integrate a Quasar Vue.js application into my Django project?
I have a Django project that serves as the back-end for my application, and I want to use Quasar as the front-end framework. I have already created a Quasar application using the quasar create command and it works fine when I run it separately. Now, I want to integrate this Quasar application into my Django project so that it can be served by Django's development server. `STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/dist/spa') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') from django.http import JsonResponse def my_api_view(request): # handle the API call here # return a JSON response data = {'message': 'Hello, world!'} return JsonResponse(data) ` -
CQRS: Should I extend my write model with some denormalized read fields?
I'm writing an app based on event sourcing and CQRS principles. The app is basically a "transaction tracker" and to exemplify the problem we can think that each Transaction is linked to an Asset. class Asset(models.Model): code = models.CharField(...) current_price = models.DecimalField(...) sector = models.CharField(...) ... def get_roi(self, percentage: bool = False) -> Decimal: # Expensive calculation using several joins in multiple tables return self.transactions.roi(incomes=self.incomes.sum(), percentage=percentage)["ROI"] class Transaction(models.Model): asset = models.ForeignKey(to=Asset, on_delete=models.CASCADE, related_name="transactions") ... class Income(models.Model): asset = models.ForeignKey(to=Asset, on_delete=models.CASCADE, related_name="incomes") ... My list endpoints for the assets has several fields that are costly to calculate in a normalized DB. Those fields changes if: a Transaction is created or deleted an Income is created or deleted current_price changes In order to scale and for several other reasons that you probably already know I want to separate those computational-costly fields from the write model. My questioning arises from the fact that a read model would have to have some fields that will probably never change and that has no relation with the events above. For example, I have a report that aggregates the ROIs per sector. With a read model I must have a sector field to generate this report. If … -
installation of Django => install virtual environment => set Virtual environment
I can't setting up the virtual environment will allow you to edit the dependency which generally your system wouldn’t allow virtualenv env_site 'virtualenv' is not recognized as an internal or external command, operable program or batch file. I want to set up a virtual environment will allow me to edit the dependency wich generally your system wouldn't allow -
Validation error when try to update table with uuid foreign key, django 4.2
This may be easy, but I have not been able to solve the issue I have 2 models wwith oneToMany relation. I am try to update the child table using foreign key of parent table, but it is returning this error: ValidationError at /StudentParentsAssign/01b93b30-e5fb-49f8-9394-94a824b7a099/ ['“c0ea3f3e-bb79-4fc5-9fd9-6bce341324d1,” is not a valid UUID.'] Below is my code: Models.py #Modeles.py class Student(models.Model): #std_matricule = models.CharField(verbose_name='Student matricule', max_length=6, null=False, unique=True, primary_key=True) std_matricule = models.CharField(verbose_name='Matricule', unique=True, max_length=16, null=False, blank=False, help_text='Matricule of the student') std_parents = models.ForeignKey(Parents, on_delete=models.DO_NOTHING, related_name='Parents', unique=False, null=True, blank=True, verbose_name='Student parents') class Parents(models.Model): father_surname = models.CharField(verbose_name='Father surname', max_length=128, null=False, blank=True, help_text='Student Father surname as in the birth certificate') father_firstName = models.CharField(verbose_name='Father name', max_length=128, null=False, blank=True) parent_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) .... view.py #view.py def StudentParentsAssign(request, pk): # parents_list = Parents.objects.all().order_by('father_surname') std = Student.objects.get(student_id = pk) if std.std_parents not in (None, ''): # parentsList = Parents.objects.all().order_by('father_surname') context = {'studentObj': std} return render(request, "students_management_app/student_template/student-single.html", context) else: if request.method == "POST": perents_id = request.POST.get('radio') Student.objects.filter(pk=pk).update(std_parents=perents_id) parentList = Parents.objects.filter(parents_deleteStatus=False).order_by('-parent_createDate') context = {'parentList': parentList} return render(request, "students_management_app/student_template/student-parents-list.html", context) url.py #url.py path('StudentParentsAssign/<uuid:pk>/', views.StudentParentsAssign, name = 'student-parents-list'), Template #Template {% block content %} <h1>List of all parents</h1> {% if parentList %} <form action="", method="POST"> {% csrf_token %} <button type="submit">Assign the … -
How to load Plotly graphs fast in a webpage?
I am using Django to create my first website. I have some complex plots made with Plotly which get passed to the render function as html (saved using to_html function). For example: def sample_plot(): import numpy as np import pandas as pd import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Barpolar( r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5], name='11-14 m/s', marker_color='rgb(106,81,163)' )) fig.add_trace(go.Barpolar( r=[57.5, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5, 55.0], name='8-11 m/s', marker_color='rgb(158,154,200)' )) fig.add_trace(go.Barpolar( r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0], name='5-8 m/s', marker_color='rgb(203,201,226)' )) fig.add_trace(go.Barpolar( r=[20.0, 7.5, 15.0, 22.5, 2.5, 2.5, 12.5, 22.5], name='< 5 m/s', marker_color='rgb(242,240,247)' )) fig.update_traces(text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W']) fig.update_layout( title='Wind Speed Distribution in Laurel, NE', font_size=16, legend_font_size=16, polar_radialaxis_ticksuffix='%', polar_angularaxis_rotation=90, ) return fig.to_html(config={'displayModeBar': False}) Just passing this plot to the webpage increases loading time by 2.1 seconds (using local server and same conditions). I have a few plots as complex as this one so the loading times make the webpage unusable. Is this behaviour expected? Is there a better approach than using to_html to render the Plotly graphs? or is Plotly a non starter for webpage plots? Sorry if it is a basic mistake, it is my first website. -
How can I properly save dropzone files from existing django form and get it from DB when need?
I am trying to handle drag&drop uploads with my django app and facing lack of actual information about dropzone + django. Previously I used just a multiple upload, as you could see below, and it worked great, but it is a time to handle drag&drop thing, cause it a way more convenient. I handled it to be inside my main form, but I totally don't understand how I suppose to save this files and get them from DB in template, when I need it. Maybe, somebody can help me with that? Don't be too angry on me, I am not an experienced JS user.. models.py class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField( max_length=200, ) ... class PostImages(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='images', ) file = models.FileField( upload_to="posts/images", validators=[], ) views.py class PostCreateView(AuthRequiredMixin, SuccessMessageMixin, View): template_name = 'create_post.html' model = Post form = PostCreationForm success_url = reverse_lazy('index') success_message = _('Post created successfully') def get(self, request, *args, **kwargs): form = self.form() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() form.save() for img in request.FILES.getlist('images'): data = img.read() new_file = PostImages(post=new_post) new_file.file.save(img.name, ContentFile(data)) … -
How to speed up or parallize a django function with multiple sequential filters and inserts?
I am doing some backtesting in python and have my DB models in Django set up as follows. One is a stock DB keyed by the symbol and one is a price DB keyed by symbol + date. Something like this: Stock DB: FB MSFT Goog Price DB: FB | 1/1/2023 | 150.0 FB | 1/2/2023 | 151.0 FB | 1/3/2023 | 160 I then run my backtesting algo to do something like for stock in stock_list: prices = Price.objects.filter(stock=stock) backtest = run_backtest(prices) Basically trying to optimize this for 500-1000 tickers and what I've noticed is the biggest bottleneck is "Price.objects.filter(stock=stock)" since it has to fetch brand new prices for each backtest. How can I best speed up the filters? Should I try something like loading 5 symbols at a time and then filtering from that? Or a second thread to fetch the next symbol as the first backtest is running? Is there something I'm missing here? I feel like I can speed this up 10-20x easily. Thanks! -
Django doesn't display that user exist
I learned Django from course but I have a problem. I can register and login. If password's doesn't match it display validate error but it doesn't display an error if user exist. OK. My view's method looks like this def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] sex = form.cleaned_data['sex'] user = Account.objects.create_user(username=username, email=email, password=password, sex=sex) user.save() messages.success(request, 'Udało Ci się zarejestrować!') return redirect('register') context = { 'form': form } return render(request, 'accounts/register.html', context) else: form = RegistrationForm() context = { 'form': form } return render(request, 'accounts/register.html', context) My forms password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'Enter Password', 'class': 'form-control' })) confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'Confirm Password', 'class': "form-control" })) class Meta: model = Account fields = ['username', 'sex', 'email', 'password'] def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' def clean(self): cleaned_data = super(RegistrationForm, self).clean() password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError( 'Password doesn not match!' ) And models class MyAccountManager(BaseUserManager): def create_user(self, username, email, sex, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') if not sex: … -
Populate parent field from url kwarg in a nested serializer in Django REST Framework
I have 2 models, Catalog and Epic: class Catalog(models.Model): created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(null=False, default=False) class Epic(models.Model): name = models.CharField(max_length=128, null=False) slug = models.SlugField(null=False) catalog = models.ForeignKey(Catalog, null=False, on_delete=models.CASCADE) I have created CRUD viewset and serializer for Catalog, using DRF. Now I want to create CRUD viewset and serializer for Epic, to be used like /catalogs/<int:catalog_pk>/epics/<int:pk>. I am using DRF-nested-router: router = routers.SimpleRouter() router.register("catalog", CatalogViewSet) catalog_router = routers.NestedSimpleRouter(router, "catalog", lookup="catalog") catalog_router.register("epics", EpicsViewSet, basename="epics") urlpatterns = router.urls + catalog_router.urls And these are my viewset and serializer for Epic: class EpicsViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): serializer_class = EpicSerializer permission_classes = (IsAuthenticated, CatalogPermissions) def get_queryset(self): return Epic.objects.filter(catalog=self.kwargs["catalog_pk"]) class EpicSerializer(serializers.ModelSerializer): class Meta: model = Epic fields = "__all__" I am trying to run the creation endpoint like this: POST /catalog/1/epics/ with epic data, but I get the error that catalog field is missing in the payload. I want this to be done automatically from URL kwargs. I want it to take the catalog_id from kwargs and set the catalog instance to the newly created Epic instance in the serializer. The starightforward way would be to override the create function in the serializer, but I am hesitant to do that and was wondering if there is a … -
How to check If the translation of a sql query to Django ORM is equivalent?
I have these models: class Messages(models.Model): channel = models.TextField(blank=True, null=True) message = models.TextField(blank=True, null=True) timestamp = models.TextField(blank=True, null=True) publisher = models.IntegerField(blank=True, null=True) type = models.CharField(max_length=5) class Meta: managed = False db_table = 'messages' class ReadMessages(models.Model): user_id = models.IntegerField(blank=True, null=True) message_id = models.ForeignKey(Messages, db_column='message_id', blank=True, null=True, on_delete=models.CASCADE) class Meta: managed = False db_table = 'read_messages' and I also have a legacy system who is using the same database, but this system is doing the following query in pure sql: SELECT messages1.id, messages1.channel FROM (SELECT * FROM messages WHERE channel IN ('U560')) messages1 LEFT JOIN read_messages ON messages1.id = read_messages.message_id WHERE read_messages.id IS NULL; I tried to do the same in Django ORM using the following code: Messages.objects.filter(channel__in=['U560'],readmessages__id__isnull=True).values('id', 'channel') with the few tests i've done they returned the same result, but I still not sure if they are equivalents and if there will be a case where the two queries will return differents results. -
Highlight words in markdown content according to search result using Reactjs
I am building React/Django app that is using markdown content I want to put a search bar at which the user can search in the blog content and the words that are matching the search results are highlighted. I have used react-highlight-words library but I found that It isn't compatible with markdown content so I am trying using react-string-replace library but there is a problem that faced me in the test react-string-replace returns array not string so I tried to use a hook (useState) which is an empty string and map each word in the array and append it to the hook then put the Hook inside ReactMarkdown element. import React from 'react' import ReactMarkdown from 'react-markdown' import reactStringReplace from 'react-string-replace'; export default function Mark(){ const [stringData, setStringData] = React.useState(""); const content = 'Hey my number is 555-555-5555.'; const replacearray= reactStringReplace(content, 's', (match, i) => ( `===${match}===` )); console.log(replacearray) replacearray.map(word =>{ console.log(word) setStringData(stringData + `${word}`) }) console.log(stringData) return( <ReactMarkdown>{stringData}</ReactMarkdown> ) } The result of console.log(replacearray) is: Array(3) [ "Hey my number i", "===s===", " 555-555-5555." ] The result of console.log(word) is: Hey my number i mark.js:116:13 ===s=== mark.js:116:13 555-555-5555 mark.js:116:13 The result of console.log(stringData) is: 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. … -
building user-based collaborative filtering system in Django
I'm trying to build a simple user based collaborative filtering in Django for an E-commerce using just the purchase history. Here are the steps I use, I know it needs more improvements but I've no idea what's the next move. here's the product model class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() here's the purcashe model class Purchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) purchase_date = models.DateTimeField(auto_now_add=True) Now to get similar users def find_similar_users(user, k=5): all_users = User.objects.exclude(id=user.id) similarities = [(other_user, jaccard_similarity(user, other_user)) for other_user in all_users] similarities.sort(key=lambda x: x[1], reverse=True) return [user_similarity[0] for user_similarity in similarities[:k]] and to calculate similarity between each: def jaccard_similarity(user1, user2): user1_purchases = set(Purchase.objects.filter(user=user1).values_list('product_id', flat=True)) user2_purchases = set(Purchase.objects.filter(user=user2).values_list('product_id', flat=True)) intersection = user1_purchases.intersection(user2_purchases) union = user1_purchases.union(user2_purchases) return len(intersection) / len(union) if len(union) > 0 else 0 now here's my entry function: def recommend_products(user, k=5): similar_users = find_similar_users(user, k) recommended_products = set() for similar_user in similar_users: purchases = Purchase.objects.filter(user=similar_user).exclude(product__in=recommended_products) for purchase in purchases: recommended_products.add(purchase.product) return recommended_products Now, obviously that'd be really slow, I was thinking of using a copy of the data in another no-sql database. Now if user A purchase something, I copy the data to the other database, do the calculation and store … -
Django and Huey task issue, record in DB doesn't exist when the task is ran
I am testing Huey with Django and found one issue, tasks can't find the record in DB. Here is the code: # settings.py USE_HUEY = env.bool("USE_HUEY", False) HUEY = { "huey_class": "huey.RedisHuey", "name": "huey", "immediate": not USE_HUEY, "connection": {"url": REDIS_URL}, } # app/signals.py @receiver(post_save, sender=Post) def post_signal(sender, instance, **kwargs): from app.tasks import create_or_update_related_objects create_or_update_related_objects(instance.pk) # app/tasks.py @db_task() def create_or_update_related_objects(object_pk): post = Post.objects.get(pk=object_pk) ... This is running an async task but I am getting the error: app.models.Post.DoesNotExist: Post matching query does not exist. This is not correct, there is a post, and this task is running on a post_save signal. What is weird, is if I do something like this, it works fine: @db_task() def create_or_update_related_objects(object_pk): import time time.sleep(3) post = Post.objects.get(pk=object_pk) ... What am I doing wrong here? -
PYTHON AND DJANGO
How can I create a balance with Django and python connect it with the the user Python print("Django") -
How to create a form choiceField with selection a models TextChoices?
I have a custom User Model with some TextChoices, How can I get that Selection "continents" into a Form? so that i Render the html page with {{ form }} and the Choices appear? I have tried both Forms1.py & Forms2.py None of them Work. Models.py class CustomUser(AbstractUser): #USER MODEL # CHOICES FOR USER CONTINENT class Continents(models.TextChoices): EUROPE = 'EUROPE' , 'EUROPE' AFRICA = 'AFRICA' , 'AFRICA' SOUTH_AMERICA = 'SOUTH AMERICA' , 'SOUTH AMERICA' NORTH_AMERICA = 'NORTH AMERICA' , 'NORTH AMERICA' OCEANIA = 'OCEANIA' , 'OCEANIA' ASIA = 'ASIA' , 'ASIA' username=None nickname = models.CharField(max_length= 50, default = 'Not Set', blank=True) bio = models.TextField(max_length = 500 , blank=True , null= True , default= "Not Set") email = models.EmailField(max_length= 256 , unique=True) #USERS EMAIL ADDRESS USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() Forms1.py class CompleteProfileForm(forms.Form): bio = forms.CharField( label='Bio: ', widget = forms.Textarea( attrs = { 'class':'bioInput' } ) ) class Meta: model = CustomUser fields = ['bio', 'continent'] exclude = ['username'] continents = forms.ChoiceField(label='Continents', choices= CustomUser.Continents) Forms2.py class CompleteProfileForm(forms.Form): bio = forms.CharField( label='Bio: ', widget = forms.Textarea( attrs = { 'class':'bioInput' } ) ) continents = forms.ChoiceField( choices=CustomUser.Continents, widget = forms.Select( attrs = { 'class':'continent', 'selected':'Continent', 'id':'continent', } … -
Dokcer - issue with creating an image for Django project
i am trying to use Docker for an Django project but i got an issue when i try to build a image. the Dockerfile : # pull the official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app RUN pip install -r requirements.txt # copy project COPY . /usr/src/app EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]` the requirements.txt file :here the problem at the terminal is anyone had the same issue ? maybe i should not have a requirements.txt file ? -
Running Cron in Django on AWS Elastic Beanstalk without .ebextensions
I'm trying to run a function to count daily active users within a Django application using cron. All guides I can find seem to be many years old and they all reference using a .config file located within .ebextentions folder. My app has been running fine for a while but I haven't actually got a .ebextensions folder so wondering if there's a bad config or if I'm just doing something obvious wrong. Problem: Trying to run cron jobs within Django application running on Elastic Beanstalk in AWS environment. Ideally all set up within code and pushed with "eb deploy" but happy for a more manual solution using command line on the linux instance itself. Attempted Solution Reading through AWS documentation and various online sources I have created a "my_cron.config" file inside a ".ebextensions" folder with the following content: files: /usr/local/bin/my_cron_script.sh: mode: "000755" owner: root group: root content: | #!/bin/bash export $(cat /opt/elasticbeanstalk/deployment/env | xargs) source $PYTHONPATH/activate python3 /var/app/current/manage.py dailyCounts /etc/cron.d/my_cron: mode: "000644" owner: root group: root content: | 0 6 00 * * root /usr/local/bin/my_cron_script.sh >> /var/log/my_cron.log 2>&1 commands: rm_old_cron: command: "rm -fr /etc/cron.d/*.bak" ignoreErrors: true When running "eb deploy" I get the following error: 2023-03-18 14:27:56 ERROR Updating Auto … -
Weird Django error when adding annotations annotations
I am trying to add comments to my django forum, but am running into an issue with annotate. whenever I add instructions to add comments com=Comment.objects.order_by("-published_date") it gives me an issue with a compleatly unrelated part of my template that checks the username. here is my view: def index(request): # check if there is any incomming data (comments) and make sure the user is authenticated POST = request.POST if POST != {} and request.user.is_authenticated: # a comment has been recived, time to move forward with creating it # figure out if the post even exists get_object_or_404(Post, id = POST['post_id']) # grab the user object user_active = User.objects.get(id = POST['user']) # grab the post object post_active = Post.objects.get(id = POST['post_id']) # make and save the comment n_comment = Comment(user = user_active, comment = POST['comment'], post = post_active) n_comment.save() posts = Post.objects.order_by("-published_date").annotate(num_likes=Count("likes"),com=Comment.objects.order_by("-published_date")) return render(request, 'home.html', {'posts': posts}) here is my model: class Comment(models.Model): comment = models.CharField(max_length=500) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') published_date = models.DateTimeField('date_published') and here is the error: Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.2.18 Python Version: 3.6.9 Installed Applications: ['core', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Logout Django Rest does not Log user out
I am making my first app, I managed to make the login/register process however the logout function does not work. Despite sending back status code of 200, when I then try to log-in with a different user there is an error saying that a username key is already present. Here is my code views.py: from django.http import JsonResponse from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from .models import Task, DailyTask from .serializers import TaskSerializer, DailyTaskSerializer, UserSerializer # Returns all possible routes for the API @api_view(['GET']) def getRoutes(request, format=None): routes= [ '/tasks', '/dailytasks', '/tasks/id', '/dailytasks/id', ] return Response(routes) # Registration/login and refresh tokens # Register function will handle registration @api_view(['POST']) def register(request, format=None): # POST requests will allow to create new users if request.method == "POST": serializer = UserSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Login function will handle logins @api_view(['POST']) def login_view(request, format=None): # Else if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username, password) # If user exists login if user is not None: login(request, user) # Otherwise return error else: return … -
How to get a value from number input in django?
I need to get a value from input with type number in django. When I tried to get that value, I got empty string. I expected getting a integer or number in string. HTML CODE: <form method="GET" action="" > <input type="number" name="ordered_amount" placeholder="amount" min="1" max="{{amount}}" value="1" /> <a href="/home/product/add/{{id}}/?q={{amount}}">Add to cart</a> </form> views.py: ordered_amount = int(request.GET.get('ordered_amount')) if request.GET.get('ordered_amount') != None else '' -
How do i pack a django module which has other django modules as dependencies?
I am developing a django module which is able to create UI interfaces to query a data repository. The module has an administration interface to configure the access to the data repository. For that it uses several other django modules such as crispy_forms. Following the tutorial at https://docs.djangoproject.com/en/4.1/intro/reusable-apps/, I created a module and uploaded it to test.pypi.org. I can add the module dependencies and upon installing my module, crispy_forms and all other dependencies are installed. This all works fine. But: in order to use my module, the user needs to make a lot of changes to the settings.py and urls.py files. Not only must my module be in INSTALLED_APPS but also my dependencies. Furthermore, to use crispy_forms, I need to specify a CRISPY_TEMPLATE_PACK setting. I always want this setting to be 'bootstrap4' and the user doesn't have to be aware of this setting. So my question is: Is there a way that the inclusion of my module can take care of these dependencies? What I need to have in settings.py: INSTALLED_APPS = [ 'my_module', 'django_tables2', 'crispy_forms', [...] ] CRISPY_TEMPLATE_PACK = 'bootstrap4' DJANGO_TABLES2_TEMPLATE = "django_tables2/bootstrap4.html" What I would like in settings.py: INSTALLED_APPS = [ 'my_module', [...] ] Is there a way … -
Could not build wheels for lxml, psycopg2, which is required to install pyproject.toml-based projects
I need to run this server on Django and React https://github.com/ozoneplatform/ozone/releases/tag/v8.0.0.0-GA I cloned it to myself, went to the "ozone-framework-python-server" folder, created a virtual environment and tried to install the libraries "pip install -r requirements.txt", but I got such errors I work for Windows Building wheels for collected packages: lxml, psycopg2-binary Building wheel for lxml (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [97 lines of output] - - - error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.35.32215\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for lxml Running setup.py clean for lxml Building wheel for psycopg2-binary (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 - - - It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try …