Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass data to Django forms from
I would like to pass my job_title from my views.py to be used to query the database in my ModelForm in forms.py. I am currently able to get the job_title from the url and pass it to my views.py. The challenge I currently have is that I keep getting errors whenever I try to query the database in my ModelMultipleChoiceField to get the particular job requirements for a specific job title. I have tried to use solutions from some articles that i found on both this site and the web. urls.py urlpatterns = [ path('application_form/<str:job_title>/', views.application_form, name='application_form'), ] views.py def application_form(request, *args, **kwargs): try: job_title = kwargs.get('job_title') get_query_data = {'job_title__job_title': job_title} model_obj = Requirements.objects.filter(**get_query_data) form = ApplicationForm(request.POST or None, model_obj) context = {'form': form} if request.method == 'GET': return render(request, 'requirements/job_specs.html', context) if request.method == 'POST': print(form.is_valid()) if form.is_valid(): form.save() return JsonResponse({'created': True}) return JsonResponse(form.errors.as_json(), safe=False) except Exception as e: print(e) form = ApplicationForm(request.POST or None) context = {'form': form} return render(request, 'requirements/job_specs.html', context) models.py class Job(models.Model): company = models.CharField(max_length=35, default='ZICTA') job_title = models.CharField(max_length=40) description = models.TextField(max_length=250) def __str__(self): return self.job_title class Requirements(models.Model): job_title = models.ForeignKey(Job, on_delete=models.CASCADE) required = models.CharField(max_length=250) def __str__(self): return self.required class Applicants(models.Model): email = models.EmailField(max_length=30) required … -
How to show the validation error in a Django form?
I am new to Django. I am trying to make a simple form to match the password. However, when I enter different passwords and press the Save button I get a cleared form instead of showing the validation error. Here newuser.html: {% block content %} <form method="POST"> {% csrf_token %} <table> {{frmNewUser.as_table}} {% for error in frmNewUser.password.errors %} {% comment %} I tried frmNewUser.non_field_errors too {% endcomment %} <p>{{error}}</p> {% endfor %} </table> <input type="submit" name="Save" value="Save" colspan=2> </form> {% endblock content %} Here forms.py: class NewUserFrom(forms.Form): username = forms.CharField(max_length=50, widget=forms.TextInput) password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput) name = forms.CharField(max_length=50, widget=forms.TextInput) email = forms.EmailField(max_length=50, widget=forms.EmailInput) def clean(self): cleaned_data = super().clean() pwd = cleaned_data.get('password') cof_pwd = cleaned_data.get('confirm_password') if pwd and cof_pwd: if pwd != cof_pwd: raise forms.ValidationError('Password is not match.') return super().clean() Here views.py: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc from .forms import NewUserFrom def newUser(request): form = NewUserFrom(request.POST) if not form.is_valid(): return render(request,'login/newuser.html', {'frmNewUser':NewUserFrom}) return render(request, "login/welcome.html") -
Python Django s3 error "file must be encoded before hashing"
We send a file via API. When the file is saved locally or on the same ec2 instance, all works fine, and we get the response from the API When the file is saved on AWS s3, we get the error 'Unicode-objects must be encoded before hashing' This is the code that works to open and send file from local device but not when getting the file from s3 my_file = self.original_file.open(mode='rb').read() -
Make ModelMultipleChoiceField with FilteredSelectMultiple widget - read only
In my project i use an intermediary model CustomizedUserGroups to keep relations between CustomizedUser and Group models: # models.py class CustomizedUser(AbstractUser): first_name = models.CharField(max_length=255, verbose_name='имя') last_name = models.CharField(max_length=255, verbose_name='фамилия') # other fields groups = models.ManyToManyField(Group, verbose_name='группы', related_name='users', through='CustomizedUserGroups') Therefore in admin class (CustomizedUserAdmin) for CustomizedUser i can't let fieldsets contain 'groups' (otherwise The value of 'fieldsets[2][1]["fields"]' cannot include the ManyToManyField 'groups', because that field manually specifies a relationship model. will happen). So, i defined fieldsets manually (with no groups) and problem was solved. # admin.py class UserAdminCustomized(FilterByMedicalCenterMixin, BasicModelAdmin, UserAdmin): fieldsets = ((None, {'fields': ('username',)}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'patronymic', 'role', 'email')})) It is intended, that value for groups field in model CustomizedUser is assigned automatically depending on other values from registration form fields, therefore when a user adds a new user via admin panel, there is no need to display groups field. But when a user wants to edit other user's data via admin panel, i want the group field to be shown to him in read only mode. To solve this i created ExtendedUserChangeForm, where i defined a group_list field: # forms.py class ExtendedUserChangeForm(UserChangeForm): group_list = forms.ModelMultipleChoiceField(label='Группы пользователя', queryset=Group.objects.all(), required=False, widget=FilteredSelectMultiple('группы пользователя', False, attrs={ 'disabled': True })) I … -
Perform update on Django Rest Framework
ive got a class that adds a number of points in an instance, but i want to limit it, so that only one user can upvote one answer. One user can't do it twice, but other users can also upvote it only once: class AddPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = AddPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) def perform_update(self, serializer): if not serializer.addition_done and self.request.user not in serializer.voters.all(): serializer.number_of_points += 1 serializer.addition_done = True serializer.save() class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) addition_done = models.BooleanField(default=False) subtraction_done = models.BooleanField(default=False) voters = models.ManyToManyField('users.CustomUser', default=None, blank=True, related_name='voters') class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points', 'addition_done') But i get an error like this AttributeError: 'AddPointsSerializer' object has no attribute 'addition_done' Do you have any idea why? -
Django, how to add a watermark of primary key on the image that is submitted with the form?
I have a form that takes some values from the dropdowns and an image as well(optional) and then submits the data to the database. The primary key of form is the collective values of all the options selected separated by "_" e.g. if someone selects A from first dropdown, 33 from second dropdown, football from third dropdown, the form would be submitted with primary key "A_33_football" and it would be unique for this form only. I want when image is submitted along with this form, it should have this primary key watermarked on it. Is there a way doing this Django? -
how pass an id into an api with django
hi i am new to working with api, i am trying to pass an id into the api this way, but it returns a none value from django.shortcuts import render import requests import json def hacker_news(request): response = requests.get( 'https://hackernews.firebaseio.com/v0/topstories.json') topstories = response.json() item_id = topstories[0] print(item_id) url = ('https://hacker-news.firebaseio.com/v0/item/{item_id}.json') re = requests.get(url) story = re.json() return render(request,'comment.html', {'story':story}) -
Filter queryset by subquery on two conditions
I need to filter SomeModel queryset on max date by groups (user field). The Model looks like: class SomeModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=date.today) ... I've already created some kind of subquery: from django.db.models import Max subquery = (SomeModel.objects .all() .values('user') .annotate(latest_date=Max('date'))) So I want to use this subquery to filter SomeModel queryset on two conditions: # pseudocode SomeModel.objects.filter(user==subquery.user and time==subquery.latest_time) Is it possible at all or my approach is wrong? -
NGINX no live upstreams while connecting to upstream
I have Django app, running in Docker container on a host. Also on a host I have Nginx server for this app. Problem that like every 5 - 10 days server not respond and I must restart app container, I don't know what can be wrong. My Nginx conf: upstream django_service { server 127.0.0.1:8001 max_fails=0 fail_timeout=10; } server { listen 443 ssl; listen [::]:443 ssl; server_name domain.com; charset utf-8; client_max_body_size 16M; ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot # include /etc/letsencrypt/options-ssl-nginx.conf; if ($scheme != "https") { return 301 https://$host$request_uri; } location /media { alias /home/paket/paket2x/var/www/media; } location /static { autoindex on; alias /home/paket/paket2x/var/www/static; } location / { proxy_read_timeout 600; proxy_pass http://django_service; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect http://localhost:8001 https://$server_name; access_log /var/log/nginx/paket.access.log paketlog; error_log /var/log/nginx/paket.error.log; } } server { listen 80 default_server; listen [::]:80 default_server; server_name domain.com; return 301 https domain.com$request_uri; } server { listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot server_name www.domain.com; # managed by Certbot return 301 https domain.com$request_uri; } server … -
How to convert Django project into mobile app
I am new in Django. I need some help to convert Django website into mobile app. Please tell someone what to do. am not able to convert it. please tell me. This help will be good for me as a fresher. I don't have any knowledge about converting Django project into mobile app. Please tell some guide to do that. please -
Django Rest Framework testing with python queue
I have a simple DRF application with a Python native queue that I'm currently writing tests for. One of the API's accepts a file, which is then put in a python queue for processing. This works fine in the Django app. However, I can't figure out how to test this properly. When I call the the API with a Django API Client, I see that the file is put in the queue, and processing is started. However, as the response is returned, the tests finishes before the task of the queue is done. This task is then never completed. I also cannot make the test sleep, cause this seems to pause the queue as well. Which is strange, cause they should be on different threads. Additionally, the default tearDown results in a ObjectInUse error from psycopg2 as the test db is in use. I presume this is my queue accessing the DB, so how can I close my queue properly so that the teardown doesn't err? My test: from django.test import TestCase from rest_framework.test import APIClient class UploadTestCase(TestCase): def setUp(self): self.client = APIClient() self.client.force_authenticate() def test_post_file(self): with open('tmp.csv', 'rt') as f: response = self.client.post('/upload', data={'files': [f]}) # Asserts ... -
How to make a LEFT JOIN in django, I can't figure it out
My first model: class HdAlerts(models.Model): raised_at = models.DateTimeField(null=False) msg = models.TextField() site = models.ForeignKey( Sites, on_delete=models.CASCADE, ) alert_class = models.CharField(max_length=120) priority = models.IntegerField(null=True) severity = models.SmallIntegerField(null=True) partner = models.ForeignKey( Partners, on_delete=models.CASCADE, ) alert_id = models.TextField(primary_key=True) updated_at = models.DateTimeField(null=True) resolved_at = models.DateTimeField(null=True) ignore_until = models.DateTimeField(null=True) class Meta: managed = False db_table = 'hd_alerts' def __str__(self): return f'<ID: {self.alert_id}: [Msg: {self.msg[:10]}]>' Second: class Partners(models.Model): partner_id = models.IntegerField(primary_key=True) partner_name = models.CharField(max_length=500, null=False) is_profiles_shared = models.BooleanField(null=False) is_deleted = models.BooleanField(null=True) class Meta: managed = False db_table = 'partners' def __str__(self): return f'<Partner_ID: {self.partner_id}: [Name: {self.partner_name}]>' And last one: class Sites(models.Model): site_id = models.IntegerField(primary_key=True) site_name = models.CharField(max_length=500, blank=True) is_deleted = models.BooleanField() is_auto = models.BooleanField() partner_id = models.IntegerField(blank=True, null=True) source_id = models.IntegerField(blank=True, null=True) category_id = models.SmallIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'sites' verbose_name = 'Site' verbose_name_plural = 'Sites' def __str__(self): return f'Site id: {self.site_id}, Site name: {self.site_name}' I need to make the following query: SELECT p.partner_name DBA, s.site_name Site, ha.msg Messege, ha.ignore_until Ignored FROM hd_alerts ha LEFT JOIN partners p ON ha.partner_id = p.partner_id LEFT JOIN sites s ON s.site_id = ha.site_id WHERE ha.resolved_at IS NULL I don't understand how this can be done with django. I tried to pass it to raw(), but … -
Can web components UI use dynamic data from our backends DB as input?
I'm considering learning web components, either stencil or lit elements. A deal breaking for me is being able to create UI elements that can actually take data from our DB as an input and then morph the output of the UI element getting displayed. So if I have a Django backend with PostgreSQL and store two columns for [stockprice] & [timedate]. Is there a web component framework that lets me write a UI widget like this (pseudo code)... Example 1 UI - line chart stock widget CSS = rectangle(purple) var1 let [stockprice] = Y axis var2 let [datetime] = X axis CSS = 3 buttons (user options) button 1 if [datetime] >= 7days, delete (exclude) button 2 if [datetime] >= 30days, delete (exclude) button 3 if [datetime] >= 365days, delete (exclude) plot_line_chart(stockprice, datetiime) addbuttons() Example1 output. Combine UI elements into ONE widget (purple rectangle) This would in theory output a line chart with stock prices against a certain timeframe and allow the users to display if they want to view price in last 7, 30 or 365days depending on which option they click. In example 1, both the stock chart and button selection are ONE element part of the same … -
Is the sqlite database (the default django database) good enough?
I am building this ecommerce app with django, and I was thinking if the default database (sqlite) was fine enough? My django app is going to have around 200 different products, and for payments I will use stripe API. I do not expect too much traffic when the app is up, since it's a website only for the country I live in with 6 million inhabitants. So can I settle with the sqlite database? -
How to resolve this "Invalid default value for a django.models field error"?
I am creating a student model which records homework details of a student. It works in a way that student has been given work to do at home with some deadlines of days or hours. When I migrate, I get this error I am getting this error File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1067, "Invalid default value for 'deadline_type'") for my this model class WorkHour(models.Model): DAYS= 'D' HOURS= 'H' STATUS = [ ('D', 'Days'), ('H', 'Hours') ] student= models.ForeignKey(Student, on_delete=models.CASCADE) date= models.DateField(verbose_name='Date') deadline_type= models.CharField(max_length=256,choices=STATUS,default= DAYS, verbose_name= "Days/Hours") deadline_time = models.IntegerField(verbose_name='Deadline',default=1) either I add default value in deadline_type, It gives me the above error. I have done the same thing in my other models too. I din;t know what I am doing wrong here. -
Print users' data inside a template in Django
I'm new to Django and I'm trying to print users' information such as email, first name, username in a template that should work as "My Profile Page". For some reason, the only thing I'm able to print is the username of the logged-in user with {{request.user.username}} Users are registered using the UserCreationForm If I try to print the email with {{request.user.email}} or {{user.email}} nothing is shown. My settings.py is the default one TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Hey everyone I have problem in sorting queryset in Django
So, I am learning Django and trying to make a site similar to AirBNB. I have models called lisitngs that has latitude and longitude stored in CharField. My model is as follows: class Listing(models.Model): class BathRoomType(models.TextChoices): ATTACHED = 'Attached Bathroom' COMMON = 'Shared Bathroom' class RoomVentType(models.TextChoices): AC = 'Air Conditioner' NO_AC = 'No Air Conditioner' class LisitngType(models.TextChoices): ROOM = 'Room' APARTEMENT = 'Apartement' HOUSE = 'Full House' user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) city = models.ForeignKey(RoomLocation, on_delete=models.CASCADE) exact_address = models.CharField(max_length=255) lat = models.CharField(max_length=300, blank=False, null=False, default="0") lng = models.CharField(max_length=300, blank=False, null=False, default="0") description = models.TextField() price = models.IntegerField() listing_type = models.CharField(max_length=20, choices=LisitngType.choices, default=LisitngType.ROOM) kitchen_available = models.BooleanField(default=False) kitchen_description = models.TextField(null=True, blank=True) bedrooms = models.IntegerField() max_acomodation = models.IntegerField() bathroom_type = models.CharField(max_length=20, choices=BathRoomType.choices, default=BathRoomType.ATTACHED) no_bathrooms = models.IntegerField() room_type = models.CharField(max_length=30, choices=RoomVentType.choices, default=RoomVentType.AC) main_photo = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_1 = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_2 = models.ImageField(upload_to='room_images', default='default_room.jpg') photo_3 = models.ImageField(upload_to='room_images', default='default_room.jpg') is_published = models.BooleanField(default=False) date_created = models.DateTimeField(default=timezone.now, editable=False) slug = AutoSlugField(populate_from=['title', 'listing_type', 'bathroom_type', 'room_type']) rating = models.IntegerField(default=5) approved = models.BooleanField(default=False) total_bookings = models.IntegerField(default=0) def __str__(self): return self.title In my homepage what I want to do is show the listings which are nearby me. For that I have a function named as near_places. This near_place function … -
django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported
I am trying to run our django-python project. When i am running this command python manage.py makemigrations it is showing error django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Django==4.0.1, djongo==1.3.6, pymongo==3.12.1, djangorestframework==3.11.1 DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'xxxxxxDB', 'HOST': 'mongodb+srv://dbadmin:xxxxxadmin@cluster0.mn4rg.mongodb.net/xxxxxxDB retryWrites=true&w=majority', 'USER': 'dbadmin', 'PASSWORD': 'xxxxxxxxxx', "authMechanism": "SCRAM-SHA-1", } } -
DRF - enable single object lookup without filter
Using default DRF Viewsets with the following models and model serializers: class Company(Model): active = BooleanField() class Person(Model): company = ForeignKeyField(to=Company) My filter for Companies: class CompanyFilter(filters.FilterSet): ... @property def qs(self): parent = super().qs if 'active' not in self.data: return parent.filter(active=True) return parent I would like to: hide inactive companies by default have a proper navigation from all persons, even to companies that are deactivated According to DRF docs: Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. If I introduce the filter mentioned, a user navigating from person to his company will get a 404 if this company is inactive. He would need to set a GET parameter on a single object lookup which is impossible to know. -
Can't Populate Database by excel file in Django ( Management Command )
Management Command (populatedb.py) import pandas as pd from django.core.management.base import BaseCommand from django.apps import apps class Command(BaseCommand): help = "Creating model objects according the file path specified" def add_arguments(self, parser): parser.add_argument('--path', type=str, help="file path") parser.add_argument('--model_name', type=str, help="model name") parser.add_argument('--app_name', type=str, help="django app name that the model is connected to") def handle(self, *args, **options): file_path = options['path'] _model = apps.get_model(options['app_name'], options['model_name']) df = pd.read_excel(file_path) header = list(df.columns) for row in df: _object_dict = {key: value for key, value in zip(header, row)} _model.objects.create(**_object_dict) Terminal Error: ValueError: Cannot assign "'a'": "State.country" must be a "Country" instance. -
Django filter specific attributes from API response
I'm working with TMDB API and i want to get the specific video from a dictionary of videos that is the main trailer of a movie. movie_video_request = requests.get("https://api.themoviedb.org/3/movie/" + str(movie_id) + "/videos?api_key=" + TMDB_API_KEY) movie_video_results = movie_video_request.json() movie_videos = movie_video_results['results'] newDict = dict() for key,value in movie_videos.items(): if key == 'name' and value == 'Official Trailer': newDict[key] = value return render(request, 'Movie Details.html', {'newDict ':newDict }) My API response "results": [ { "iso_639_1": "en", "iso_3166_1": "US", "name": "Walking Corpses Clip", "key": "GGe_h2MWMrs", "site": "YouTube", "size": 1080, "type": "Clip", "official": true, "published_at": "2022-01-29T17:00:39.000Z", "id": "61f77629bb105700a0b16a3f" }, { "iso_639_1": "en", "iso_3166_1": "US", "name": "Official Trailer", "key": "JfVOs4VSpmA", "site": "YouTube", "size": 1080, "type": "Trailer", "official": true, "published_at": "2021-11-17T01:30:05.000Z", "id": "61945b8a4da3d4002992d5a6" }, { "iso_639_1": "en", "iso_3166_1": "US", "name": "The New Spider-Man Title is…", "key": "iqyPvdsOWKk", "site": "YouTube", "size": 1080, "type": "Teaser", "official": true, "published_at": "2021-02-24T17:44:20.000Z", "id": "60378fdcd132d60040a45d96" } ] I want my result to be that of the Official Trailer {key": "JfVOs4VSpmA"} so that I can place it in an <a href> tag <a href="https://www.youtube.com/watch?v={{ newDict.value }}"> <p> Watch Trailer </p> </a> I'm getting an error Exception Value: 'list' object has no attribute 'items' -
React Native FormData not being sent to Django API
I have created a simple Register page in Expo CLI but when I try to send the data to my Django Server it is not receiving the actual content like email password etc. I have tested this API with Postmen its working fine there, any idea what might be causing this? Here is the working example from Postmen Postmen Working Api Calls Here is the Console Log Output From the vscode terminal And my Register.js Code import { View, Text, StyleSheet, KeyboardAvoidingView, Image, } from "react-native"; import React from "react"; import { Button, SafeAreaView } from "react-native"; import { TextInput, TouchableOpacity } from "react-native-gesture-handler"; import * as ImagePicker from "expo-image-picker"; import axios from "axios"; import { auth_URL } from "../config/env"; const Register = ({ navigation }) => { const [image, setImage] = React.useState(null); const [userData, setUserData] = React.useState({ username: "", email: "", password: "", confirm_password: "", }); const pickImage = async () => { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [4, 3], quality: 1, }); console.log(result); if (!result.cancelled) { setImage(result.uri); } }; var data = new FormData(); data.append("username", userData.username); data.append("email", userData.email); data.append("password", userData.password); data.append("re_password", userData.confirm_password); data.append("image", { uri: image, type: "image/jpeg", name: "image.jpg", }); const handleSubmit … -
Save Logs inside Django container to AWS S3
Hey i have a docker Django app deployed on AWS. i am having trouble figuring out a way to store the logs generated inside the container, whenever i build it again the logs are delete. i want to store the logs to S3 maybe using a CRON job. one thing i can do is docker-compose -f docker-compose.prod.yml exec web tail django.log > django.log this gets the logs out. but there is also a directory that has sub directories that has logs for scrappy. they also need to be stored on s3 once a day. any guide will help. thanks! -
EditUserForm() create a new user insted of editing the correct one in Django
I'm new to Django and I'm building my first website. I'm now in the phase of creating the register/edit profile pages. I have correctly created my register page but I'm having a hard time creating the edit profile page. My profile has the classic fields username, first name, last name, email, password. On my edit page, I would like to be able to modify only the email field. For some reason, instead of editing the current user, my edit profile page creates a new user with every field blank except for the one I've edited. My code can be found below. urls.py urlpatterns = [ path('register', views.register_user, name="register"), path('account', views.account_user, name="account"), ] views.py @unauthenticated_user def register_user(request): if request.method == "POST": form = RegisterUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, "Registration Succesfully") # ogni utente è associato ad un gruppo univoco Group.objects.get_or_create(name=username) group = Group.objects.get(name=username) group.user_set.add(user) user.save() else: pass else: form = RegisterUserForm() return render(request, 'authenticate/register_user.html', { 'form': form, }) @authenticated_user def account_user(request): if request.method == "POST": form = EditUserForm(request.POST) if form.is_valid(): form.save() else: pass else: form = EditUserForm() return render(request, 'authenticate/account.html', { 'form_edit': form, }) forms.py class RegisterUserForm(UserCreationForm): email = … -
django: how to render and redirect page together at same time
I have a home page (OnlinePricing.html) as form for user to input some information. After input some required information, if the user click the button "Get Pice", the price will be shown in the botton page (here I am using htmx to partially refresh the home page). if the user click the button "Order Now", it will need to redirect to the new page called CreateOrder.html at path: "homepage/order/", where the price will be shown in this new page. below is the full codes. The current problem is related to the function of CreateOrder in veiws.py. When click "Order Now", the page redirect but with some wrong information: NoReverseMatch at /order/ Reverse for 'CreateOrder' with keyword arguments '{'kwargs': {'pickup_address': 'xxx', 'delivery_address': 'xxx', 'distance': xxx, 'charge': xxx}}' not found. 1 pattern(s) tried: ['order\\/\\Z'] #views.py def OnlinePricing(request): result = 0 pickup_date = "" pickup_address = "" delivery_address = "" weight = 0 volume = 0 height = 0 stack = "" FTL = "" time_window = "" dist = "" charge = "" navi_load = "" navi_unload = "" error_message = "" try: if request.method == "POST": # print("REQUEST ", request.POST) pickup_date = request.POST.get('pickup_date') pickup_address = request.POST.get('pickup_address') delivery_address = request.POST.get('delivery_address') weight = …