Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate an unique id for each Component of initial value of useState()
I want to create 30 empty Taskcard components at the beginning of the state my problem is that each taskcard has import React from 'react' import { useEffect, useState } from 'react' import { getTasks } from '../api/task.api' import { TaskCard } from './TaskCard' export function TaskLists() { const [tasks, setTasks] = useState(Array(30).fill({id: 1, title: 'title', description: 'description'})) useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data) setTasks(res.data); } loadTasks(); },[]); const removeTask = (id) => { setTasks(tasks.filter(task => task.id !== id)); } return ( <div> {tasks.map((task) => ( <TaskCard key={task.id} task={task} onDelete={removeTask} /> ))} </div> ) } the same id how can I fix that? -
Is it possible to use variable in meta tag?
I am new at web dev. I am using Django, and I just wonder is it possible to use variable in meta description tag, Just like this: <meta name="description" content="{{blog_detail.context_1|slice:160|safe}}"> Will it still appear on search engines? -
Django: How to get an element from list by using index on templates?
This is my current code: {% for question in model.get_questions %} {% with counter=forloop.counter %} {{ question }} {{ model.get_fields.counter }} <br> {% endwith %} {% endfor %} When I only print counter it works, when I type any number instead of model.get_fields.counter but in this way that I do does not works. What should I do? -
How can i send data back to Vue/Quasar with Django?
Im currently working on a project that used a Django backend with a Vue/Qasar front ends. I am able to make a POST request to Django using CORS, but I cannot figure out how to send data back to the frontend. I have it so that each vue page makes a post request to say send login information to django. django takes the json format in the views.py page as a request and sends it to the database to call the users profile information. Once i get the data back i don't know how to target my front-end. Django is running on localhost:8000 while vue is running on localhost:9000.[python back end](https://i.stack.imgur.com/tBItJ.png) I tried looking if there is a way to issue an httpresponse or jsonresponse so that it takes in a parameter to a different url in this case localhost:9000, but can't find anything. I also tried to see if maybe the request carries information on the url making the request as to make a direct response, but my response is being sent to localhost:8000 instead. -
Problem with my state when deleting a component
Here is my api file: import axios from "axios"; const taskApi = axios.create({ baseURL: "http://localhost:8000/tareas/api/v1/tareas/", }); export const getTasks = () => taskApi.get("/"); export const createTask = (task) => taskApi.post("/", task); export const deleteTask = (id) => axios.delete(`http://localhost:8000/tareas/api/v1/tareas/${id}/`); now here is the component that displays all of my tasks: import React from 'react' import { useEffect, useState } from 'react' import { getTasks } from '../api/task.api' import { TaskCard } from './TaskCard' export function TaskLists() { const [tasks, setTasks] = useState([]) useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data) setTasks(res.data); } loadTasks(); },[]); return ( <div> {tasks.map((task) => ( <TaskCard key={task.id} task={task} /> ))} </div> ) } and here is my TaskCard component that is causing the error: import React, { useState } from 'react' import { deleteTask } from '../api/task.api' export function TaskCard({task}) { const [tasks, setTasks] = useState([]); const handleDelete = async (id) => { await deleteTask(id); setTasks(tasks.filter(task => task.id !== id)); } return ( <div> <h1>{task.title}</h1> <p>{task.description}</p> <hr/> <button onClick={() => handleDelete(task.id)}>Delete</button> </div> ) } I am getting the error : settle.js:19 Uncaught (in promise) When I press the delete button I want that the task card immediately gets deleted from the … -
Wagtail CheckConstraint, column live does not exists
I have such model from wagtail.models import Page class Article(Page): price = PositiveIntegerField( null=True, blank=True, ) class Meta: constraints = [ CheckConstraint(check=Q(price__gte=100) & Q(live=True), name="min price for published"), CheckConstraint(check=Q(price__lte=350000) & Q(live=True), name="max price for published"), ] After running makemigrations everything is fine. But when I try to execute it I got an error django.db.utils.ProgrammingError: column "live" does not exist How could that possible be? live column is part of Page. How this can be fixed? -
How to resolve Horn clause-like tag implications with Django and Postgres database
I am creating a content system with Django where users can create and publish content. Each document created by the user can have multiple tags. I am designing a tag implication system where some tags can imply the presence of other tags. For a simple example, assume "color" and "red" are tags. The following implication exists: "red" implies "color". When a user tags their document with "red", it also has a "color" tag added automatically. Implications are global and apply to every user and document. What I want to do is make tag implications more powerful, I would like to make it possible to require the presence of multiple tags to imply another tag, like a Horn clause. For example, I want an implication where the presence of "red" and "blue" implies the tag "multiple_colors". This could be written Horn clause-like: "red", "blue" -> "multiple_colors". Using Postgres and Django to implement tag implication resolution where only a single tag can imply a tag is simple to implement. You simply have a Django model: class Tag(Model): name = CharField() class TagImplication(Model): antecedent = ForeignKey(Tag) consequent = ForeignKey(Tag) To resolve all implied tags given a set of tags requires an iterative approach. … -
how to make the possibility of adding products to cart for anyone even for non authorized people
when i try to add the product to cart as guest i get this error: Page not found (404) No Session matches the given query. Request Method: POST Request URL: http://127.0.0.1:8000/store/la-fleur-fily-suvignuion/ Raised by: shop.views.Product Using the URLconf defined in lafleurlily.urls, Django tried these URL patterns, in this order: admin/ [name='home'] about/ [name='about_us'] near_me/ [name='find_near_me'] contact-us/ [name='contact_us'] store/ [name='all_products'] store/ category/wines/ [name='wine_category'] store/ category/sparkling/ [name='sparkling_category'] store/ <slug:wine_slug>/ [name='each_wine'] The current path, store/la-fleur-fily-suvignuion/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. orders/views.py: class CartPage(View): template = 'orders/cart.html' def get(self, request): session_key = request.session.session_key session = get_object_or_404(Session, session_key=session_key) cart = get_object_or_404(Cart, session=session) items = CartItem.objects.filter(cart_items=cart) def item_total(): summ = 0 for each in items: print(each.product.price, each.quantity) summ = summ + each.product.price * each.quantity return float(summ) context = { 'cart': cart, 'item': items, 'item_total': item_total() } return render(request, self.template, context) shop/views.py: class Product(View): #SubscribePost, template = 'shop/product.html' model = Wine def get(self, request, wine_slug): product = get_object_or_404(self.model, slug=wine_slug) context = {'wine': product} return render(request, self.template, context=context) def post(self, request, wine_slug): action = request.POST.get('action') if action == 'add_to_cart': return self.add_to_cart(request, wine_slug) def … -
Streaming not working when adding uwsgi in between python ngnix
I'm developing a chat application that streams messages, and it functions well when I access the UI directly through Django on my local environment. It also works when I have the following setup: Python server <-> Nginx However, when I introduce uWSGI into the configuration, the response streaming stops, and I receive the response all at once. I've tried various solutions, but none have resolved the issue. Can you provide guidance on how to correct this problem? Python server <-> uwsgi <-> Nginx Streaming should work as expected. I tried to reduce buffer but didnt work -
Django: Fields as list element in models
Actually I don't know if its possible but this is a rough example of what do I want its like, class ImAModel(models.Model): field_of_list_of_questions = (models.BooleanField(), models.BooleanField(), models.BooleanField()) I need this beacuse I will have a model that have a vary field. And also there may be a lot of fields in it. Then I want to call them like this val = model.field_of_lists_of_questions[1] It'll be very enjoying if it's possible. -
All channels in a group
I used redis as a channel layer in a project . Now i want to access all the channels in group . How can i achieve this without using database . I just want to iterate over group . CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [ # (REDIS_HOST, REDIS_PORT) , (os.getenv('REDIS_URL'), os.getenv('REDIS_PORT')), ], }, }, } Is it possible when redis is used as channel layer . -
CSRF cookie not set. Django auth
Here is my "login" function that I am using to authenticate users when they provide their credentials in NextJs website fronend: export const login = (username, email, password) => async dispatch => { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); console.log(csrftoken); const config = { headers: { 'Content-Type': 'application/json', } }; const config_two = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, } }; console.log(config_two) const body = JSON.stringify({ email, password }); const body_two = JSON.stringify({ username, password }); try { const res = await axios.post(`http://localhost:8000/auth/jwt/create/`, body, config); const res_two = await axios.post(`http://localhost:8000/api-token-auth/`, body_two, config_two); dispatch({ type: LOGIN_SUCCESS, payload: res.data }); dispatch(load_user()); toast.success("You are logged in"); } catch (err) { toast.error("Something went wrong"); dispatch({ type: LOGIN_FAIL }) } }; For one purpose I had to include another post request to get tokens from the database which are … -
Passing values from the forms from one view (one url) to another view (second url) in Django
So I have two forms, and a view which enables users to fill them: def input_view(request): if request.method =="POST": simulation_form = SimulationSettings(request.POST) strategy_form = StrategySettings(request.POST) if simulation_form.is_valid() and strategy_form.is_valid(): simulation_settings = simulation_form.cleaned_data strategy_settings = strategy_form.cleaned_data return render( request, "strategy_simulator/results_view.html", {"simulation_settings": simulation_settings, "strategy_settings": strategy_settings}, ) else: simulation_form = SimulationSettings() strategy_form = StrategySettings() return render( request, "strategy_simulator/input_view.html", {"simulation_form": simulation_form, "strategy_form": strategy_form}, ) With this code, it works and after submitting the forms results_view.html template is displayed properly, but the url does not change and I want results to be under different url. So I've created second view and url to it, but I do not know how to pass forms values from one view to another and then redirect to the url connected to the specific view (results_view in this case). Here is the view: def results_view(request): simulation_settings = request.POST.get('simulation_settings') strategy_settings = request.POST.get('strategy_settings') return render( request, "strategy_simulator/results_view.html", {"simulation_settings": simulation_settings, "strategy_settings": strategy_settings}, ) And here are urls: from . import views from django.urls import path app_name = "strategy_simulator" urlpatterns = [path("results/", views.results_view, name="results_view"),path("", views.input_view, name="input_view"), ] Thanks for help in advance. -
Affiliate marketing in django model
I have a django travel blog, now im looking to find a way to integrate extern city widgets and scripts from my associates inside my articles, what is the best option to do so? I tried in Django CkEditor from Richtextfield(model) in django admin inside scripts to insert the code provided from associated but it's not working at all. -
No module found [my_app] with Apache and mod_wsgi
This is my directory structure, in /var/www: team_django --team_db ---- __init__.py -----settings.py -----wsgi.py My wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'team_db.settings') application = get_wsgi_application() My /etc/apache2/mods-available/wsgi.load: LoadModule wsgi_module "/usr/local/py_ptracker/lib/python3.11/site-packages/mod_wsgi/server/mod_wsgi-py311.cpython-311-x86_64-linux-gnu.so" WSGIPythonHome "/usr/local/py_ptracker" My /etc/apache2/sites-available/vhost.conf: WSGIScriptAlias / /var/www/team_django/team_db/wsgi.py <Directory /var/www/team_django/team_db> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> The mod_wsgi is enabled, as the vhost configuration, and everything gets loaded fine. I get this in the error.log though: ModuleNotFoundError: No module named 'team_db' [wsgi:error] [pid 225277] mod_wsgi (pid=225277): Failed to exec Python script file '/var/www/team_django/team_db/wsgi.py'., referer: ... [wsgi:error] [pid 225277] mod_wsgi (pid=225277): Exception occurred processing WSGI script '/var/www/team_django/team_db/wsgi.py'., referer: .... Why isn't the os.environ.setdefault not finding team_db? I've checked all permisions and I also set everything to 777, changing owners and group to www-data or root and all that; to no avail. I can't understand why it's not finding the team_db. Te server runs correctly with Django's runserver and also with the mod_wsgi-express runserver. The mod_wsgi has been built with the same version of Python, within the virtual environment. -
Any Microsoft Dataverse database backend for Django?
I'd like to write a frontend for my Microsoft Dataverse database backend so as to manage Dataverse data easily. Django comes with an easy-to-configure admin which suits my needs fine. I would like to know if there has been any third-party backends for Dataverse already, or I just need to implement the backend by myself because few people care about using Dataverse as the backend for their Django Applications. Craving for your insights! -
how to post an image from react native to django
I'ive been trying to post an image file from react-native but i can't seem to get it right this is the code I tried: const pickImage = async () => { // No permissions request is necessary for launching the image library let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [4, 3], quality: 1, }); if (!result.canceled){ delete result.cancelled; setImage(result.assets[0].uri) } }; and this is the fetch request: const handleSubmit = (name, description, image, email, phone) => { let uri = image.replace("///", "//") var myHeaders = new Headers(); myHeaders.append("Authorization", `Bearer ${userInfo.access_token}`); myHeaders.append("Content-Type", "multipart/form-data"); var formdata = new FormData(); formdata.append("name", name); formdata.append("description", description); formdata.append("photo", uri, uri.split("/").pop()); formdata.append("phone", phone); formdata.append("email", email); var requestOptions = { method: 'POST', headers: myHeaders, body: formdata, redirect: 'follow' }; fetch(`${Url.base}/api/realtor/create-profile`, requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); } this is the error i keep getting: {"photo":["The submitted data was not a file. Check the encoding type on the form."]} -
I'm trying to create multiple user in Django using flags and a custom user model but keep getting something went wrong error
I have created my custom user model with the following code. class UserManager(BaseUserManager): def create_user(self, email, name, phone, password=None): if not email: raise ValueError("Users must have an email address") email = self.normalize_email(email) email = email.lower() user = self.model(email=email, name=name, phone=phone) user.set_password(password) user.save(using=self._db) return user def create_vendor(self, email, name, phone, password=None): user = self.create_user(email, name, phone, password) user.is_vendor = True user.save(using=self._db) return user def create_superuser(self, email, name, phone, password=None): user = self.create_user(email, name, phone, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, db_index=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=15, unique=True) otp = models.CharField( max_length=6, ) is_vendor = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name", "phone"] objects = UserManager() def __str__(self): return self.email I have also created my view and i don't know where the issue is in the following code also: class RegisterAPIView(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): try: data = request.data print(data) email = data["email"].lower() name = data["email"] phone = data["phone"] password = data["password"] re_password = data["re_password"] is_vendor = data["vendor"] if is_vendor == "True": is_vendor = True else: is_vendor = False if … -
django admin autocomplete filter without foreign key
I have this model: class Person(models.Model): first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) gender = models.CharField(choices=Gender.choices, null=True, blank=True) city = models.CharField(max_length=200, null=True, blank=True) I need autocomplete filter for "city" field https://github.com/farhan0581/django-admin-autocomplete-filter didnt do the job -
Django-React integration Django port does not actualize
I made changes to the src/app.js when I use npm start inside the react_app, in port 3000 changes and gets rendered but when I do that using python manage.py runserver I only see the default react-app welcome how can I fix that? views from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index') ] Heres is my react_app inside my django project here is the app.js import "./App.css"; function App() { return ( <div className="App"> <p>Calendar App</p> </div> ); } export default App; using python manage.py runserver: enter image description here using npm run inside react app: enter image description here -
Set initial data in Django Form forms.Select()
I want to set initial value for my staus field that is forms.Select() widget in django ModelForm but it does not work. I cant debug my code. My model form class is: class CRMFollowUpStatusLogForm(ModelForm): class Meta: model = CRMFollowUpStatusLog fields = ['status'] widgets = { "status": forms.Select() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) status_id = kwargs["data"]["followup"].current_status.id # status_id is correctly passed here self.fields['status'].initial = status_id status_id is correctly passed to init method. but self.fields['status'].initial = status_id does not work correctly. CRMFollowUpStatusLog is: class CRMFollowUpStatusLog(models.Model): status = models.ForeignKey( "CRMFollowUpStatus", related_name="follow_up_logs", on_delete=models.CASCADE ) follow_up = models.ForeignKey( "CRMFollowUp", related_name="status_logs", on_delete=models.CASCADE ) and CRMFollowUpStatus is: class CRMFollowUpStatus(models.Model): name = models.CharField(max_length=256, unique=True) status_id in init method of CRMFollowUpStatusLogForm is pk of CRMFollowUpStatus. -
Django is not accepting my nested for loop with double zip
In views.py I have: mylist1 = ["peru", "germany", "japan"] mylist2 = [["lima","cusco"], ["berlin","munich"], ["tokyo"]] mylist3 = [[1,2], [3,4], [5]] mylist = zip(mylist1, zip(mylist2, mylist3)) In templates for country, info in mylist: {{country}} for city, number in info: {{city}} {{number}} error: Need 2 values to unpack in for loop; got 1. I feel my double zip definition is not being accepted or properly read. any ideas on how to fix this: -
Flask AppBuilder add_registration function is not redirecting to activation page
I am using Flask AppBuilder to build a web application. I am having trouble with the add_registration() function. The function is sending the registration email successfully, but it is not redirecting to the activation page. Instead, it is redirecting to the index page. def add_registration(self, username, first_name, last_name, email, password=""): """ Add a registration request for the user. :rtype : RegisterUser """ print("first passed") register_user = self.appbuilder.sm.add_register_user( username, first_name, last_name, email, password ) print("second passed") if register_user: print("third passed") verification_code = self.send_email(register_user) if verification_code: print("fourth passed") flash(as_unicode(self.message), "info") verfication_info = ( f"{verification_code}/{username}/{first_name}/{last_name}/{email}/{password}" ) print("fifth passed ") # Redirect to activation page only if email was sent successfully. return redirect( url_for(".activation", _external=True, activation_hash=register_user.registration_hash) ) else: print("fith faild") flash(as_unicode(self.error_message), "danger") self.appbuilder.sm.del_register_user(register_user) # Redirect to index page if email failed to send. return redirect(self.appbuilder.get_url_for_index) even it is printing "fifth passed" to ensure if the email is sent -
What is wrong with this django view?
in this django view I'm trying to do the following: Check if there is a "chartentry" with today's date In that case, do not substitute the description with the new value, but just append it to the old value I can't for the life of me figure out why it is always repeating twice the new value (e.g. the description ends up as "newvalue;newvalue" instead of "oldvalue;newvalue" Help appreciated @login_required def chartentry_create(request, chart_id): obj = get_object_or_404(Chart, id=chart_id) todaysentry = obj.chartentries.filter( created_at__gte=timezone.now().replace(hour=0, minute=0, second=0), created_at__lte=timezone.now().replace(hour=23, minute=59, second=59), ).first() # if it's today's entry, append data to it instead of creating a new one if todaysentry: form = ChartEntryForm(request.POST, instance=todaysentry) else: form = ChartEntryForm(request.POST or None) if form.is_valid(): # if it's today's entry, append description if todaysentry: form.instance.description = ( todaysentry.description + ";" + request.POST["description"] ) form.instance.chart = obj form.save() messages.success(request, "Entry updated successfully") else: for error in form.errors: messages.error(request, form.errors[error]) if is_ajax(request): context = {"chart": obj} return render(request, "chart_entries_by_patient_partial.html", context) else: return redirect("chart-detail", patient_id=obj.patient.id) -
Could not find 'price' in DJ4E assignment
I've got a problem with DJ4E course by dr.Chuck. On Building Classified Ad Site #2 assignment my site can't pass a validation and checking form keeps throwing an error "Could not find 'price' The price field is missing on the create form - check the field_list in views.py" for URL http://meredan.pythonanywhere.com/ads/ad/create I have re-checked multiple times and can't find why this is raised, because price field is available in the UI and also present when I checked manually in a shell. I am not very experienced with Django, maybe I'm missing something, would appreciate any help. creation class in views.py class AdCreateView(LoginRequiredMixin, View): template_name = 'ads/ad_form.html' success_url = reverse_lazy('ads:all') def get(self, request, pk=None) : form = CreateForm() ctx = { 'form': form } return render(request, self.template_name, ctx) def post(self, request, pk=None) : form = CreateForm(request.POST, request.FILES or None) if not form.is_valid() : ctx = {'form' : form} return render(request, self.template_name, ctx) # Add owner to the model before saving ad = form.save(commit=False) ad.owner = self.request.user ad.save() return redirect(self.success_url) forms.py class CreateForm(forms.ModelForm): max_upload_limit = 2 * 1024 * 1024 max_upload_limit_text = naturalsize(max_upload_limit) picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text) upload_field_name = 'picture' class Meta: model = Ad fields = ['title', …