Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i record an audio in .wav file format that would meet the standard of Google Speech To Text API in React Native Expo
I have a function that starts and stops recordings, when the recording stops, i can playback the recording and everything works well, but whenever I upload the audio file to Google for transcription, I get an empty response. But when i upload another .wav file (downloaded online, not the recording). I get the transcription of that audio. const startRecording = async () => { try { console.log("Requesting permissions.."); const { status } = await Audio.requestPermissionsAsync(); if (status !== "granted") { alert("Sorry, we need audio recording permissions to make this work!"); return; } console.log("Starting recording.."); await Audio.setAudioModeAsync({ allowsRecordingIOS: true, playsInSilentModeIOS: true, }); const { recording } = await Audio.Recording.createAsync({ android: { extension: ".wav", outputFormat: Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT, audioEncoder: Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT, sampleRate: 16000, numberOfChannels: 1, bitRate: 128000, }, ios: { extension: ".wav", audioQuality: Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH, sampleRate: 16000, numberOfChannels: 1, bitRate: 128000, linearPCMBitDepth: 16, linearPCMIsBigEndian: false, linearPCMIsFloat: false, }, }); setRecording(recording); } catch (err) { console.error("Failed to start recording", err); } }; const stopRecording = async () => { console.log("Stopping recording.."); if (recording) { await recording.stopAndUnloadAsync(); const uri = recording.getURI(); setRecording(null); uploadAudio(uri); } }; function getOtherUser(data, username) { if (data.receiver.username !== username) { return data.receiver; } if (data.sender.username !== username) { return data.sender; } return null; } … -
ModuleNotFoundError: No module named 'walk.myadmin'
I am trying to import my myadmin models into shoppingapp when I am getting error from walk.myadmin.models import Order I am trying this code and getting error when also I tried this one from myadmin.models import Order but same error I am expecting to import my models from one app to another in the same project. -
Django Template Not Displaying Vendor Contact and Description Fields
I'm working on a Django project where I have a Vendor model. The goal is to display the vendor's profile, including their contact information and description, on a profile page. However, the contact and description fields are not displaying in the template. Here is my Vendor model definition: class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") cover_image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=RichTextUploadingField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title Here is the view function that retrieves the vendor profile: def shop_page(request): products = Vendor.objects.all() revenue = CartOrder.objects.aggregate(price=Sum("price"))["price"] total_sales = CartOrderItems.objects.filter(order__paid_status=True).aggregate(qty=Sum("qty"))["qty"] context = { "products": products, "revenue": revenue, "total_sales": total_sales, } return render(request, "useradmin/shop_page.html", context) Here is the template shop_page.html: {% load static %} {% block content %} <style> body, html { height: 100%; margin: 0; } .container-fluid { height: 100vh; display: flex; justify-content: center; align-items: center; } .profile-card { border-radius: 12px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #ffffff; overflow: hidden; } .card-header { background-color: #007bff; color: #fff; padding: 20px; border-bottom: none; } .card-title { font-size: 2rem; font-weight: 700; margin: 0; } .card-body { padding: 30px; } .profile-image { max-width: 200px; height: … -
Frustrating Cors problem between django and react js
So hello everyone, I am working on a project which have django as the api and react js as the frontend, but i am getting this annoying cors error no matter what i do to fix it. I have tried everything and every solution i've found maybe i am doing smtg wrong but one think i can addon is that get works perfectly like expected but not post your help is much appreciated . thanks Access to fetch at 'http://localhost:8000/Chercheur/Add' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. Django side Settings.py : """ Django settings for API project. Generated by 'django-admin startproject' using Django 5.0.6. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-i*mo_5h-6v5fi_$pxy3%-acy22u4_c9vm9+a@84j^(nl&hw@ae' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True … -
Django OperationalError: MySQL Connection not available
I am encountering an issue while trying to connect my Django project to a MySQL database hosted on cPanel using "mysql-connector-python". Despite configuring the settings correctly, I consistently receive an OperationalError: MySQL Connection not available when attempting to run my Django application. Database Settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'the name', 'USER': 'the user', 'PASSWORD': 'the pass', 'HOST': 'localhost', 'PORT': '3306', } } I am using mysql-connector-python version 8.4.0 to connect to the MySQL database. Verified database credentials and ensured they match those configured in cPanel. Checked MySQL server status and confirmed it is running without issues. Error Message: django.db.utils.OperationalError: (-1, 'MySQL Connection not available.', None) The Django application and MySQL database are hosted on separate servers, with cPanel managing the MySQL instance. The MySQL user has been granted all privileges (ALL PRIVILEGES) for the specified database. -
Serving media files in Django using whitenoise for simple blog application
I am building a simple blog application where only I would be uploading the images and text of the blog from admin dashboard. I used whitenoise in production, with static files like css js and logo images etc. were loading correectly, but the media files of the blog were not being served. I explore the web and got to know that due to security considerations, static files and media files are separated with media files being loaded from storage services like S3 bucket etc. But in my case, only me, not any external user would be uploading the images for the blog from admin dashboard, so the security risk doesn't seem to apply here. (correct me if I am wrong here). So, to serve the media files from whitenoise what I did was to make static root and media root as same location, and used {% static %} to serve the blog images instead of media url. Now the application is working as it should, but I am concerned whether this approach is suitable in the long run or not. Please advise if there is any downside of using this approach for simple application like blogging websites. -
Admin page not found (404) in Django project?
I'm using a shared hosting with cPanel but without Terminal access. It was hard to find tutorial for this situation. After struggling to make it work. The website shows the home page at : https://mywebsite.com but not found (404) for the url: https://mywebsite.com/admin or https://mywebsite.com/admin/ I didn't touch anything in urls.py. The homepage is showing the famous green rocket and the message "The install worked successfully! Congratulations!" What I did is to run manage.py migrate and collectstatic and set STATIC_ROOT = 'home/mywebsite/dj/static/' in setting.py. But all of the above haven't improve the situation. Feel free to edit or improve the title of my question. -
Is it possible to change the url in view (Django) after a certain operation?
Let's say there is a page of a separate blog article with this url (aviary-ensemble is the slug of the article): http://127.0.0.1:8002/articles/article/aviary-ensemble/ Now I'm making a comment system and the form for writing a comment is on the same page. The view for creating a new comment I have formalized as follows: if there is no submitted data, then load the page, if there is - then based on this data create a comment and load the page. def details(request, slug, author=None): article = models.Article.objects.get(slug=slug) print(author) if request.method == 'POST': if author is not None: user = User.objects.get(username=author) print(user.username, type(user)) comment_author = UserProfile.objects.get(user=user) comment = request.POST['comment_area'] if comment[0] == '@': receiver = comment[1:].split(', ')[0] comment_text = comment[1:].split(', ')[1] models.Comment.objects.create(article=article, author=comment_author, receiver=receiver, text=comment_text) else: models.Comment.objects.create(article=article, author=comment_author, text=comment) article_comments = models.Comment.objects.filter(article=article) context = { 'article': article, 'article_comments': article_comments } return render(request, 'articles/article.html', context=context) else: article.views = article.views + 1 article_comments = models.Comment.objects.filter(article=article) context = { 'article': article, 'article_comments': article_comments } return render(request, 'articles/article.html', context=context) I set the url itself as follows: urlpatterns = [ path('', views.index, name='articles_catalog'), path('article/<slug:slug>/<str:author>/', views.details, name='comment_creation'), path('article/<slug:slug>/', views.details, name='details'), ] The nuance is that after submitting the form the url changes to http://127.0.0.1:8002/articles/article/aviary-ensemble/admin/ (admin is the username of … -
Why can I not drill down a model to get to a field?
I have this contestant model: class Contestant(models.Model): GENDERS = [ ("male", "Male"), ("female", "Female") ] EYE_COLORS = [ ("brown", "Brown"), ("blue", "Blue"), ("green", "Green"), ("hazel", "Hazel"), ("amber", "Amber"), ("gray", "Gray") ] HAIR_COLORS = [ ("black", "Black"), ("brown", "Brown"), ("blonde", "Blonde"), ("red", "Red"), ("gray", "Gray"), ("white", "White"), ("pink", "Pink"), ("purple", "Purple"), ("green", "Green"), ("orange", "Orange") ] main_photo = models.FileField(upload_to='main_image/') first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() gender = models.CharField(max_length=8, choices=GENDERS) height = models.IntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(120)]) weight = models.IntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(1500)]) eye_color = models.CharField(max_length=20, choices=EYE_COLORS) hair_color = models.CharField(max_length=20, choices=HAIR_COLORS) city = models.OneToOneField(City, on_delete=models.DO_NOTHING, related_name="contestant") user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="contestant_profile") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "contestant" verbose_name_plural = "contestants" db_table = "contestants" def __str__(self): return f"contestant {self.user}" and I want people to vote on the contestant. Here is the votes model: class ContestantVote(models.Model): contestant = models.ForeignKey(Contestant, on_delete=models.CASCADE) score = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(10)]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="votes") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = (("contestant", "user"),) verbose_name = "vote" verbose_name_plural = "votes" db_table = "votes" def save(self, *args, **kwargs): if ContestantVote.objects.filter(contestant=self.contestant, user=self.user).exists(): raise ValidationError(f'User {self.user} has already voted for contestant {self.contestant}.') if … -
Password field in Signup/Login form not appearing properly | Django | HTML | Bootstrap
I am trying to create a custom signup form using HTML, CSS, Bootstrap as front end, and Django as backend, when I create the form, firstname, lastname, and email are appearing as required, but the password and confirm_password fields are not appearing as required, from forms.py, the widget's placeholder and class=form-control is also not being applied to it. I asked ChatGPT, it is asking to clear Cache, switching to incognito or a different browser, I tried all things, and still it is appearing the same. I am providing all the files associated with the signup form I created. models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, last_name=None, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set.') if not first_name: raise ValueError('The First Name field must be set.') if not password: raise ValueError('Password cannot be left blank.') email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] def __str__(self): return self.email forms.py from django import forms from django.contrib.auth.forms import … -
reasons for using rust api over django, node?
Has anyone made a large scale rust web api and if so why did you choose it over easier languages like python. Is there significant performance, lower response times, concurrency, etc from using rust compared to python or is it negligible. Assume we’re talking about a social media app which wouldnt be heavy mathematically. It was suggested to me that a web api is dominated by the speed and efficiency of database operations and this using a faster language like rust compared to python has negligible benefits in real world, is this true in your experience? -
How to pass a Django form response through another template
I am creating a site for users to record their chicken's weights and I am trying to design a confirmation form for if a user tries to submit another weight for the same chicken on the same day. In other words, if a record already exists for that date, how to ask the user if it should be overwritten without the user re-entering the weight. This is all I have so far: # views.py def add_record(request, chicken) -> HttpResponseRedirect | HttpResponsePermanentRedirect | HttpResponse: """ View for the "record_weight.html" Post & Get methods """ if request.method == "POST": form = RecordForm(request.POST) if form.is_valid(): record = form.save(commit=False) record.chicken = Chicken.objects.filter(number=chicken).first() record.date = datetime.now().date() try: Record.save(record) except ValidationError: # There is a record for that day, render another form asking if they want to overwrite return render(request, "tags/duplicate_record.html", {"bird": record.chicken}) return redirect("/admin/tags/record/") form = RecordForm() try: birds = Chicken.objects.all() req_bird = birds.filter(number=chicken).first() except Chicken.DoesNotExist: raise Http404("Bird does not exist") try: req_records = Record.objects.filter(chicken_id=chicken).order_by("date").reverse() except Record.DoesNotExist: req_records = [] return render(request, "tags/record_weight.html", {"bird": req_bird, "records": req_records, "form": form, "nav_filter": get_birds_navbar(birds)}) # duplicate_records.html (styling removed for easier reading) {% extends "tags/layout.html" %} {% block content %} <div> <div> <h2>There is already a weight for today!</h2> … -
Image Field in Django forms is not working
urls.py: urlpatterns = [ path("",views.index,name = "index"), path("signup/",views.signup,name = "signup"), path("login/",views.login,name = "login"), ] urlpatterns+=static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT ) settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' forms.py: class SignUp(forms.Form): is_doctor = forms.BooleanField(label = "Are you a doctor?",required=False) f_name = forms.CharField(label = "First Name", max_length=200) l_name = forms.CharField(label="Last Name",max_length=200) username = forms.CharField(label = "Username",max_length = 100) email = forms.CharField(label = "Email",max_length=200) profile_pic = forms.FileField(label= "Profile Picture", widget = forms.ClearableFileInput(attrs={'class':'form-control'}),required=False) password = forms.CharField(label ="Password",max_length=200) confirm_password = forms.CharField(label = "Confirm Password",max_length=200) address = forms.CharField(label="Address",max_length = 400) views.py: form = SignUp(response.POST,response.FILES) In the html file I have the attribute: enctype="multipart/form-data" I cannot understaNd what else I need to do. I have read so many docs and watched so many videos. They're all saying the same thing. -
Django authencation problem- two different authencation one for custom admin and other for worker
I am facing this problem again n again. lemme explain you i am working on a complaint management site for my college, I have designed a separate customized admin panel which is working good, but the problem is occurring in making another admin panel for worker, where they can see allotted complaints and other things related to that, but I am not getting my desired result. ValueError at /worker-login/ The following fields do not exist in this model, are m2m fields, or are non-concrete fields: last_login **models.py def generate_id(): alphanumeric = string.ascii_uppercase + string.digits return ''.join(random.choices(alphanumeric, k=4)) class Assign(models.Model): id = models.CharField(max_length=4, primary_key=True, unique=True, default=generate_id) name = models.CharField(max_length=20) email = models.EmailField(max_length=30, unique=True) dob = models.DateField(null=True, blank=True) department = models.ForeignKey('Department', on_delete=models.SET_NULL, null=True, blank=True) phone_number = models.CharField(max_length=13, unique=True) profile_picture = models.ImageField(upload_to='profile_pictures/', blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['dob'] class Meta: # Add this to prevent clashes with auth.User's groups and user_permissions default_related_name = 'assign_users' def save(self, *args, **kwargs): if not self.id: self.id = generate_id() super().save(*args, **kwargs) def __str__(self): return self.email **views.py def worker_login(request): if request.method == 'POST': email = request.POST.get('email') id = request.POST.get('id') user = authenticate(request, email=email, id=id) if user is not None: login(request, user, backend='app1.authentication_backends.AssignBackend') return redirect('worker_dashboard') else: messages.error(request, 'Invalid … -
why does self.filefield_field.path of an instance of a django model does not match the path where the file was actually uploaded
I am building an app in django (Django==3.1.14). the app should allow the user to upload zip files (in particular, they are shapefiles). I want django to upload and manage these files by storing them inside a model, having a FileField t host the file. I want each file to be uploaded at a specific path, like this: MEDIA_ROOT/shp/<timestamp>/<file_name>.zip NOTE: timestamp has seconds precision. my model has a field shp_file_folder_path that must have value equal to the path of the folder in which <file_name>.zip is stored, so MEDIA_ROOT/shp/<timestamp> Now, I have written the following model def generate_current_timestamp(): return datetime.datetime.now().strftime("%Y%m%d%H%M%S") def generate_uploaded_shp_file_relpath(): UPLOADED_SHP_FILES_DIR = 'shp' uploaded_shp_files_relpath_from_media_root = UPLOADED_SHP_FILES_DIR timestamp = generate_current_timestamp() current_file_subfolder = timestamp # relative path of the folder which will contain the uploaded file uploaded_shp_file_relpath = os.path.join( uploaded_shp_files_relpath_from_media_root, current_file_subfolder ) return uploaded_shp_file_relpath # Create your models here. class Shp(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=1000, blank=True) shp_file = models.FileField(upload_to=generate_uploaded_shp_file_relpath()) # this is a file, but in postgres is represented as path uploaded_date = models.DateField(default=datetime.date.today, blank=True) shp_file_folder_path = models.CharField(default='undefined', max_length=1000, blank=True) # this is to be not visible nor editable by admins # this defaultvalue is not required the function to be correct because it will be overwritten by the … -
raised unexpected: TypeError('send_verification() takes 1 positional argument but 3 were given') in celery
class CreateAccountView(APIView): permission_classes = [] def post(self, request): print(request.data) email = request.data.get('email') if User.objects.filter(email=email).exists(): return Response({"message": "User with this email already exists"}, status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): domain = request.get_host() send_verification.delay(email,domain) serializer.save() return Response({"message": "Check your email to verify your account"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @shared_task(bind=True) def send_verification(self,email,domain): print(email) try: email_from = settings.EMAIL_HOST_USER token = generate_token(email) verify_url = f'http://{domain}{reverse("verify_email", args=[token])}' subject = 'Verify your email address' message = f'Click the link to verify your email: {verify_url}' send_mail(subject, message, email_from, [email]) print(message) except Exception as e: print(f'Error sending email: {e}') print("Done") return "Done" when i was try to send a verification link through celery and pass 2 arguments to the send_verification() function but it always says takes 1 positional argumentt and 3 where given -
How do I get my CSS to function in Chrome?
I am new to Python and taking a Django course online from Dave Gray. In the course we create CSS for Nav feature. * { margin: 0; padding: 0; box-sizing: border-box; } body { min-height: 100vh; background-color: black; color: whitesmoke; font-size: 3rem; display: flex; flex-flow: column; } nav { padding: 1rem; background-color: #44B78B; color: white; font-size: 2.5rem; } main { flex-grow: 1; display: grid; place-content: center; } h1, p { text-align: center; } a { text-decoration: none; color: #81dbb8; } a:hover { opacity: .85; } My Layout HTML is: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> {% block title %} Django App {% endblock %} </title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/main.js' %}" defer></script> </head> <body> <nav> <a href="/">🏡</a> | <a href="/about">😊</a> | <a href="/posts">📰</a> </nav> <main> {% block content %} {% endblock %} </main> </body> </html> My Home Page HTML is: {% extends 'layout.html' %} {% block title %} Home {% endblock %} {% block content %} <h1>Home</h1> <p>Check out my <a href="/about">About</a> page.</p> {% endblock %} I normally use Chrome and it did not look like his example. After reviewing the CSS I opened the … -
Flutterwave 403 Client Error: Forbidden for url: https://api.flutterwave.com/v3/payments
Please, I need help integrating flutterwave on my django project. Whenever I click on the checkout button on my payment page, I get the error above. Here is what my flutterwave view looks like: this view is used to get the slug of the particular product and price when the checkout button is clicked def flutterwave(request,slug,price): mobile = Mobile.objects.get(user=request.user) try: food_product = food.get(slug=slug,food_price=price) #soup_product = soup.get(soup_item=product) except food.DoesNotExist: return JsonResponse({"error": "Food product does not exist"}, status=404, safe=False) url = "https://api.flutterwave.com/v3/payments" headers = { "Authorization": f"Bearer {FLUTTERWAVE_LIVE_SECRET_KEY}", "Content-Type": "application/json" } payload = { "tx_ref": tx_ref(), "amount": float(food_product.food_price), "currency": "NGN", "redirect_url": "http://127.0.0.1:8000/payments/verify_payment/", "meta": { "consumer_id": 23, "consumer_mac": "92a3-912ba-1192a" }, "customer": { "email": request.user.email, "phonenumber": str(mobile.phone_no), "name": request.user.username }, "customizations": { "title": "Pied Piper Payments", "logo": "http://www.piedpiper.com/app/themes/joystick-v27/images/logo.png" }, "configurations": { "session_duration": 10, # Session timeout in minutes (maxValue: 1440 minutes) "max_retry_attempt": 5 # Max retry attempts for failed transactions } } try: print("URL:", url) print("Headers:", headers) print("Payload:", payload) response = requests.post(url, headers=headers, json=payload) print("Response Type:", type(response)) response.raise_for_status() # Raise an error for bad status codes # Assuming the response is JSON, you can access it like this: json_response = response.json() return JsonResponse(json_response, safe=False) except requests.exceptions.RequestException as err: error_message = f"Error: {err}" return JsonResponse({"error": … -
API for dota player information using Django
Good afternoon, I might be mistaken as I am new to Django and API, but hopefully someone can correct me if I am wrong. I have this task to create a webpage here is the sample https://impactosolardota.com/. I have to create a website for something similar like this is Cuban leaderboard and I want to do one for Colombia. How can I obtain the player information that updates constantly. As far as my understanding goes, I need an API to send information from another website to mine. My plan is to build a Django website and the frontend in React. However, I am starting to think that I might not need Django at all and maybe do only with React?. -
Django Admin automatically logs me out when i click the save button and won't allow me log in again
Whenever I click the save button to add user on the django admin interface, it automatically logs me out and won't re-authenticate me despite being the superuser. The design pattern: I created a class called CustomUser which inherited the django AbstractUser and another class UserProfile model which has OneToOneField to the settings.AUTH_USER_MODEL(main.CustomUser) and added some common fields among the student, parent and staff(e.g other_name), then student, staff and parent class inherited the UserProfile and I added their specific field. So I do add a user first, then go to the student model to add the user as a student. main is my app_name. Kindly help with on this as I have deadline which is near. I'll provide more details and code on request settings.py file from pathlib import Path import os import secrets from django.conf.urls import handler403 # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-!&740lo5u6#-@c9d80ab*-!k1-8f$fu@r*3xp5ytke)7t+dwy+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition # SESSION_TIMEOUT_SECONDS = 120 … -
I'm having problems with the layout of a web page using the django framework
I'm taking a course at ww3school and in part of the course I see that it didn't look the same in the proposed exercise, I'm going to put two images to reference my problemIn this image the page layout is correct, this image was my result I'm using Visual Studio Code on Windows 10 Django version: I've made sure I'm using the same version of Django as the course. I made sure the project settings (like settings.py) are correct. I checked that I followed the same customization steps. I tried clearing the browser cache or opening the page in an incognito/incognito window. -
How to make content fetched during login persist even if the user logs out and logs in again?
I currently am working on a project where a user authenticates, and when they are redirected to the home page, a GET request to an API is made: def home(request): url = f'https://icanhazdadjoke.com/' headers = { "Accept": "application/json" } #Putting the application/json in the header to get a JSON result r = requests.get(url,headers=headers) #Making a get request to get a random dad joke data = r.json() #Converting JSON data to a python dictionary required_joke = {'joke': data['joke']} return render(request,'test_section/Home.html',required_joke) Now, I mainly have two requirements: When the user presses the refresh button, a new joke should be generated (satisfied). If the user logs out, and logs back in again, the same joke that was being shown on the screen previously should be shown. For example, if the user logs out now, and logs back in, he should see this same joke displayed. I will be very grateful if someone can guide me regarding how to tackle this. It looks simple but I do not understand where to start. -
Updating a django table, hashing a specific field in a table
I have a table that looks something like class PodUsage(models.Model): pod_id = models.CharField(max_length=256, db_index=True) pod_name = models.CharField(max_length=256) start_time = models.DateTimeField(blank=True, null=True, default=timezone.now) end_time = models.DateTimeField(blank=True, null=True) anonymised = models.BooleanField(default=False) user = models.ForeignKey("accounts.ServiceUser", null=True, blank=True, on_delete=models.CASCADE) As part of our GDPR requirement, we need to anonymize data after a certain period, which I could absolutely do as a loop: count = 0 records = PodUsage.objects.filter( anonymised=False, start_time__lte=timezone.now() - timedelta(weeks=settings.DATA_ANONYMISING_PERIOD_WEEKS) ) for record in records: record.pod_name = hashlib.sha256(record.pod_name.encode('utf-8')).hexdigest() record.user = None record.anonymised = True record.save() count += 1 # Log count somewhere however I think I should be able to do it with an update function: count = PodUsage.objects.filter( anonymised=False, start_time__lte=timezone.now() - timedelta(weeks=settings.DATA_ANONYMISING_PERIOD_WEEKS) ).update( pod_name = hashlib.sha256(pod_name.encode('utf-8')).hexdigest(), user = None, anonymised = True ) # Log count somewhere ..... but I can't figure out the correct incantation to reference the field in the update portion as given, pod_name is not defined sha256("pod_name".encode('utf-8')) obviously just encodes the string "pod_name" sha256(F("pod_name").encode('utf-8')) breaks the code with 'F' object has no attribute 'encode' Any suggestions? -
Django: Preload query from django-simple-history
I need to preload the update history queries saved with django-simple-history, to significantly improve the query execution time, for example, I have these models in my application: class Staff(models.Model): registration = models.CharField(max_length=100, unique=True) identification_type = models.CharField(max_length=2, choices=( ('V', 'V'), ('E', 'E'), ('J', 'J') ), default='V') identification_number = models.CharField(max_length=100, unique=True) first_names = models.CharField(max_length=100) last_names = models.CharField(max_length=100) birth_date = models.DateField() hire_date = models.DateField() hire_date_to_public_administration = models.SmallIntegerField(default=0) termination_date = models.DateField(null=True) sex = models.CharField(max_length=10, choices=( ('F', 'Femenino'), ('M', 'Masculino') )) address = models.TextField() marital_status = models.CharField(max_length=15, choices=( ('Soltero/a', 'Soltero/a'), ('Casado/a', 'Casado/a'), ('Divorciado/a', 'Divorciado/a') )) education_level = models.CharField(max_length=100) department = models.ForeignKey( Department, on_delete=models.RESTRICT, related_name='staffs' ) position = models.ForeignKey( Position, on_delete=models.RESTRICT, related_name='staffs' ) payroll_type = models.CharField(max_length=10, choices=[ ('Empleado', 'Empleado'), ('Obrero', 'Obrero'), ], default='Empleado') worker_type = models.CharField(max_length=10, choices=[ ('Fijo', 'Fijo'), ('Contratado', 'Contratado'), ('Pensionado', 'Pensionado'), ('Jubilado', 'Jubilado'), ], default='Contratado') status = models.CharField(max_length=100, choices=( ('Activo', 'Activo'), ('Inactivo', 'Inactivo'), ), default='Activo') bank = models.CharField(max_length=100) bank_number = models.CharField(max_length=100) concepts = models.ManyToManyField( Concept, related_name='staffs', blank=True ) salary = models.DecimalField(max_digits=8, decimal_places=2) children_number = models.SmallIntegerField(default=0) is_disabled = models.BooleanField(default=False) receive_complement = models.BooleanField(default=False) history = HistoricalRecords() class Meta: ordering = ['identification_number'] class Payment(models.Model): date = models.ForeignKey( Calendar, on_delete=models.RESTRICT, related_name="payments" ) staff = models.ForeignKey( Staff, on_delete=models.RESTRICT ) total = models.DecimalField(max_digits=8, decimal_places=2, default=0) total_deduction = models.DecimalField(max_digits=8, decimal_places=2, default=0) … -
creating custom validators for fields in Django REST framework serializers.Serializer
I am writing a serializer for a complicated put API with a large validate function. To simplify the logic and make it more readable, I want to create validators for individual fields (I want to make my serializer class as small as possible and hence don't want to write individual validate methods for each field). I am passing context to my serializer from the view and each of my fields share a common context. I want to use that context in the validator to perform the required checks. This is how I am attempting to create custom validators: My validator class: class MyCustomValidator: requires_context = True def __call__(self, value, serializer_field): context = serializer_field.context print(f"got this context: {context}") my serializer: class MySerializer(serializers.Serializer): my_field = serializers.IntegerField(required=True, validators=[MyCustomValidator()]) sending context in my view: def get_serializer_context(self): context = super().get_serializer_context() context.update({'test_context': {'key': 'value'}}) return context But when I am calling this API, I get the following error: __call__() missing 1 required positional argument: 'serializer_field' Can someone please tell me what am I missing here? Thank you...