Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting 'No field found in Account with column name ""' when creating data for project using django-multitenant library
I'm trying to create a data migration script to insert initial data I have a migration file as below Account = apps.get_model("quickstart", "Account") Account.objects.using(db_alias).bulk_create([ Account(name="johndoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="USA")), Account(name="jilldoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="USA")), Account(name="milldoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="USA")), Account(name="velidoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="Turkiye")), Account(name="alidoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="Turkiye")), Account(name="pierredoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="France")), ]) When I execute ./manage migrate I got the error below Traceback (most recent call last): File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/manage.py", line 22, in \<module\> main() File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(\*args, \*\*cmd_options) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(\*args, \*\*options) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(\*args, \*\*kwargs) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self.\_migrate_all_forwards( File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in \_migrate_all_forwards state = self.apply_migration( File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards self.code(from_state.apps, schema_editor) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/tutorial/quickstart/migrations/0002_initial_data.py", line 95, in forwards_func TenantNotIdModel(tenant_column=1, name="TenantNotIdModel 1"), File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django_multitenant/mixins.py", line 58, in __init__ super(TenantModelMixin, self).__init__(\*args, \*\*kwargs) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/models/base.py", line 470, in __init__ self.\_state = ModelState() File … -
Django redirecting
I can't figure out why my redirection after paying doesn't work. I'm trying to display the thank_you template once the user has paid via Paypal. My code all works other than the final render of the thank_you template (I receive the email and see the 'Made it' print statement). Urls: from django.urls import path from . import views app_name = 'checkout' urlpatterns = [ path('', views.checkout, name='checkout'), path('thank_you', views.thank_you, name='thank_you'), path('order_success', views.order_success, name='order_success'), ] Views.py: import json from django.shortcuts import render, redirect, reverse, HttpResponseRedirect from django.http import JsonResponse from django.contrib import messages from django.urls import reverse from profiles.models import UserProfile from products.models import Product from django.views.decorators.http import require_POST from .models import Order, OrderDetail from django.core.mail import send_mail from the_rescuers.settings import DEFAULT_FROM_EMAIL from templated_email import send_templated_mail from .forms import OrderForm def checkout(request): bag = request.session.get('bag', {}) if not bag: messages.error(request, "There's nothing in your bag at the moment") return redirect(reverse('products:products_list')) order_form = OrderForm() bag_products = [] for item_id, quantity in bag.items(): product = Product.objects.get(pk=item_id) name = product.name id = product.id bag_products.append({'name': name, 'id': id, 'quantity': quantity}) bag_products = json.dumps(bag_products) # Attempt to prefill the form with any info the user maintains in # their profile if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order_form … -
Why my base.html page not showing in my website, only showing the code like{% extends 'base.html' %}
enter image description herethis is index.html page enter image description here Why the code showing -
Using Django ChoiceField gives a Value Error
I try to create dynamic choice. I fill choices with unit_list. Data to unit_list loading from API (units). I set the choices dynamicly in the constructor. But when I try to save a new form, it gives 'value error'. Have a nice day. class Announcement(models.Model): title = models.CharField(max_length=200, verbose_name=_('İlan Başlığı')) unit = models.IntegerField(null=True,blank=True) def announcement_new(request): response = requests.get('http://127.0.0.1:8001/api/units/list/') units = response.json() unit_list=[] for unit in units: unit_list.append(((int(unit.get('id'))), str(unit.get('name')))) ann_form = AnnouncementForm(unit_list) if request.method == 'POST': ann_form = AnnouncementForm( request.POST) if ann_form.is_valid(): ann_instance = ann_form.save(commit=False) ann_instance.save() return redirect('ann') else: print('Hata: ',ann_form.errors) else: context = { 'ann_form':ann_form, } return render(request,'pages/ann/ann_new.html',context) class AnnouncementForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "", })) unit = forms.ChoiceField( required=False, widget=forms.Select(attrs={ "class": "form-control form-select select2", }),) def __init__(self, unit_list, *args, **kwargs): super(AnnouncementForm, self).__init__(*args, **kwargs) self.fields['unit'].choices = unit_list class Meta: model = Announcement fields = "__all__" -
The view users.views.view didn't return an HttpResponse object. It returned None instead
I'm making a to-do list web with my friend. So, I have created the register function with email authentication, and it works fin. I pushed it to the GitHub and my friend pulled it and tried it in his laptop. But when he clicks "register" he got this error The view users.views.view didn't return an HttpResponse object. It returned None instead. We literally have the same code since he pulled the code from my repository, we both user virtual environment, installing from the same requirements.txt, and we both uses WSL2. This is the code views.py class UserRegister(CreateView): form_class = UserRegisterForm template_name = 'users/form_register.html' redirect_authenticated_user = True success_url = reverse_lazy('tasks') # Forbid logged in user to enter register page def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('tasks') return super(UserRegister, self).get(*args, **kwargs) # Send email verification def post(self, request, *args, **kwargs): form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your account' message = render_to_string('users/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('login') else: form = UserRegisterForm() form_register.html -- Register --> <section> <div class="register-card"> <h2>Register for an account</h2> <form method="POST"> {% csrf_token %} <div class="txt_field"> <input type="text" … -
AttributeError at /register/ 'User' object has no attribute 'is_authenticed --- when i check user is auth
i want create function when user is authenticed -- redirect to home but is not authenticed show page register +++ in views from django.shortcuts import render, redirect from .models import customer from .forms import customer_form from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate from django.contrib.auth import login as login_auth from django.contrib.auth import logout from django.contrib.auth.decorators import login_required def register(request): if request.user.is_authenticed(): return redirect('/') else: form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form' : form} return render(request, 'register.html', context) +++ path from django.urls import path from . import views path('register/', views.register, name="register"), i want create function when user is authenticed -- redirect to home but is not authenticed show page register -
django.db.utils.IntegrityError: and django.db.utils.OperationalError:
raise IntegrityError( django.db.utils.IntegrityError: The row in table 'hazeapp_orderitem' with primary key '1' has an invalid foreign key: hazeapp_orderitem.product_id contains a value '5' that does not have a corresponding value in hazeapp_newarrival.id. django.db.utils.OperationalError: no such column: hazeapp_orderitem.collection_id class NewArrival(models.Model): name = models.CharField(max_length=200, null=False, blank=True) price = models.FloatField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Collection(models.Model): name = models.CharField(max_length=200, null=False, blank=True) price = models.FloatField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): collection = models.ForeignKey(Collection, on_delete=models.SET_NULL, blank=True, null=True) newarrival = models.ForeignKey(NewArrival, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = 0 if self.collection: total += self.collection.price * self.quantity if self.newarrival: total += self.newarrival.price * self.quantity return total -
how to solve Import error for zinnia package for django v 3.2 and python 3.8(python_2_unicode_compatible import for zinnia v 0.20)?
trying to add zinnia to my django project django 3.2 python 3.8 zinnia 0.20 but shows File "/home/sayone/Documents/learning/virtuals/fastkart/lib/python3.8/site-packages/zinnia/models/init.py", line 2, in from zinnia.models.author import Author File "/home/sayone/Documents/learning/virtuals/fastkart/lib/python3.8/site-packages/zinnia/models/author.py", line 6, in from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (/home/sayone/Documents/learning/virtuals/fastkart/lib/python3.8/site-packages/django/utils/encoding.py) is there any other version of zinnia supporting django 3.2. -
'method' object is not subscriptable, usando request.GET en django [closed]
estoy viendo un tutorial de Django soy bastante nuevo en esto, por lo que no entiendo porque me sale ese error, no sé si quizá sea la versión de Django ya que el tutorial es de 2021. Help me !!! **Este es el formulario, nada tan complicado: ** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/buscar/" method="GET"> <input type="text" name="prd"> <input type="submit" value="Buscar"> </form> </body> </html> Este es mi view: def buscar(request): if request.GET["prd"]: #mensaje = "Articulo buscado: %r " %request.GET['prd'] product = request.GET["prd"] art = Articulo.objects.filter(nombre__icontains=product) return render(request, "resultado_busqueda.html", {"art":art, "query":product}) else: mensaje = "No escribio nada" return HttpResponse(mensaje) -
How to make an attribute read-only in serializers in DRF?
I have a serializer. class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass My model class is: class MyClass(models.Model): employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want employee attribute to be read-only and should only show this value in it's field: employee = Employee.objects.get(user=self.request.user) How can I do this in serializers? -
Problem to run python commands in Pycharm
I am trying to run the server in my Django project, but I found this problem, I just look my envirol path, it is all ok. Run my server, and all the Python commands. -
django- how can login page with Custom User without UserCreationForm?
models.py class CustomUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() username = models.CharField(max_length=30) email = models.EmailField(max_length=100) password = models.CharField(max_length=100) fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) forms.py class pal1Form(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta(): model=CustomUser fields=['username','email','password'] def save(self): user = super().save(commit=False) user.is_student = True user.save() return user class palForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model=palabout fields =['username','password','email','fname','lname','dob','gender','profileImage'] views.py from .forms import palForm,pal1Form def add_form(request): form = palForm(request.POST, request.FILES) form1=pal1Form(request.POST) if request.method == "POST": form = palForm(request.POST , request.FILES) form1=pal1Form(request.POST) if form.is_valid() and form1.is_valid() : try: form.save() form1.save() messages.success(request,"Successfully Added") return render(request,"home.html") except: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html",context={"form":form}) else: form=palForm() form=pal1Form() return render (request,"home/pal-form.html",context={"form":form,"form1":form1}) def login(request): form=pal1Form(request.POST) if request.method == 'POST': form=pal1Form(request.POST) if form.is_valid(): user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password'], ) if user is not None: login(request, user) return redirect("menu") else: messages.error(request,"Invalid username or password.") return redirect(login") return render( request, 'login.html', context={'form': form}) I'm trying a lot login page with multiple user page but login is not open so How can i login in custom user page? What was the problem? Can anyone help me? -
Integrate Sphinx documentation in Django
I've created the documentation for a webpage using Sphinx. The index.html generated via Sphinx is saved in a html folder. I'm not sure how to integrate the index.html and display on webpage content from Django. Currently, a link has been provided and it redirects to the documentation page. I would like to know how to display the page directly. For example, -
Console error 'Uncaught ReferenceError: React is not defined' when using Rollup.js + React 18
I am getting this console error in the Chrome browser index.tsx:13 Uncaught ReferenceError: React is not defined at index.tsx:13:2 I am really struggling to figure out how to get Rollup.js to work with React. I've been able to write a good-sized app in pure js using Rollup.js, but I want to start using React with it now. I'm not sure how to resolve this issue ; the code simply won't run in the browser yet I have no compilation issues. I've done much searching on this topic and none of the suggestions work. Any help would be appreciated! I am compiling to bundle.js using rollup -c -w The output from rollup is rollup v3.6.0 bundles src/ts/index.tsx → resources/public/js/bundle.js... LiveReload enabled created resources/public/js/bundle.js in 1.1s [2023-01-24 01:11:33] waiting for changes... My rollup.config.js looks like import typescript from '@rollup/plugin-typescript'; import { nodeResolve } from '@rollup/plugin-node-resolve'; import livereload from 'rollup-plugin-livereload'; import babel from '@rollup/plugin-babel'; export default { input: 'src/ts/index.tsx', output: { file: 'resources/public/js/bundle.js', format: 'iife', sourcemap: 'inline', inlineDynamicImports: true, globals: { "react/jsx-runtime":"jsxRuntime", "react-dom/client":"ReactDOM", "react":"React"}, }, external: [ 'react', 'react/jsx-runtime','react-is', 'react-dom/client','react-dom'], watch: true, plugins: [typescript(), nodeResolve(), livereload(), babel({ babelHelpers: "bundled", exclude: 'node_modules/**', presets: [ ["@babel/preset-react", {"runtime": "automatic"}] ] })] }; My tsconfig.js { "compilerOptions": … -
Is there any way I can delete all the rows from database before altering the model in django?
I want to alter my model but before doing so I want to delete all the records from my database, is there any dajngo ORM query for doing that cuz I don't want to do it manually. Thanks. I tried to alter my model but when I migrated the changes an error occured. it was a long error but the last line was this. File "C:\\Users\\ALI SHANAWER.virtualenvs\\PiikFM-App-Backend-O_dKS6jY\\Lib\\site-packages\\MySQLdb\\connections.py", line 254, in query \_mysql.connection.query(self, query) django.db.utils.OperationalError: (3140, 'Invalid JSON text: "Invalid value." at position 0 in value for column '#sql-45_2d01.qbo_class'.') any one knows what this is? -
Child form instance in Django
As a beginner in a contact list project I could not pass the instance of the contact profiles to the phone list form. When I want to add several phone numbers to a person I need the person's instance to be loaded to the add-phone form. models.py class newuser(forms.ModelForm): class Meta: model= contact_names fields='__all__' class newphone(forms.ModelForm): class Meta: model=contact_phone fields=['person','typep','phone'] views.py def user(request): form=newuser() if request.method =='POST': form=newuser(request.POST) if form.is_valid(): form.save(commit=True) return redirect('contacts') return render(request,'apptwo/form_page.html',{'form':form}) def addphone(request,pk): ps=contact_names.objects.get(id=pk) form=newphone(instance=ps) if request.method =='POST': form=newphone(request.POST) if form.is_valid(): form.save(commit=True) return redirect('contacts') return render(request,'apptwo/form_page2.html',{'form':form}) forms.py class newuser(forms.ModelForm): class Meta: model= contact_names fields='__all__' class newphone(forms.ModelForm): class Meta: model=contact_phone fields=['person','typep','phone'] -
how to insert daily average of a column into another column of another table(postgresql)
I have a machine that sends data every 3 minutes and i store that in a table called "machine_data" in postgresql. i need to get 10 minutes ,hourly,daily, monthly and yearly average of data column and store that in another table with columns of ( 10minutes_avg,hourly_avg ,daily_avg , ...) for these periodic tasks i wanted to use pgagent in postgresql but i didn't know how to write the code. note1: i have datetime field(2023-01-01 9:42:10+3:30) note2: additional note: i use django for getting and storing data , and i used many modules for scheduled tasks but i didn't get good results. thanks. -
WebSocket Django Python
I have to add real time data update in my Django project.I have to send data from one project and receive it in another project. I would like to add web socket in my first project and send data from it and listen that request in another project using Javascript to show real time update on dashboard. How is it possible to send data when we call an function from first project using web socket and listen that request in another project to update data . Thanks I have created Web socket connection in my first project but got stucked while sending data from that connection . We need to send data when an function call . -
templates does not show anything in react and django
I am trying to use react and django together and when I dont use Browser Router in react, the single page template loads perfectly but after adding route in App.js frontend is blank. folder structure -- Django_React -- frontend -- urls.py -- views.py --src -- templates -- index.html here is my urls.py urlpatterns = [ path('/login',indexView), re_path(r'^(?:.*)/?$',TemplateView.as_view(template_name='index.html')), ] App.js import React, { Component } from "react"; import ReactDOM from "react-dom/client"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import Index from "./Home/index"; import Login from "./auth/Login"; const App = () => { <BrowserRouter> <Routes> <Route path="">element={<Index />}</Route> <Route path="/login"> element={<Login/>}</Route> </Routes> </BrowserRouter>; }; export default App; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<App />); This is webpack.config.js const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js|.jsx$/, exclude: /node_modules/, use: "babel-loader", }, { test: /\.css$/, exclude: /node_modules/, use: ["style-loader", "css-loader"], }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("development"), }, }), ], }; If I remove Browser Router and return a <div>React</div>, I can see it on frontend but Browser Router does not work. I also recieve … -
Custom Validate function is not being called inside perform_create function in DRF
This is my code. class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = MyClass.objects.all() def get_serializer_class(self): if request.user.is_superuser: return self.serializer_class else: return OtherSerializer def perform_create(self, serializer): if request.user.is_superuser: if serializer.is_valid(): serializer.save(organization=self.request.user.organization) else: employee = Employee.objects.get(user=self.request.user) serializer.save(employee=employee, organization=self.request.user.organization) This is my Serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass def validate(self, data): employee = data.get('employee') members = Team.objects.get(id=team.id.members.all()) if employee not in members: raise serializers.ValidationError('Invalid') return data The issue is, My custom validate function is not being called when I call it inside perform_create() in my ViewSet. What might be the issue? -
how i change the positions of the anwsers
I have a Quiz-Game and wanna change the positions of the answer. How i can fixed that? I've tried a few things but unfortunately nothing worked html {% for q in questions %} {% if q.kategorie == category and q.flaag == True %} {% if questions.has_next %} <br/> <div class="flex-container"> <div class="container1"> <div class="position_startButton"><button type="submit" name="next" value="{{q.question}}" class="nächstefrage_btn">Nächste Frage!</button></div> <div class="game_options_top"> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op1}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">A: <span id="option_span">{{q.op1}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op2}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">B: <span id="option_span">{{q.op2}}</span></button></p> </div> </div> <div class="game_question"> <h1 class="display_question">{{q.question}}</h1> </div> <div class="game_options_bottom"> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op3}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">C: <span id="option_span">{{q.op3}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op4}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">D: <span id="option_span">{{q.op4}}</span></button></p> </div> </div> </div> <div class="menü"> <button class="menü_button"><i class="fa fa-bars" aria-hidden="true"></i><b> Menü</b></button> <div class="items"> <a href="{% url 'Example_dashboard' %}"> <i class="fa-solid fa-house"></i> Startseite </a> <a href="{% url 'Example_fragenkatalog' %}"> <i class="fa-solid fa-pen"></i> Fragenkatalog </a> <a href="{% url 'statistics' %}"> <i class="fa-solid fa-trophy"></i> Statistik </a> <a href="{% url 'settings' %}"> <i class="fa-solid fa-gear"></i> Einstellungen </a> <a href="{% url 'logoutUser' %}"> <i class=></i> Log-Out </a> </div> </div> … -
How do I get a Django redirect to work properly when updating my database?
I can't get my Django redirect to work correctly after updating a bicycle in my Django app. When I use my update_bike view and update the bicycle profile, if my redirect is just to '/bikes', I'm taken back to the bicycle collection/bicycles owned. But when I try and redirect back to the profile of the current bike I'm editing, I get this error that my return pathway doesn't match any of the url patterns. I've pasted the function code here: def bikes_update(request, bike_id): if request.method != 'POST' or 'user_id' not in request.session: return redirect("/") this_bike = Bike.objects.filter(id=bike_id).update( name = request.POST['bike_name'], model = request.POST['model_id'], ) return redirect('/bikes') return redirect('/bikes/<int:bike_id>') return redirect('/bikes/<int:bike_id>/') I obviously comment out the bottom two redirects and the ('/bikes') works fine, it's trying to get back to the current bike profile that doesn't work and gives me the error. I'm able to update the bicycle profile correctly, so it's something to do with this redirect, but I don't get it. I don't understand how line 12 in my screen snippet and the current path (both highlighted in the image), aren't the same/don't match. -
Django while running the server ModuleNotFoundError: No module named 'customer data'
I'm using django to make an API that connects to another one to get some data and update some values. The idea is that the api can be executed from a CLI through commands like upgrade customer_id target_subscription. Before making the CLI file, the api works perfectly if you make requests to it (for example using vs code's thunder client). Once I make the CLI file and try to test I get the following error: Im running the code on Windows 10 and WSL bash. I create the django project using: django-admin startproject customer_data cd customer_data python manage.py startapp customer My file/folder strucutre is this: My API code: class UpdateCustomerSubscriptionView(APIView): def extractCustomerData(self, customer_id): """ Input: A customer id Output: The customer data """ customer = None try: response = requests.get(f'{API_LINK}{customer_id}/') customer_data = response.json() customer = Customer(**customer_data) except: return Response({"error": "The ID does not exist or is badly formated."}, status=500) return customer def upgrade_or_downgrade(self, customer_id, target_subscription): """ Input: A customer id and a target subscription level Output: The updated customer data """ # Validate that the id is not null if customer_id is None: return Response({"error": "The customer id is null."}, status=500) # Validate that the new subscription is not null … -
ManyToManyField constraints
Django ORM seems not to permit constraints on ManyToManyField. class Component(ComponentMetaData): class Type(models.IntegerChoices): Part = 0 Components = 1 type = models.IntegerField( choices=Type.choices, ) components = models.ManyToManyField( "self", blank=True, null=True, ) def clean(self) -> None: if self.type == 0 and self.components: raise ValidationError("Parts could not have components.") return super().clean() class Meta: constraints = [ models.CheckConstraint( check=( Q(type = 0) & Q(components__isnull = True) ) | ( Q(type = 1) # componenets only fields ), name = "components_enum" ) ] Migration attempt with the above model results in the error below; ERRORS: myapp.Component: (models.E013) 'constraints' refers to a ManyToManyField 'components', but ManyToManyFields are not permitted in 'constraints'. Does anyone know why this is not permitted and what should one do if one would like to keep a ManyToManyField empty on some condition based on the values of other fields? -
react oauth2 authentication not working when request is sent
i am trying to integrate social authentication for my react site which i am using drf for the server side, here i am using react-oauth2/google library because the react-google-login npm package seem to be depreciated, so unlike react-google-login that once a request is sent to google from the client side it return an accesstoken and refresh token that is automatically sent to django's end through a callback requesting django authtoken and also sending/comparing users data if any. react-oauth2/google on the other hand tend to only give me just one token called code. i sent it to my server side and it returned wrong credential. error i am using social_django for my drf server side AUTH.JS const GoogleLoginFunc = useGoogleLogin({ flow: 'auth-code', onSuccess: async (codeResponse) => { console.log(codeResponse); // const tokens = await axios.post( // 'http://localhost:3000/auth/google', { // code: codeResponse.code, // }); // console.log(tokens); SocialGoogleLoginFunc(codeResponse.code) }, onError: errorResponse => console.log(errorResponse), }); <GoogleLogin onSuccess={GoogleLoginFunc} // onSuccess={credentialResponse => { // console.log(credentialResponse.credential); // SocialGoogleLoginFunc(credentialResponse.credential) // }} onError={() => { console.log('Login Failed'); }} useOneTap />; GOOGLEAUTH.JS const SocialGoogleLoginFunc=(accesstoken,app_id,app_secret)=>{ // console.log(`MY CREDENTIALS ${app_id},${app_secret}`) // let client_id='nILBGJCOSiaLKDyRZeFpHmUoyDw0PgChrkEGzjkj' // let client_secret='fkUSbr5mtR6oIX3osX51zS1ycbWOfNWGvEjhhKwVQvBb3rJ8gRN1BW2gkFMiPBfBKq3437IC3joXQUEFxPRs1PSXfSgKehOCwoRJoNgjtAzI6ZXwdjyX3RyZfTKKb8hE' // console.log(client_secret.includes(' ')) // http://127.0.0.1:8000/client/auth/convert-token // grant_type:"convert_token", // client_id: client_id, // client_secret: client_secret, // backend:"google-oauth2", // token:accesstoken …