Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template code not showing in Django template file despite moving from base.html to sports.html
I have a Django project where I initially wrote all the HTML and template code in the base.html file. However, as my project grew, I decided to organize my templates better by moving specific code to separate template files. I created a new template file named sports.html and copied the relevant code from base.html to sports.html. However, when I view the sports.html page in my browser, I only see the contents of base.html being rendered, and the code I moved to sports.html is not showing up. Here's the structure of my sports.html file: {% extends 'BTXApp/base.html' %} {% block content %} <!-- My content code goes here --> <!-- But it's not showing up in the rendered page --> {% endblock %} I have double-checked the paths and the configuration in my Django settings, and everything seems to be correct. I can see the code perfectly fine in my text editor (Sublime Text), but it's not rendering in the browser. What could be causing this issue, and how can I resolve it? Any help or insights would be greatly appreciated. Thank you! -
Django-React App not finding manifest.json file
I am working on a Django + React powered system. I have encountered this manifest not found error for a while now. The frontend page shows nothing at all. Help me find the root cause. I have shared the images as follows: 1.) The image of the error: enter image description here 2.)Image of the admin working perfectly: enter image description here Any help will really be appreciated. Here is the link to my github where the files are:https://github.com/FelixOmollo/FourthYearProject Here is my navbar code: import AuthContext from '../context/AuthContext' import {useContext} from 'react' import jwt_decode from "jwt-decode"; import { Link } from 'react-router-dom' function Navbar() { const {user, logoutUser} = useContext(AuthContext) const token = localStorage.getItem("authTokens") if (token){ const decoded = jwt_decode(token) var user_id = decoded.user_id } return ( <div> <nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <Navbar.Brand href='/'>SPORRMS</Navbar.Brand> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav "> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/s">Home</a> </li> <li class="nav-item"> <Link class="nav-link" to="/about">About</Link> </li> {token === null && <> <li class="nav-item"> <Link class="nav-link" to="/login">Login</Link> </li> <li class="nav-item"> <Link class="nav-link" to="/register">Register</Link> </li> </> } {token !== null && <> <li … -
RelatedObjectDoesNotExist at /account/edit/ User has no profile
I can edit other users with no admin status with no issues but this error message saying RelatedObjectDoesNotExist at /account/edit/ User has no profile when i try to edit superuser. I created this superuser AFTER I have added Profile module class with its attributes, and making migrations. Spent hours trying to figure it out but couldn't. Thank yall for any help Models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class Profile(models.Model): print(f'------->{settings.AUTH_USER_MODEL}') user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True, default=None) photo = models.ImageField(blank=True, upload_to="users/%Y/%m/%d/") def __str__(self): return f'Profile of {self.user.username}' Views.py from account.models import Profile @login_required def Edit(request): if request.method == "POST": user_form = UserEditForm(instance= request.user, data=request.POST) profile_form = ProfileEditForm(instance= request.user.profile,data=request.POST, files=request.FILES) if user_form.is_valid(): user_form.save() profile_form.save() return render(request,'account/dashboard.html') else: user_form = UserEditForm(instance= request.user) profile_form = ProfileEditForm(instance= request.user.profile) return render(request, "account/edit.html",{'user_form':user_form}) forms.py class UserEditForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name','email'] def clean_email(self): data = self.cleaned_data['email'] qs = User.objects.exclude(id=self.instance.id).filter(email=data) if qs.exists(): raise forms.ValidationError('email already in use') else: return data class ProfileEditForm(forms.ModelForm): class Meta: model = Profile fields = ['date_of_birth','photo'] edit.html {% extends "base.html" %} {% block content %} <html> <p>Please enter correct information bellow to edit</p> <form method="POST" enctype="multipart/form-data"> {{user_form.as_p}} {{profile_form.as_p}} {% csrf_token … -
Django REST Framework: can't properly annotate values to many-to-many model, keep getting error Field name <field> is not valid for model <m2m model>
I have a model for recipes and many-to-many model that represents favorite recipes by users: class Recipe(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=LENGTH_FOR_TEXTFIELD) image = models.ImageField() text = models.TextField(max_length=LENGTH_FOR_TEXTFIELD) cooking_time = models.PositiveSmallIntegerField() def __str__(self): return self.name class FavoriteRecipe(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.recipe.name After POST request an entry in that model is created (recipe ID and user ID) and i am trying to write a serializer for response that will contain info about recipe itself: class FavoriteRecipeSerializerForRead(serializers.ModelSerializer): class Meta: model = FavoriteRecipe fields = ('id', 'name', 'image', 'cooking_time') So the problem is that i cannot insert into this serializer any recipe-field because i keep getting error: django.core.exceptions.ImproperlyConfigured: Field name `name` is not valid for model `FavoriteRecipe` I tried to imply select_related() and .annotate(field=Value(Query)) in my viewset like this but nothing seems to work: class FavoriteRecipeViewSet(viewsets.ModelViewSet): queryset = FavoriteRecipe.objects.all() serializer_class = FavoriteRecipeSerializerForRead def get_queryset(self): queryset = FavoriteRecipe.objects.all().annotate( recipe=Value( Recipe.objects.filter(id=self.id).values('cooking_time',) ) ) return queryset The question is: how could i do this the proper way? -
Can I Register a Django Project's Inner Directory as an App Within the Same Project?
Within a Django project, such as "myproject," where a subdirectory named "myproject" is automatically created, I've registered this subdirectory as an app with the intention of using it as a control app for the entire project. For instance, if my project directory structure looks like this: myproject/ ├── myproject/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── apps.py <!-- the odd addition --> │ ├── wsgi.py │ └── asgi.py ├── myapp1/ │ ├── __init__.py │ ├── models.py │ ├── views.py │ └── ... └── ... I've registered the inner "myproject" directory as an app within the Django project. Despite this setup functioning smoothly, I'm curious about the community's thoughts or any considerations regarding this approach. Are there any insights, opinions, or best practices associated with registering the project directory as an app within a Django project? -
JQuery .show() working, but .hide() not working
I am trying to build a dropdown select box in js, which I have to use js as it includes images. The problem is, when I click on the "input box" i made the jquery code to open it works i.e. $('#ratingDropdownContainer').on('click', function() { if ($('#dropdownListContainer').css('display') == 'none') { $('#dropdownListContainer').show(); } }) and there is no problem. But when the user selects one of the options, the .hide() won't work. The in-line style of style="display: block;" doesn't change when I do $('#dropdownListContainer').hide(); I have tried many things such as: making sure its wrapped in a $(document).ready(function(), checking if js recognizes its display is block (which it is as the console.log("okokoko"); prints as seen in my code below), I make sure my jquery is loaded before my js file, I tried using vanilla js instead, but none of those have worked, and I don't understand why the .show() would work but not the .hide(). Any help would be appreciated. Thank you. js: $('#ratingDropdownContainer').on('click', function() { if ($('.dropdown-list-container').css('display') == 'none') { $('.dropdown-list-container').show(); } }) $('.avg-rating-select').on('click', function() { var selectedRatingImg = $(this).find('img').prop('outerHTML'); var selectedRatingText = $(this).find('p').prop('outerHTML'); var newDiv = $("<div>" + selectedRatingImg + selectedRatingText + "</div>"); newDiv.addClass("rating-selected-container"); if ($('.rating-selected-container').length) { $('.rating-selected-container').replaceWith(newDiv); } else … -
Django modeltranslation not working properly on templates
I have set up and configured django-modeltranslation for a project according to the documentation as follows: urls.py from django.conf.urls.i18n import set_language from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( ... path('set_language/', set_language, name='set_language'), ) settings.py from django.utils.translation import gettext_lazy as _ INSTALLED_APPS = [ 'modeltranslation', ... ] MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TIME_ZONE = 'CET' LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', _('English')), ('cz', _('Czech')), ] LOCALE_PATHS = [ BASE_DIR / 'Project/locale/', ] USE_I18N = True Homepage language switcher <form id="languageForm" action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" /> <input id="languageInput" name="language" type="hidden" value="" /> </form> onclick="setLanguage('en')" onclick="setLanguage('cz')" function setLanguage(lang) { document.getElementById('languageInput').value = lang; document.getElementById('languageForm').submit(); } In .html templates {% load i18n %} ... {% trans "Text" %} ... I collected the strings for translation using: python manage.py makemessages -l cz Then translated them in the locale django.po file and compiled them using: python manage.py compilemessages Now when running the project and switching the language to cz, only one translated string and date strings are displayed. Thank you for your help, and I hope I provided everything needed. I tried setting up the django-modeltranslation using its documentation as I provided before. -
getting error while installig python packeges
in a Django project I faced an strange error , every thing functions so smoot but whenever I want to install a package I get this error , I'm totaly sure about my network conaction and I have tried using VPN but it didn't help (using Pycharm) WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._ven dor.urllib3.connection.HTTPSConnection object at 0x000001FF6F9617D0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine acti vely refused it'))': /simple/pillow/ what's wrong ? -
Django: Redirect to object's change (admin) page while overriding save_related
I am uploading a temporary file while changin my object, and this file might have problems which I can determine after it is fully read. I want my page to be rediretded to the object's change page whenever an error occures. here's the code i wrote: def save_related(self, request, form, formsets, change): try: cleaned_data = form.cleaned_data if cleaned_data['file_field']: DEFAULT_COLUMN_INDEX = 0 try: # read file logic here that might raise an error return super().save_related(request, form, formsets, change) except ValidationError as e: messages.error(request, f"Error while proccessing data: {str(e)}") redirection_url = reverse('admin:mymodel_change', args=[form.instance.id]) return HttpResponseRedirect(redirection_url) except TimeoutError as e: messages.error(request, f"Timeout in uploading file: {str(e)}") redirection_url = reverse('admin:mymodel_change', args=[form.instance.id]) return HttpResponseRedirect(redirection_url) Note that i can not just raise the error because it is set to response 500 because of other parts of the project (long story... i just cant change them!) Here's my problem: This code redirects to the mymodel admin page, not the change page of the object. So, here's my questions: Am i doing the right approach (since I'm new to django)? If the approach's fine, how can i fix it? -
NameError at /admin/ name 'process_request' is not defined
when i try to access to admin pannel in django project i face problem : NameError at /admin/ name 'process_request' is not defined: Internal Server Error: /admin/ Traceback (most recent call last): File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\contrib\admin\sites.py", line 259, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\utils\decorators.py", line 181, in _view_wrapper result = _pre_process_request(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\IdeaProjects\Weather_Backend\venv\Lib\site-packages\django\utils\decorators.py", line 127, in _pre_process_request result = process_request(request) ^^^^^^^^^^^^^^^ NameError: name 'process_request' is not defined i'm expecting to access to django admin panel as normal -
Django - How to create One to Many relationship using default User class
I'm creating an app called Trading Journal, that allows users to login and record the results from their stock trades. Each user should have access to only their individual entries. I am adding a ForeignKey field on my Entry class, tied to Django's default User class, to do this. But I am getting this error when I try to run the /migrate command: ValueError: Field 'id' expected a number but got 'andredi15' (andredi15 is one of the usernames) So I have two questions: 1) How do i fix this error and, 2) Should I go about this a different way? Perhaps by setting up a custom user model? Thanks! Models.py: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse from django.utils.text import slugify from django.contrib.auth.models import User from django.contrib.auth import get_user_model class Entry(models.Model): ONEORB="1-Min ORB" FIVEORB="5-Min ORB" ABCD="ABCD" REVERSAL="Reversal" PROFIT="Profit" LOSS="Loss" RESULT_CHOICES = ( (PROFIT, "Profit"), (LOSS, "Loss") ) STRATEGY_CHOICES = ( (ONEORB,"1-Min ORB"), (FIVEORB,"5-Min ORB"), (ABCD,"ABCD"), (REVERSAL,"Reversal") ) entered_date=models.DateField(auto_now_add=True) ticker=models.CharField(max_length=8, default="") strategy=models.CharField(max_length=12, choices=STRATEGY_CHOICES, default="ONEORB") result=models.CharField(max_length=6, choices=RESULT_CHOICES, default="PROFIT") comments=models.TextField(max_length=300, blank=True) image = models.ImageField(upload_to="", null=True, blank=True) #will save to default BASE_DIR which is 'uploads' username = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="usernames", to_field="username") def __str__(self): return f"{self.result} {self.entered_date}" Forms.py: from … -
Need to convert data in xml to json using python
I need to convert xml data to json format. I am using django for backend, and I'm not really comfortable parsing data from xml, so I thought about converting data in json and then parsing it. The xml data format is as shown below: <?xml version='1.0' encoding='ASCII'?> <add> ... <doc> <field name="id">1</field> <field name="title1">subtitle1</field> <field name="title2">subtitle2</field> </doc> ... </add> I need to convert format into json using python. Also, if there is any better way to do it, please let me know. I tried converting using online converters but the json data is not accurate. I'm getting the values but not the keys and some converters are throwing error. -
Getting 'Broken Pipe' Error with AJAX Request in Django
I keep encountering a "Broken pipe" error when making an AJAX request in Django. The request is intended to retrieve text and selected languages, among other data, then translate it in the views, with the translated text appearing in the output window. Here's my AJAX code snippet: Here is AJAX code: var outputTextarea = document.getElementById("output-textarea"); // AJAX request $(document).ready(function () { $('.translate-button').click(function () { // Retrieve input data var fromLanguage = document.getElementById("from-language-selectbox").selectedOptions[0]; var toLanguage = document.getElementById("to-language-selectbox").selectedOptions[0]; var isFlashcard = document.getElementById("is-flashcard-switch2").checked; var selectedDecks = document.getElementById("decks-list-selectbox").selectedOptions; console.log(selectedDecks) var selectedDeckValues = []; var inputText = document.getElementById("input-textarea").value; console.log(inputText); for (var i = 0; i < selectedDecks.length; i++) { selectedDeckValues.push(selectedDecks[i].textContent); } console.log(selectedDeckValues); var outputTextarea = document.getElementById("output-textarea"); $.ajax({ url: '{% url "mainapp:translator" %}', data: { 'input_text': inputText, 'is_flashcard': isFlashcard, 'decks': selectedDeckValues, 'from_language': fromLanguage.textContent, 'to_language': toLanguage.textContent, }, dataType: 'json', success: function (data) { console.log("success"); outputText = data.output_text; outputTextarea.textContent = outputText; }, error: function (xhr, status, error) { console.log("Error occurred: " + error); } }); }); }); And here is view: def translator(request): """View for translatation.""" if request.headers.get("x-requested-with") == "XMLHttpRequest": #Retrieve data from AJAX request input_text = request.GET.get("input_text") is_flashcard = request.GET.get("is_flashcard") if is_flashcard == "true": is_flashcard = True else: is_flashcard = False decks = ["superdeck", "talja"] #request.GET.get("decks") from_language … -
Firebase State changing problems, Page does not change its aspect when user is logged in
Basically when the user is logged in I want the homepage to have written my account instead of login/register. I tried my chatpgt since I'm a beginner but it is not working. I would really appreciate a help. I have no idea how to solve it. <script src="https://www.gstatic.com/firebasejs/10.10.0/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/10.10.0/firebase-auth.js"></script> <script> import { initializeApp } from "https://www.gstatic.com/firebasejs/10.10.0/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.10.0/firebase-analytics.js"; import { getAuth, onAuthStateChanged} from "https://www.gstatic.com/firebasejs/10.10.0/firebase-auth.js"; // Your web app's Firebase configuration const firebaseConfig = { I have removed my keys here }; // Initialize Firebase const app = firebase.initializeApp(firebaseConfig); const auth = firebase.auth(); // Listen for auth state changes onAuthStateChanged(auth, user => { if (user) { // User is signed in, show "My Account" link document.querySelector('.navigation').innerHTML = ` <a href="chat" class="nav-link">Chat</a> <a href="account" class="nav-link">My Account</a> `; } else { // No user is signed in, show "Login / Register" link document.querySelector('.navigation').innerHTML = ` <a href="chat" class="nav-link">Chat</a> <a href="auth" class="nav-link">Login / Register</a> `; } }); </script> Here is the nav bar in the html: <header> <div class="header-container"> <div class="logo-container"> <h1 class="site-title">Athena</h1> </div> <nav class="navigation"> <a href="chat" class="nav-link">Chat</a> <a href="auth" class="nav-link">Login / Register</a> </nav> </div> </header> -
I cant configure LOGIN_REDIRECT_URL Django
I want to setting that after succesfully login with google it redirect me to the profile_detail.html page LOGIN_REDIRECT_URL = "/polls/profile/" LOGOUT_REDIRECT_URL = "/" views.py def profile_detail(request): return render(request, "profile_detail.html") urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path("", views.home, name='home'), path("logout/", views.logout_view, name='logout'), path('googleLogin/', views.googleLogin, name='googleLogin'), path('profile/', views.profile_detail, name='profile_detail'), path('profile_creation/', views.create_profile, name='profile_creation') ] -
JSON Decode Exception
import requests import json URL = "http://127.0.0.1:8000/TESTGET_api/" def get_data(id = None): data = {} if id is not None: data = {'id':id} json_data = json.dumps(data) r = requests.get(url= URL, data = json_data ) data = r.json() print(data) get_data() this is the code, the problem lies at r.json(). Please guide with the solution. I tried using print(r.content) before data = r.json(). but still not working. -
CPU and time problem with gunicorn,django,nginx
We are got a project on gunicorn,django and nginx. Got a table in postgres with 600000 records with a big char fields(about 7500). That problem solved by triggers and searchvector. Also there api(rest) and 1 endpoint. On this endpoint db request take about 0.3 s. Its normal for us. But getting response take about 1 minute. I think maybe that gunicorn. While we are waitint for a response one on process take 100%. gunicorn.service User=www-data Group=www-data WorkingDirectory=/home/***/market ExecStart=/home/***/venv/bin/gunicorn \ --access-logfile - \ -k uvicorn.workers.UvicornWorker \ --workers 8 \ --threads 20 \ --bind unix:/run/gunicorn.sock \ --timeout 200 \ --worker-connections 1000 \ *.asgi:application This is phisical hosting with 8 cores CPU User CPU time 201678.567 ms System CPU time 224.307 ms Total CPU time 201902.874 ms TOTAAL TIME 202161.019 ms SQL 385 ms Trying change count of workers,threads,change from wsgi to asgi,but nothing help. -
Does deleting an image from a model delete it from the media folder?
I'm making a social networking website project to practice Django I am curious as to whether deleting an image from a model also deletes it from the media folder? For example, I have a field in my User model where a user can upload their profile picture. As standard, I save that profile picture in my media folder and a reference to that media folder is used by my model to load it. But, if the user wishes to delete that picture, I use User.profilepic.delete() to delete it Does that mean that the picture also gets deleted from the media folder or I have to handle that separately? I tried looking it up on the net but I couldn't find a direct answer. All of the articles talk about deleting the image from the DATABASE. But none from the folder. Thanks in advance. -
Django: object has no attribute 'cleaned_data'
my models.py is Like this: from django.db import models class Form(models.Model): first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.EmailField() date = models.DateField() occupation = models.CharField(max_length=80) # Magic Method def __str__(self): return f"{self.first_name}{self.last_name}" My forms.py is: And my views.py is: from django.shortcuts import render from .forms import ContactForm from .models import Form def index(request): # To fetch data from webpage if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): first_name = form.cleaned_data["fname"] last_name = form.cleaned_data["lname"] email = form.cleaned_data["email"] date = form.cleaned_data["date"] occupation = form.cleaned_data["occupation"] print(first_name) # To store in database Form.objects.create(first_name=first_name, last_name=last_name, email=email, date=date, occupation=occupation) return render(request, "index.html") And I am getting the following error: 'ContactForm' object has no attribute 'cleaned_data' In 'views.py' -- "if form.is_validate()" is returning "False"..and the following code is not executing. -
How to only display superusers in ManyToManyField field when creating an instance in admin page
We have this model: # models.py from django.conf import settings User = settings.AUTH_USER_MODEL class Category(models.Model): ... users = models.ManyToManyField(User, help_text='Choose Superusers only', blank=True) The questions is:when creating an instance in the admin page, how can I force the form to only display superusers in the multiple select? -
valid view function or pattern name error in django
I am learning django. My URL pattern is like below. path('task-delete/<int:pk>/', DeleteView.as_view(), name="tasks-delete"), I have class based view like below. class DeleteView(DeleteView): model = Task context_object_name = 'task' success_url = reverse_lazy('tasks') HTML code in template is like below. <a href="{% url 'task-delete' task.pk %}">Delete</a> My error is like below. How to fix this error ? -
Django Incorrectly sending image files to React Native frontend
I am coding my first react native project, although I just created one with django/react. In my first project I configured the react side to serve static files. I couldnt get this new project to serve them correctly so I copied word for word what I did in the last one and it is still incorrect. Format I get it in my React Native frontend is profilePicture : "/media/images/beserk.png" but it should be http://localhost:8000/media/images/beserk.png, or atleast thats what it looked like in my other project. Frontend does not display image, but does display local ones so the problem is 100% backend. Below are my relevant configurations: settings.py: STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') MEDIA_URL = '/media/' (static/media/images is in project directory) urls.py: urlpatterns = [ path('api/', include('backend.urls')), path('admin/', admin.site.urls), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model/serializer class UserProfile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) biography = models.CharField(max_length=255) public_name = models.CharField(max_length=30) user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/') friends = models.ManyToManyField('self', blank=True) description_tags = models.ForeignKey('Descriptor', null=True, blank=True, on_delete=models.PROTECT) def __str__(self): return str(self.user) class UserProfileSerializer(ModelSerializer): description_tags = DescriptorSerializer() class Meta: model = UserProfile fields = '__all__' def to_representation(self, instance): if self.context.get('list_view', False): return { 'id': … -
How do I upload data to html from a database?
I have a home project, DRF is deployed in it, the database itself is on postgresql and I learned how to create a page template, BUT without data from the database. That's how I did it.: $ mkdir static $ vim Project1/settings.py $ cat Project1/settings.py ... from pathlib import Path import os ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'portfolio', 'ckeditor', 'ckeditor_uploader', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'Project2')], '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', ], }, }, ] ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media/" ... $ mv Project2/css static/ $ ls static/ css $ vim Project2/index.html $ cat Project2/index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Project2</title> </head> <body> <!--SECTIONS--> <!--CARDS--> <section> <div class="container"> <div class="cards"> <div class="card__content" id=""> <h2 class="card_hidden" onclick="card__hidden(this)">Опыт работы</h2> <div style="text-align: left;"> <ul> <li><strong> ' . $row['begin'] . ' - ' . $row['finish'] . ':</strong> ' . … -
Django google oauth2.0, i want to implement profile creation for my web app using build in google ouath2
i want to implement profile creation for my web app using build in google ouath2, i try to override auth.user model and inheritence from there info and create my own columns.But smth i do wrong, can someone help me.I need inheritence auth data from auth.user for CustomUser how to do this. models.py from django.contrib.auth.models import AbstractUser from .choices import STATUS_CHOICES, HOBBY_CHOICES, GENDER_CHOICES from django.db import models class CustomUser(AbstractUser): email = models.EmailField(unique=True) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default='regular') hobby = models.CharField(max_length=200, choices=HOBBY_CHOICES) photo = models.ImageField(upload_to='profile_pics/', blank=True, null=True) city = models.CharField(max_length=100, blank=True) age = models.PositiveIntegerField(blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True) description = models.TextField(blank=True) groups = models.ManyToManyField( 'auth.Group', related_name='custom_user_groups', blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='custom_user_permissions', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', ) def __str__(self): return self.username CustomUserCreationModel.py from django import forms from django.core.exceptions import ValidationError from .models import CustomUser from .choices import HOBBY_CHOICES, GENDER_CHOICES class CustomUserCreationForm(forms.ModelForm): hobby = forms.ChoiceField( choices=HOBBY_CHOICES, widget=forms.Select(attrs={'class': 'custom-dropdown form-control', 'id': 'Hobby'}) ) photo = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-file-input'})) city = forms.CharField(widget=forms.TextInput(attrs={'class': 'custom-input'})) age = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'custom-input'})) gender = forms.ChoiceField( choices=GENDER_CHOICES, widget=forms.RadioSelect(attrs={'class': 'custom-radio'}) ) description = forms.CharField( widget=forms.Textarea(attrs={'class': 'custom-textarea'}) ) … -
django react project createAction not working
This is my actions.jsx: import { redirect } from "react-router-dom"; const URL = import.meta.env.VITE_BASE_URL; //Create Action export const createAction = async ({ request }) => { const formData = await request.formData(); const newBlog = { subject: formData.get("subject"), details: formData.get("details"), image_url: formData.get("image_url") } await fetch(`${URL}`,{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newBlog) }); return redirect("/"); } export async function updateAction({ request, params }) { const formData = await request.formData(); const id = params.id; const updatedBlog = { subject: formData.get("subject"), details: formData.get("details"), image: formData.get("image_url") } await fetch(`${URL}${id}/`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(updatedBlog) }); return redirect(`./`); } //Delete Action export const deleteAction = async ({params}) => { const id = params.id; await fetch(`${URL}${id}/`, { method: "DELETE" }); return redirect("/"); } This is my Index.jsx: import Blog from "../components/Blog" import { Form, useLoaderData } from "react-router-dom" import { useState } from "react" export default function Index(props) { const allBlogs=useLoaderData() const [image, setImage] = useState('app.logomakr.com/3EC6KR') const handleInputChange = (event) => { setImage(event.target.value) } return( <> <h1>Index</h1> <hr/> <h1>Add a Post</h1> <Form action="/create" method="post"> <label htmlFor="subject"> Title: <input type="text" subject="subject" id="subject"/> </label> <label htmlFor="details"> Write your post here: <input type="textarea" name="details" id="details"/> </label> <label htmlFor="image_url"> Image Link: <input type="text" …