Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
retrieve query params in django
I created a redirect endpoint on my django app. I normally am able to get query params from the url path but when this redirect happens, it appends the value # to the url. this stops me from being able to get the query params. how do i retrieve access_token as a query params from this url? /redirect/#access_token=ya29.a0AXooCgvXSv2-9x-4i6V I tried using request.GET.get('access_token') but it did not work. I also printed request.META but access_token is not in it -
Use IntegerChoices instead of Model for rest framework
I have field like this, models.py from django.db import models as m class Faculty(m.IntegerChoices): Arts = 1, 'Arts', Scienece = 2, 'Sceience' Other = 3 ,'Other' and it is used as reference in other models. Howeber, now I want to get the list by API rest framework. For example if it is not IntegerChoices but Model I can use the rest framework with view and serializer class MyModelViewSet(viewsets.ModelViewSet): queryset = sm.Faculty.objects.all() serializer_class = s.FormSelectorSerializer class MyModleSerializer(ModelSerializer): detail = serializers.JSONField() class Meta: model = sm.MyModel fields = ('id') I can use the rest framework like this , However for IntegerChoices, How can I do the equivalent to this thing? Or is it possible? -
Django extra actions need to add additional parameter but not working
I have a extra action in Django. I need to provide additional query param to it, shown below: class MyViewSet: .... ... @action(detail=True, method=["get"], url_path=r"abc/(?P<name>[A-Za-z\.]+)") def abc_op(self, request, pk, name): .... The above is not working when I call the API like: http://localhost:8000/employee/1/abc/xy.z, but if I append / at the end I get the result: http://localhost:8000/employee/1/abc/xy.z/ with request http://localhost:8000/employee/1/abc/xy.z I get: { "detail": "Not found." } But when I make request http://localhost:8000/employee/1/abc/xy.z/ (appending / at the end) I get: { "result": True, "data": [] } Please let me help understand what is wrong here. This should work without appending any / at the end. -
DatabaseError at /admin/shop/item/add/
here pic of error another pic debug log DatabaseError at /admin/shop/item/add/ No exception message supplied Request Method:POSTRequest URL:http://127.0.0.1:8000/admin/shop/item/add/Django Version:4.1.13Exception Type:DatabaseErrorException Location:C:\Users\MSI\Desktop\A Project_Django_thanhduc\my_venv\Lib\site-packages\djongo\cursor.py, line 81, in fetchoneRaised during:django.contrib.admin.options.add_viewPython Executable:C:\Users\MSI\Desktop\A Project_Django_thanhduc\my_venv\Scripts\python.exePython Version:3.11.9Python Path:['C:\\Users\\MSI\\Desktop\\A Project_Django_thanhduc\\my_app', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\python311.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\Lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0', 'C:\\Users\\MSI\\Desktop\\A Project_Django_thanhduc\\my_venv', 'C:\\Users\\MSI\\Desktop\\A ' 'Project_Django_thanhduc\\my_venv\\Lib\\site-packages']Server time:Tue, 21 May 2024 08:33:44 +0000 This is my setting.py database DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'onlineshop', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'localhost', 'port': 27017, 'authSource': 'admin', # Đảm bảo rằng authSource là đúng }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, } } Model.py : from django.db import models from django.contrib.auth.models import User class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=20, decimal_places=2) image = models.ImageField(upload_to='items/', null=True, blank=True) description = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return f"{self.name} - {self.host.username if self.host else 'No Host'}" I'm start a project with django and mongodb(with djongo eninge). When I create user in my template(html) i can create item, update, delete, even with superuser. But when I go to adminstrations(with … -
Reverse for 'listing_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['listings/listings/(?P<pk>[0-9]+)/\\Z']
I'm new to django and I'm creating a listing site, similar to Gumtree. When I try to retrieve the logged-in user's listings from the database and display on their MyListings page, I get the above error. My code is below. Any help would be appreciated! Also, I have checked, each listing has a pk value. urls.py from django.urls import path from listings import views urlpatterns = [ path('my_listings/', views.my_listings, name='my_listings'), path('create/', views.create_listing, name='create_listing'), path('listings/<int:pk>/', views.listing_detail, name='listing_detail'), path('listings/<int:pk>/update/', views.update_listing, name='update_listing'), path('listings/<int:pk>/delete/', views.delete_listing, name='delete_listing'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Listing from users.models import Profile from .forms import ListingForm from django.contrib import messages from django.contrib.auth import get_user_model from django.db import IntegrityError from django.core.exceptions import ObjectDoesNotExist User = get_user_model() @login_required def my_listings(request): print("my_listings view called") context = {} #initialise the context dictionary if request.user.is_authenticated: try: # Get logged-in user logged_in_user=request.user # Get user profile profile=get_object_or_404(Profile, email=logged_in_user.email) print(f"Profile for user {request.user}: {profile}") listings = Listing.objects.filter(profile=profile) print(f"Listings for profile {profile}: {listings}") for listing in listings: print(f"Listing PK: {listing.pk}") except ObjectDoesNotExist: print(f"Profile does not exist for user {request.user}") # If the profile doesn't exist, handle the error profile = None listings = Listing.objects.none() context['listings'] = listings print("Context … -
How can I prevent the user to add a public holiday who has the same date with other public holiday in django?
I am new to django. My model is this: class PublicHoliday(models.Model): name = models.CharField(_('Holiday Name'), max_length=100, unique=True) date_time = models.DateField(_('Holiday Date')) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name @receiver(pre_save, sender=PublicHoliday) def save_current_year(sender, instance, **kwargs): new_intance_date_time = instance.date_time.replace(year=timezone.now( ).year, month=instance.date_time.month, day=instance.date_time.day) instance.date_time = new_intance_date_time And the serializer is this: class PublicHolidayCreateSerializer(serializers.ModelSerializer): class Meta: model = PublicHoliday fields = '__all__' def create(self, validated_data): if PublicHoliday.objects.filter(date_time=validated_data['date_time']).exists(): raise serializers.ValidationError("This public day already exists") return super().create(validated_data) def update(self, instance, validated_data): if 'date_time' in validated_data and PublicHoliday.objects.filter(date_time=validated_data['date_time']).exclude(pk=instance.pk).exists(): raise serializers.ValidationError("This public day already exists") return super().update(instance, validated_data) But when I create or update a public holiday who has the same dates as other public holidays doesn't work. How can I solve this -
Django Links & Buttons Click Issue: All clicks open in a new window
Since a number of commits, All clicks on buttons, links, submit buttons... open in a new window. Submitting forms does not work anymore, which means I can't test the last changes I've made, and the navigation is obviously broken. What's happening: Clicking on any button or link opens a new window/tab, as the target="_blank" attribute would have the links behave What's expected: Action after clicking on any button or link should instead stay on the same page, as the default target="self" link behavior... I have no real clue of where the issue might be coming from...: An incorect or closure? I've checked, rechecking... One of the libraries that remained after I uninstalled tailwind A fault in the django_browser_reload extension Something linked with django-unicorn ? Thank you for helping me fix this blocking issue... -
Django Model OneToOneField migrations cannot encounter column
Hello im learning Django and trying to add a new table where I save my isbn numbers and I wanted to make onetoone relation book with isbn number. Django creates the tables of isbn and books aswell. the problem when I do the onetoonefield. models.py from django.db import models class BookNumber(models.Model): isbn_10 = models.CharField(max_length=10, blank=True) isbn_13 = models.CharField(max_length=13, blank=True) class Book(models.Model): title = models.CharField(max_length=36, blank=False, unique=True) description = models.TextField(max_length=266, blank=True, unique=False) price = models.DecimalField(default=0, max_digits=6, decimal_places=2) published = models.DateField(blank=True, null=True) is_published = models.BooleanField(default=False) file = models.FileField(upload_to='covers/', blank=True) cover = models.ImageField(upload_to='covers/', blank=True) #numbers = models.OneToOneField(BookNumber, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title when I uncomment the numbers it throws the next error: virtenv/lib/python3.12/site-packages/django/db/backends/sqlite3/base.py", line 329, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.OperationalError: **no such column: demo_book.number_id** from the SQLLite: sqlite> .tables auth_group demo_book auth_group_permissions demo_booknumber auth_permission django_admin_log auth_user django_content_type auth_user_groups django_migrations auth_user_user_permissions django_session authtoken_token sqlite> .schema demo_book CREATE TABLE IF NOT EXISTS "demo_book" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(36) NOT NULL UNIQUE, "cover" varchar(100) NOT NULL, "description" text NOT NULL, "file" varchar(100) NOT NULL, "is_published" bool NOT NULL, "price" decimal NOT NULL, "published" date NULL); sqlite> .schema demo_booknumber CREATE TABLE IF NOT EXISTS "demo_booknumber" ("isbn_10" varchar(10) NOT NULL, … -
Simplest way to get Django errors emailed to
I have a Django Application hosted on Python Anywhere with a PostGre back end. Is there anyway I can get the errors that are normally added to the error log to sent to my email, so I can be quickly notified of error. I am familiar with writing simple middleware, but i don't understand Django well enough to know how to capture the errors that go to error-log file. -
How to serialize subprocess.popen()
This is follow-on to Return output of subprocess.popen() in webserver. I have a long running process that is kicked off by a Webserver call (running Django). I'm using subprocess.popen() to spawn the process. I figured out how I can save the stdout and retrieve it later. But since this is a long-running process, I want the client to be able to cancel it. But in order to do that, I need an instance of the popen() object. But it is not serialiable, so I can't store it in a database or anywhere else? Is there any other solution other that just storing it locally in a map in views.py? -
Cannot view Django application installed with helm on Minikube
I have packaged a custom helm chart and did helm install announcements /helm When I go to kubectl get pods and kubectl get deploy it shows the pods and deployments are up. However, when I try to go to the Service IP to see the application, it hangs. I then try to do the command given by the helm install: export SERVICE_IP=$(kubectl get svc --namespace default announcements-helm --template "{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}") And then I get the error: error: error executing template "{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}": template: output:1:10: executing "output" at <index .status.loadBalancer.ingress 0>: error calling index: index of untyped nil I'm very new to Helm and Kubernetes, so I'm not sure what to try to fix this. Any advice? -
Embed HTML file inside another HTML file
I have an HTML file which contains Django Template Language loops and variables. I want to add this file to another HTML file for readability mainly. I tried to use but I am getting a 404 error (file is located inside a folder which I already tried to add to src="folder/file.html"). Thank you in advance. -
django multiple database settingup for multiple region
In a Django project with multiple regional databases, fetching an employee object with a related model from a different database results in the related model being retrieved from the default database instead of the intended regional database. Two regional databases (us and potentially others) DatabaseRouter to route models to their respective databases Issue occurs when trying to prefetch or access related models using foreign key relationships i have share the djangoshellplus and the dbrouter code for reference -
django TemplateSyntaxError at /display/displaymyoperations/ Could not parse the remainder: '(url)' from 'unquote(url)'
hi every one i received the message above when i want to show the oprations that user make i have a project to evluate youtube vidios and web shows in frame in my project this is views.py for myoprations `def displaymyoperations(request): # استرداد بيانات المستخدم الحالي current_user = request.user userprofile=UserProfile.objects.get(user=current_user) # استعلام بيانات العروض التي قام المستخدم بتقييمها display_data = Display_Data.objects.filter(users=userprofile).order_by('-puplish_date') #display_data = Display_Data.objects.filter(users=userprofile) # تحويل قيمة التقييم إلى نص وصفي for display_datum in display_data: if display_datum.choosenum == 1: display_datum.choosenum_text = "نجاح" elif display_datum.choosenum == 2: display_datum.choosenum_text = "فشل" elif display_datum.choosenum == 3: display_datum.choosenum_text = "بحاجة إلى مال" elif display_datum.choosenum == 4: display_datum.choosenum_text = "بحاجة إلى أدوات" else: display_datum.choosenum_text = "مؤجل" # تحضير سياق العرض (context) context = { 'display_data': display_data, } # عرض القالب (template) مع البيانات return render(request, 'display/displaymyoperations.html', context) and this is templete ` {% for display_datum in display_data %} {% if display_datum.displays.isyoutube %} {% with video_id=display_datum.displays.url|slice:"30:" %} {{ display_datum.displays.text }} {% endwith %} {% else %} {% with url=display_datum.displays.url|stringformat:"s" %} {{ display_datum.displays.text }} {% endwith %} {% endif %} <strong>{{ display_datum.choosenum_text }}</strong> {{ display_datum.puplish_date }}<br> {% endfor %}`` the probelm is raise on display_web although display_video is the same i dont know why this error rise … -
How can I host a Django application for free?
I have made APIs for my project Now I want to host it, but I am using MySQL workbench for the database. Is it possible to host it from render? or any better option to do so please give me the solution. So can I host from Render? or any other easy method? -
How to get value of variable from one funtion to another in python?
This is first Funtion: def signup(request): if request.method == "POST": username = request.POST['uname'] first_name = request.POST['fname'] last_name = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] This is second function: def createPost(request): if request.method == "POST": form = PostForm(request.POST) print(form.is_valid()) if form.is_valid(): # To extarct data from web page title = form.cleaned_data['title_name'] description = form.cleaned_data['description'] print(title) # To store Data PostData.objects.create(title_name=title, description=description) How to get value of 'username' from first function to second function? -
Django app log messages not appearing in ECS/CloudWatch
Issue: I have a Django project deployed on ECS, and I am experiencing issues with my logging configuration. I am unable to see my custom logging messages in AWS CloudWatch Logs. The only log messages I can see are from botocore, urllib3, and root loggers. My custom log messages are not appearing at all. Current Logging Configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'json': { 'format': '%(levelname)s %(asctime)s %(name)s %(message)s %(lineno)d %(pathname)s', 'class': 'pythonjsonlogger.jsonlogger.JsonFormatter', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'json', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, 'ru_profile': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, '': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG', }, } Example Log Usage: import logging logger = logging.getLogger('ru_profile') class ForgotPasswordView(CreateView): model = User template_name = 'user/forgot_password.html' form_class = ForgotPasswordForm def form_valid(self, form): phone = str(form.cleaned_data['phone']) user = User.find_by_phone(phone) if user is not None: user.send_reset_pin() logger.info(f"Reset PIN sent successfully to {phone}") else: logger.error(f"Couldn't reset PIN, user not found for phone '{phone}'") django_messages.error(self.request, _("Couldn't reset your PIN. Please try again")) return self.form_invalid(form) return redirect('reset_pin_view', phone=phone) Observed Logs: In CloudWatch Logs, I only see … -
space is not sliced from my text in front-end
so here my front-end js code for the keyHandler let snippet = document.getElementById('snippet'); let remaining = document.getElementById('remaining'); let typed = document.getElementById('typed'); let result = document.getElementById('result'); const keydownHandler = (event) => { let key = event.key; if (key.length === 1 && /[a-z .]/i.test(key) ) { if (key === snippet.innerText[typed.innerText.length]) { if(key == " "){ console.log('its space !!!!!!'); typed.innerText += ' '; }else{ typed.innerText += key.toLowerCase(); } remaining.innerText = snippet.innerText.slice(typed.innerText.length); result.innerText = ''; } else { result.innerText = 'Incorrect key pressed!'; } } let message = JSON.stringify({ 'snippet_text':snippet.innerText, 'typed_text': typed.innerText, 'remaining_text': remaining.innerText, }); if (socket.readyState === WebSocket.OPEN) { console.log('Sending message:', message); socket.send(message); } }; the problem is that when i type the ' ' (spacebar) , it does not get removed from my remaining text in the front-end. here is the back-end consumer : def receive(self, text_data): data = json.loads(text_data) typed_text = data.get('typed_text', '').lower() snippet_text = data.get('snippet_text', '').lower() is_correct = typed_text == snippet_text if is_correct: self.current_snippet_index += 1 self.player_score += 1 self.send(json.dumps({ 'is_correct': is_correct, 'player_score': self.player_score, })) self.send_new_snippet() #send new snippet with full details else: remaining_text = snippet_text[len(typed_text):] self.send(json.dumps({ 'snippet_text': snippet_text, 'typed_text': typed_text, 'remaining_text': remaining_text, })) here an image of the results : -
Django app, how to generate form dynamicly based of JSON?
Currently i am doing this: [ { "name": "hostname", "type": "string", "description": "Hostname router", "required": "Yes" (No if it is not required) }, { "name": "is_dhcp", "type": "choice", "description": "DHCP?", "choices": [ [ "yes", "Yes" ], [ "no", "No" ] ], "required": "No" }, { "name": "gateway", "type": "ip", "description": "Gateway DHCP", "required": "Yes" }, { "name": "sub_int_bck", "type": "integer", "description": "In case of existing! - Sub interface", "required": "No" }, { "name": "exIpList", "type": "list", "description": "List excluded IPs, seperated by ;", "required": "No" } ] Then i use a big amount of If's to check one by one: if var_type.lower() == 'string': self.fields[var_name] = forms.CharField( label=var_description, required=var_req_bool, widget=forms.TextInput(attrs={"class": "form-control"}) ) elif var_type.lower() == 'integer': self.fields[var_name] = forms.IntegerField( label=var_description, required=var_req_bool, widget=forms.TextInput(attrs={"class": "form-control"}) ) elif var_type.lower() == 'choice': self.fields[var_name] = forms.ChoiceField( label=var_description, choices=var.get('choices', []), # Default to empty list if not provided widget=forms.Select(attrs={"class": "form-control"}), required=var_req_bool ) elif var_type.lower() == 'ip' and 'mask' in var_description.lower(): self.fields[var_name] = forms.GenericIPAddressField( label=var_description, required=var_req_bool, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "255.255.255.0 OU 0.0.0.255 OU 24"}), ) elif var_type.lower() == 'ip': self.fields[var_name] = forms.GenericIPAddressField( label=var_description, required=var_req_bool, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "192.168.1.1"}), ) elif var_type.lower() == 'list': self.fields[var_name] = forms.CharField( label=var_description, required=var_req_bool, widget=forms.Textarea(attrs={"class": "form-control"}), ) elif var_type.lower() == 'bool': self.fields[var_name] = … -
Nothing happens when transferring the registration form data to the database
I have a problem. I'm new to django. And so the error lies in the fact that nothing happens during the data transfer. The database is not being updated. I will be very grateful for your help! this is code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('/register', views.register, name='register'), ] registration/views.py: from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import RegistrationForm from django.shortcuts import render, redirect def register(request): # Change function name to match the URL pattern if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) print(form) return redirect('home') else: form = RegistrationForm() return redirect('news') return render(request, 'registration/register.html', {'form':form}) urls.py(In the project itself): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('news/', include('news.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) register.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Регистрация</title> </head> <body> <h1>Регистрация</h1> <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{ form.email }} {{ form.password1 }} {{ form.password2 … -
Django: overriding an abstract class with a generic relation limiting ContentType choices dynamically?
Following the current documentation https://docs.djangoproject.com/en/5.0/ref/contrib/contenttypes/#generic-relations I created a GenericReferModel which is an abstract class that define a generic relation towards one or more models. So far so good. Now I'd like to limit the ContentType choices exploiting the limit_choices_to attribute of models.ForeignKey. from typing import Any from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import gettext_lazy as _ class GenericReferModel(models.Model): refer_type_choices: models.Q | dict[str, Any] | None = None # https://docs.djangoproject.com/en/5.0/ref/contrib/contenttypes/#generic-relations refer_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to=refer_type_choices, verbose_name=_("refer type"), ) refer_id = models.PositiveIntegerField( _("refer id"), null=True, blank=True, ) refer = GenericForeignKey("refer_type", "refer_id") class Meta: abstract = True indexes = [ models.Index(fields=["refer_type", "refer_id"]), ] class Chat(GenericReferModel): nome = models.CharField(_("nome"), max_length=255) refer_type_choices = ( models.Q(app_label="core", model="studio") ) class Meta: verbose_name = _("chat") verbose_name_plural = _("chat") Apparently, overriding refer_type_choices does not work and it is always considered the abstract class default value. Is there a way to achieve a dynamic assignation of choices on each subclass? -
Django Custom admin template
I changed the admin site index template in Django like this: ``` admin.site.index_template = "admin/list-aprovals.html" ``` but how can i send my model datas this page or can i add a custom view for this url: ``` path('admin/', admin.site.urls), ``` So, I want to work with the existing django admin, but I only want to change the template and see my models in this special template, but with the original admin app. Is this possible in Django? How do I solve this problem? I tried custom app but i want to use original contrib admin. -
Return output of subprocess.popen() in webserver
I have a Webserver in Python using Django. I want to be able to kick of a long-running asynchronous subprocess and then have the client poll with a GET or POST and receive stdout as well as other information. For each iteration, the server will return the lines of stdout that it has so far. When the process ends, additional information will be returned. How can I save the instance of cmd=subprocess.popen() so that on subsequent GET/POST, it can make the appropriate calls (e.g. cmd.poll, cmd.stdout.readline(), etc) I've tried using Django's session manager, but the popen object is not Json serializable -
how to create a foreign key from the top model to bottom model?
class Model1(models.Model): x = models.ForeignKey(Model2, on_delete=models.CASCADE) class Model2(models.Model): y = models.CharField(max_length=200) How to create a foreign key to Model2 from Model1? I know maybe you say you just need to replace Model1 with Model2 and then create a foreign key, but sometimes like now I need to do something like this. -
how to use a variable where a keyword is expected
I have this problem with Django, but I feel is more of a python question: user_data = User.objects.filter(userid__startswith='Jeremy').values('mail','address') the above works and returns me exactly one line, as I know it should. This does not work: jeremy='Jeremy' user_data = User.objects.filter(userid__startswith=jeremy).values('mail','address') because manage.py runserver complains that my queryset is empty, when attempting to use it. I went all over the internet and found countless variations about using a dictionary, like this: my_kws={'userid__startswith':'Jeremy'} user_data = User.objects.filter(**mykws).values('mail','address') which do work, but when changed to: jeremy='Jeremy' my_kws={'userid__startswith':jeremy} user_data = User.objects.filter(**mykws).values('mail','address') absolutely do not. For me, at least, they end up exactly as before, with an empty querySet. Other uncountable answers propose to do: jeremy='Jeremy' user_data = User.objects.filter(f'userid__startswith={jeremy}').values('mail','address') with exactly the same result as before. FWIW, I am using python 3.10.12