Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why I'm getting "Not Found: /api/v1.0/productos/${this.id_product}/"
I got a problem with vue.js. I made a CRUD, and got an issue trying to use PUT to update. when I applied this method to send update information to Django, an error appeared: METHOD IN VUE.JS methods: { onSubmit(evt){ evt.preventDefault() const path = 'http://127.0.0.1:8000/api/v1.0/productos/${this.id_product}/' axios.put(path, this.form).then((response) => { this.form.nombreProd = response.data.nombreProd this.form.precioProd = response.data.precioProd this.form.contenido = response.data.contenido this.form.descripcionProd = response.data.descripcionProd alert("Actualización exitosa") }) .catch((error) => { console.log(error) }) } ANSWER IN DJANGO Not Found: /api/v1.0/productos/${this.id_product}/ [02/Oct/2022 12:57:46] "PUT /api/v1.0/productos/$%7Bthis.id_product%7D/ HTTP/1.1" 404 2609 Trying to understand, I realized that it could be an issue with the curly braces, but I don´t know how to solve it -
Django: Nested Loop In Template
category = ['cat1','cat2','cat3'] inventory = CurrentInventory.objects.all() for cats in categories inventorybycat = inventory.filter(category =cats) setofinventories.append(inventorybycat) dictofstuff = [zip(setofinventories,categories)] context = { 'setofinventories':setofinventories 'category':category 'dictofstuff':dictofstuff } In views.py above this loop creates a list of objects per each category. In the template below this loop prints a filtered object list per every item in the category list. {% for inventory in setofinventories%} {% for item in inventory %} {{ item.category }} {{ item.productName }} {% endfor %} {% endfor %} The only thing I am missing is I do not now how to reference the category in the template. I pass the whole list in context, but {{category{{forloop.counter}}}} is not a valid statement. I would either like to use zip(category,setofinventories) to pass these two items together, or create a category model, filter by that model and then I can reference that model by item? If I zip these items dictofstuff = [zip(setofinventories,categories)] How do I reference the category in the template? {% for inventory in setofinventories%} {{categories{{[forloop.counter]}}}}#This line does not work {% for item in inventory %} {{ item.category }} {{ item.productName }} {% endfor %} {% endfor %} -
Poblem when updating a table using celery task: OperationalError
I use Celery task and got an error I do not understand. I loop over a table (that contain query definitions) to edit missing/inconsistent data in a database (using API) and registered discrepencies in another table. If I run query one at a time, it works but when I try to loop over queries, I got an error OperationalError('server closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\n') def DCF_edition(self): DCF_BEFORE_UPDATE = pd.DataFrame.from_records(DataCorrectionForm.objects.all().values()) DCF_BEFORE_UPDATE = DCF_BEFORE_UPDATE.astype({'record_date': str,'created_date': str}) if not DCF_BEFORE_UPDATE.empty else DCF_BEFORE_UPDATE data = [] # load queries definition queries = queries_definitions() if not queries.empty: for index, row in queries.iterrows(): try: missing_or_inconsistent = missing_or_inconsistent_data(row['ide'],row['query_type'],row['crf_name'].lower(),row['crf identification data.append(missing_or_inconsistent[['dcf_ide','category','crf','crf_ide','pat','record_date','field_name','field_label','message','field_value','dcf_status','DEF','deactivated']]) DCF_AFTER_UPDATE = pd.concat(data) DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.drop_duplicates(keep='last') DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.drop(['DEF'], axis=1) DCF_AFTER_UPDATE.rename(columns = {'pat':'patient',}, inplace = True) except Exception as e: Log.objects.create(dcf_edition_status=0,dcf_edition_exception=str(e)[:200]) continue # Cast date into string format to be able to dumps data DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.astype({'record_date': str}) if not DCF_AFTER_UPDATE.empty else DCF_AFTER_UPDATE records = json.loads(json.dumps(list(DCF_AFTER_UPDATE.T.to_dict().values()))) for record in records: if not DCF_BEFORE_UPDATE.empty and record['dcf_ide'] in DCF_BEFORE_UPDATE.values: DataCorrectionForm.objects.filter(dcf_ide=record['dcf_ide']).update(dcf_status=2) else: DataCorrectionForm.objects.get_or_create(**record) # resolved dcf => status=0 if not DCF_BEFORE_UPDATE.empty: records = json.loads(json.dumps(list(DCF_BEFORE_UPDATE.T.to_dict().values()))) for record in records: if record['dcf_ide'] not in DCF_AFTER_UPDATE.values: DataCorrectionForm.objects.filter(dcf_ide=record['dcf_ide']).update(dcf_status=0) Log.objects.create(dcf_edition_status=1) return True -
request not sent from other device in the same network in reactjs/nextjs and django back-end
I have Reactjs and Nextjs front-end and Django backend my laptop IP is: xx.xx.xx.xx I run Django on loopback IP my requests do not send when I connect my front-end with another device with my laptop IP These two devises are in the same network no logs in laptop browser and backend logger -
Django Website Http Error 405; Method Not Allowed (POST): /dashboard/
I am trying to access my 'dashboard' page after signing in on the 'login' page in Django. The url in is throwing http error 405. If I replace the url with another page (eg: 'dbtable') it works absolutely fine. Below is my code in django: urls.py: urlpatterns = [ path('',views.register_login, name='login'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('dbtable/', views.DBTableView, name = 'dbtable'), ] views.py (includes login view and dashboard view): def register_login(request): form = UserCreationForm() if "register" in request.method == 'POST': form = UserCreationForm(request.POST) == "Register" if form.is_valid(): form.save() user = form.cleaned_data['username'] messages.success(request,"Account was Created for " + user) context = {'form':form} return render(request,'login.html',context) if "login" in request.method == "POST": if request.POST['submit'] == 'Login': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request,user) return redirect('login') else: messages.error(request, 'Wrong Username or password') context = {} return render(request,'login.html',context) class DashboardPageView(TemplateView): template_name = 'dashboard.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(DashboardPageView, self).get_context_data(**kwargs) context['plot'] = plot1.cumulative_plot() return context login.html: <!-- SIGN IN --> <div class="col align-items-center flex-col sign-in"> <div class="form-wrapper align-items-center"> <div class="form sign-in"> <div class="input-group"> <form action = "{% url 'dashboard' %}" method="POST" name="login" value="login"> {% csrf_token %} <i … -
string list as a parameter in url in django
i am working in a search view which take two inputs as a filter : search word 2.cities (multi select) i did it using serializer and it worked but paggination does not work because it was a post method , so i'm trying to take these inputs from url parameters , i tried this pattern : path(r"search/<str:search>/(?P<city>\w*)/", SearchView.as_view({"get": "search"}), name="search"), but when i browse : http://127.0.0.1:8000/company/search/taxi/montrial/ it return Not Found: /company/search/ so how to pass the paramteres or is there another way to use paggination with post method -
Send mail using email from user database in django
In Django how can i send email to user by importing email from user database. from django.contrib.auth.models import User class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = AdsForm def form_valid(self, form): email = User.email # try to import email from user model database. subject = 'Thanks for adding your trip' message = f'Hi {email}, thank you for Adding your Trip .' email_from = 'xyz@gmail.com' recipient_list = [email] send_mail(subject, message, email_from, recipient_list, fail_silently=False) form.instance.author = self.request.user return super().form_valid(form) In this form i tried to send email to the user that adding trip, the email i tried to pickup from User database. And i get this error while sending the mail. Help would be appreciated as Iam beginner to Django and programming. -
How to delete a specific Django cache by the name of the cache fragment?
Let's assume I don't want to clear the whole cache, but only a specific fragment. I have this in my template: {% cache 500 sidebar %} .. sidebar .. {% endcache %} I know about cache.delete(key), but how can I find the key based on the cache fragment name "sidebar"? I'm using FileBasedCache cache. When I used Redis Cache, there was keys() method which allowed to find the key based on a name pattern, but it doesn't work with FileBasedCache. -
My model form is not showing in the browser. It only appear after I click the submit button as a required field to be filled
My model form is not showing in the browser. It only appear after I click the submit button as a required field to be filled. I have searched similar problems but the context was just a little different and the fixes couldn't work on my project. My models from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Post(models.Model): body = models.TextField() date = models.DateTimeField(auto_now_add = True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author", default=None) def __str__(self): return f"{self.body} by {self.author} at {self.date}" Forms.py from django import forms from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ['body'] widgets = { "body": forms.Textarea(attrs={'class': 'form-control col-md-5 col-lg-6'}), } Views.py def create_post(request): posted = False if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return HttpResponseRedirect("/create_post?posted=True") else: form = PostForm() if "posted" in request.GET: posted = True return render(request, "network/create_post.html", { "form": form, "posted": posted }) Urls from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create_post", views.create_post, name="create_post"), path("create_post_page", views.create_post_page, name="create_post_page") ] The template {% extends "network/layout.html" %} {% block body %} … -
django Broken pipe from ('127.0.0.1', 49903)
enter code hereI got this error when I passed an id in the URL. Please check my below code. href url urls from django.contrib import admin from django.urls import path from he_admin import views app_name='he_admin' urlpatterns = [ path('',views.index,name='index'), path('addproductscategory',views.add_products_category,name='addcategory'), path('showcategories',views.ShowCategory,name='showcategories'), path('view/int:pk',views.ViewCategory,name='viewcategory'), ] view function def ViewCategory(request, pk): try: category=ProductCategory.objects.get(id=pk) except: raise Http404('category does not exist') return render(request,"viewcategory.html",{"category":category}) error -
Django static files get from wrong url
I am migrating an old Django 2.2 project to Django 3.2. I use AWS Cloudfront and S3. I have done most of the tasks to do. But i have something weird in my static files serving. When 'static' template tag is called, the rendered url is "https//<cloudfront_url>/static.." instead of "https://<cloudfront_url>/static..". The comma disapears ! It obviously results to a 404 not found. It worked without any problem on Django2.2. So for the moment i dirty patched this by doing a '.replace("https//", "https://")' on django static template tag. My settings relatives to static files are : # settings.py STATICFILES_LOCATION = 'static' AWS_CLOUDFRONT_DOMAIN = <idcloudfront>.cloudfront.net STATICFILES_STORAGE = 'app.custom_storages.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_CLOUDFRONT_DOMAIN, STATICFILES_LOCATION) AWS_STORAGE_STATIC_BUCKET_NAME = 'assets' # app.custom_storages.py class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION bucket_name = settings.AWS_STORAGE_STATIC_BUCKET_NAME def __init__(self, *args, **kwargs): kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN super(StaticStorage, self).__init__(*args, **kwargs)``` -
User uploaded images not serve after debug=false in django?
install whitenoise urls.py setting urlpatterns += static(settings.STATIC_URL, document_root = STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = MEDIA_ROOT) urlpatterns += [re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }), ] also configure static root and static url in settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / '/static/images/' STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))] -
How to run python scripts on button click in React?
I don't know how to run .py file on clicking a button in ReactJS . All i want is to fetch the data created by the .py file using flask on clicking a button in React application . I set up a link on that button which will redirect to another webpage on which i want to display that fetched data. The React app and the .py file are on the same machine. I have no idea on how to do this . My app.js file in React app runs on "http://localhost:3000" const onClickHandler = () => { //fetching the data from the server localhost:5000/page_name const url = "http://localhost:5000/user"; const [name, setName] = useState(""); const [password, setPassword] = useState(""); try { const res = await fetch(url); const data = await res.json(); console.log(data); setName(data.name); setPassword(data.password); } catch (error) { console.log(error); } }; return( <div> <button onClick={onClickHandler}>Click me</button> {name} {password} </div> ); My .py file runs on "http://localhost:5000/my_link" from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/data',methods=['GET', 'POST']) def my_link(): print("I got Clicked") return {'name': "geek", "password": "This is PWD"} if __name__ == '__main__': app.run(debug=True) Please help me with this . Thanks in advance . -
How to pass a string to a django url path through a hyperlink
I am creating a Django website that shows overwatch maps for strategic purposes. I have created a page that shows all the maps. Each map is wrapped in a hyperlink that is supposed to dynamically display information about that map. <div id="item"> <a href="{% url 'overwatch:maps/blizzard' %}"> <img src="{% static 'pics/blizzard-world.jpg' %}" alt="Blizzard World" /> </a> </div> When you click on the map picture I want the url to send a string to the url path: app_name = "overwatch" path('maps/<str:mapName>', views.mapStrategies, name='maps/<str:mapName>'), After that this view is supposed to be rendered. def mapStrategies(request, mapName): return render(request, "overwatch/maps/mapStrategies.html", { "mapName": mapName }) The url pattern is not recognized when the map is clicked on. However I can type in the url and it works just fine. -
'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128) Django
I only include this to the middleware. 'django.middleware.locale.LocaleMiddleware' And the middleware is: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', # new 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'django.middleware.locale.LocaleMiddleware', #This middleware is used to determine the current language based on the request data. ] But it throws the error 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128) Lots of people said Django is very easy and handy. But in my opinion of view, it's not an ameture framework. Strange bugs always happen and it really waste programmer's time. The docs are really tedious and bothering. So confused to continue or not... -
I want like button to make a function multiple on clicking multiple times without refreshing the page
I'm working on a network website(like twitter) using django and javascript. I want to make a like button for each post that upon clicking, it saves in the database that the user liked the post and it changes its inner content to('liked') and the classname and vice versa. The problem that this work but only on clicking on the button first time only not multiple times and I need to refresh the page to make the function works again. The problem is in the javascript code but I will add the html page and the python code(views.py) to make it more obvious. javascript code: document.addEventListener('DOMContentLoaded',function(){ window.addEventListener('load', function(){ document.querySelector('#likesdiv').querySelectorAll('button').forEach(input =>{ console.log('sl') let like__btn = true; if (input.value == 'like__btn'){ like__btn = true; console.log('like') } else { like__btn = false; console.log('liked') } input.addEventListener('click', function(){ if (like__btn){ console.log('clicked'); console.log(input.id); fetch('/like/' + input.id , { method:'PUT', body: JSON.stringify({ like: true }) }) input.innerHTML = ' <span id="icon"><i class="fa-regular fa-thumbs-up"></i></span>liked' input.classList.remove('like__btn') input.classList.add('liked__btn') input.value = 'liked__btn' console.log('changed') } else { console.log('clicked'); console.log(input.id); fetch('/like/' + input.id , { method:'PUT', body: JSON.stringify({ notlike: true })}) input.innerHTML = ' <span id="icon"><i class="fa-regular fa-thumbs-up"></i></span>like' input.classList.remove('liked__btn') input.classList.add('like__btn') input.value = 'like__btn' console.log('unchan') } } )}) }) }) in html page: <div id="likesdiv"> … -
Django UniqueConstraint returns error after adding modifying by adding a field to it
I have UniqueConstraint on a model and realized I needed to add one more field (field3) to prevent double entries but when I did that and I run python manage.py makemigrations it works fine but python manage.py migrate returns the error below: django.db.utils.OperationalError: (1553, "Cannot drop index 'bulk_fee_amount_key': needed in a foreign key constraint") The initial unique constraint is models.UniqueConstraint(fields=['field1', 'field2'], name='special_key') The new updated unique constraint is models.UniqueConstraint(fields=['field1', 'field2', 'field3'], name='special_key') But I get the error above when I try applying the migration. I use MySQL as my database management system. -
making an app using python with django library but the server not responding
i have installed django using command prompt and do coding on visual studio code by installing python. it is showing the django installed successfully but after the project setup , it does not show any kind of output . instead it is showing ' this site can't be reached . server refused to connect.' -
How to correctly output an image to the template in Django?
The image of the page is not displayed. Most likely I am incorrectly specifying the path to the image file. Please tell me what I should fix in my code? Code in the template <main> {% block content %} <p> <img src="../outputs/imgoutputs/14.jpg" width="189" height="255" alt="lorem"> </p> {% endblock %} </main> Approximate project structure: project -generate(app) -views.py -outputs -imgoutputs -14.jpg -templates -thankyou.html Help me please to correctly specify the path to the image. -
Can we connect sqflite and django in flutter?
With flutter I am using sqflite package for my reminder feature where user will be able to create a reminder, and I am using django for my other backend tasks, now the problem is, there will multiple users in an app and each user will have their own user_id and password to login into the app (the users are created from django) and since reminder feature will use sqflite package to store the user data it can't differentiate between users, meaning: if user "A" logged into the app and created a reminder and then user "B" logged into the app then he will also see the reminder created by user "A", user "B" will be able to see only the reminders set by user "A" not other personal data of user A which are coming from django server. So is there any way that I can make the reminder only visible to that particular users who created them ? or any way I can connect my sqflite package with my django?? -
Could someone check out my code error please?
Hello, could someone take a look at my code please? My login button return NONE and I am lost with it since 2 days. The views: def login_view(request, *args, **kwargs): context = {} user = request.user if user.is_authenticated: return redirect("index") destination = get_redirect_if_exists(request) print("destination: " + str(destination)) if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) if destination: # si destination n'est None return redirect(destination) return redirect("index") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, "login.html", context) def get_redirect_if_exists(request): redirect = None if request.GET: if request.GET.get("next"): redirect = str(request.GET.get("next")) return redirect The root_urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include("vazimba.urls")), path('account/', include("account.urls")), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) The_app_urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from .views import register_view, login_view, logout_view urlpatterns = [ path('login/', login_view, name="login"), path('logout/', logout_view, name="logout"), path('register/', register_view, name="register"), The templates: ==> account(the app) => templates/account/login.html {% if user.is_authenticated %} # html code----- {% else %} <div class="container"> <h1>home page</h1> <h2>Vous vous … -
Django relations sqlite
in my models i have a problem. Using Types model i want to take the costs from Outgo. I cant do this other way, mayby you know how to take it and display in template? class Types(models.Model): name = models.CharField(max_length=50, unique=True) class Outgo(models.Model): name = models.CharField(max_length=50) cost= models.DecimalField(max_digits=9, decimal_places=3) date = models.DateField(default=datetime.date.today) types= models.ForeignKey(Types,null=True, blank=True) -
Django - authenticate always returns None
I'm trying to create a login form for my website, but I cannot log into any existing account. def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'User does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Invalid username/password') context = {} return render(request, 'base/login_register.html', context) Even if I use the correct credentials, it will display: User does not exist Invalid username/password I've also added this to my settings.py: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) I've created those accounts manually from the Django admin account, not with a registration form, could this be the issue? -
Django DRF - Manually validate CSRF token
I read in the docs that DRF only validates CSRF tokens on authenticated requests and login views should explicitely check the CSRF token. Problem is, how does one manually check the CSRF token? In my settings.py: MIDDLEWARE = [ ... "django.middleware.csrf.CsrfViewMiddleware", ... ] Here's my view: from rest_framework.decorators import api_view from django.http import JsonResponse from django.views.decorators.csrf import get_token # I have to manually generate the csrf token and put it in the response body, because I use react-native and that can't read the token from the 'Set-Cookie' header @api_view(["GET"]) def user_info(request): return JsonResponse({"csrf_token": get_token(request)}) @api_view(["POST"]) def login(request): return JsonResponse({"foo": "bar"}) When I make a POST request in the frontend and I don't provide the CSRF token, it should fail, but I actually receive the {"foo": "bar"} JSON. I tried the @csrf_protect and @requires_csrf_token decorators, but the request is still not failing. I also tried this, but that errors on required positional argument: 'get_response CsrfViewMiddleware().process_request(request) If I pass a function to get_response, that function is never called: def test_get_response(req): breakpoint() CsrfViewMiddleware(get_response=test_get_response).process_request(request) I checked that the CSRF token is not passed in the headers, not the cookies, and I tried different browsers and incognito mode. How do I get my api requests … -
Page not reloading on targeted elements except the first session
I'm working on an e-commerce store, it has a cart page where there are quantity increase and decrease buttons for every product added to the cart, I'm trying to reload the page every time someone hits any of these buttons. So when I have only one product in the cart, the reloading works fine when clicking on the buttons, but when I have more than one product in the cart and I try to increase or decrease the quantity of the second or the third product, it doesn't reload. It seems reloading only works with the first product that has been added, any clue why this is happening? I'm guessing this has something to do with DOM, but how do I fix this? {% for item in items %} <div class="quantity"> <p id="quantity-style" class="quantity-style">{{item.quantity}}</p> <div class="quantity-arrows"> <img data-product="{{item.product.id}}" id="reload_arrow_up" data-action="add" src="{% static 'shop/images/arrow-up.png' %}"> <img data-product="{{item.product.id}}" id="reload_arrow_down" data-action="remove" src="{% static 'shop/images/arrow-down.png' %}"> </div> </div> {% endfor %} $('#reload_arrow_down').click(function() { location.reload(); }); $('#reload_arrow_up').click(function() { location.reload(); });