Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you deploy sqlite db to pythonanywhere? if so how do you configure it for deployment?
Deploying sqlite database to python anywhere -
Why is my attempt to clone this django repository failing?
I am trying to clone a django repository, but I keep running into problems. I am trying to do this through a virtualenv. When I run python3 manage.py runserver I am met with the following error: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 480, in check for pattern in self.url_patterns: File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 689, in urlconf_module return import_module(self.urlconf_name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", … -
Securing Endpoint in Django including Generic Relationship
In a simplified version i have 3 classes in the first app (named: appBasic): class ClassA(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) class ClassB(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() specific_B = GenericForeignKey('content_type', 'object_id') in another app (appSpec) class ClassBSpec(models.Model): class_b = GenericRelation(ClassB, related_name='class_b') class_a = ForeignKey(ClassA, on_delete=models.CASCADE) using these classes i build the endpoints using NestedRouters form the rest_framework_nested to get to: /appSpec/class_b_spec/ /appSpec/class_b_spec/<pk>/ /appSpec/class_b_spec/<class_b_spec_pk>/class_b/ /appSpec/class_b_spec/<class_b_spec_pk>/class_b/<pk>/ my goal is to protect these endpoints and allow post,get,put,patch request only for instances, which belong (via class_a) to the current user. To secure the first two endpoints i add the following method in the ClassBSpecSerializer: def validate_class_a(self, class_a): user_id = self.context['user_id'] if classs_a.user.id != user_id: raise serializers.ValidationError('No class_a with given ID found for this user') return class_a However, i cannot do the same for the other two endpoints, /appB/class_b_spec/<class_b_spec_pk>/class_b/ /appB/class_b_spec/<class_b_spec_pk>/class_b/<pk>/ because here i am dealing with a generic relation-ship What i have implemented for now is to override the ViewSet for ClassB in the second app (appSpec) such as: from appBasic.views import classBViewSet as BasicClassBViewSet class ClassBViewSet(BasicClassBViewSet): class_b_spec_queryset = ClassBSpec.objects.filter(classA__user_id=self.request.user.id) class_b_spec = get_object_or_404(class_b_spec_querset=self.kwargs['class_b_spec_pk'] return class_b_spec.class_b.all() like that i can ensure that i get a 404 error when i am at this endpoint: /appB/class_b_spec/<class_b_spec_pk>/class_b/ … -
Having a list of autocomplete options in Django form CharField
I have a Django form with two CharFields. I want users to be able to type but I want autocomplete suggestions based on the values in the database. Here is an example of what I want pulled from another website. This is what I am currently doing. albums = Album.objects.values_list('artist', flat=True).distinct() artists = Album.objects.values_list('name', flat=True).distinct() class MakeGuess(forms.Form): artist = forms.CharField(max_length=100, label='', widget=forms.TextInput(attrs={'placeholder': 'Artist'})) album = forms.CharField(max_length=100, label='', widget=forms.TextInput(attrs={'placeholder': 'Album'})) The goal is to have the autocomplete dropdown for the artist field be the artists list and same for the albums. I tried to use a forms.TypedChoice field with choices=artists but it did not do what I thought it would. -
How do I check if a user is in a group or another group
I'm making an API using django and I want to check whether the user is in a group A or a group B using request.user.groups.filter() method but it does not seem to work. I want to be able to pass more than just one group through the name parameter to check if they are indeed in group A or group B. I've tried the following: if request.user.groups.filter(name="A") or request.user.groups.filter(name="B"): do stuff I've also tried: if request.user.groups.filter(name="A" or "B"): do stuff But I seem to be getting no luck and all I'm getting is that I need to be in group A to access the content when I want it to check whether I'm in A or B. -
There is no way to use app password on gmail account trough django app
I have running in production a django app, the webapp has a function in order to send emails with attachment to some guys using a gmail account through app password option . The functionallity worked OK for more than 3 years until a couple of days when show up this error in the errorlog: App 2165051 output: smtplib.SMTPAuthenticationError: (535, b'Incorrect authentication data') Things that i've already checked: 1.- When I checked the app password of gmail account there wasn´t anyone. ( weird, it seems that dissapeared) 2.- I created a new one, replace the new password in my code and still showing 535 error. 3.- I've create trhee app passwords and still no luck. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxx@adicra.org.ar' EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = True views.py #Vista de enviar por mail class pagosMailPdfView(View): def get(self,request,*args,**kwargs): print("Aca en pagosMailPdfView") mailServer = smtplib.SMTP(settings.EMAIL_HOST,settings.EMAIL_PORT) #print(mailServer.ehlo()) mailServer.starttls() #print(mailServer.ehlo()) print(settings.EMAIL_HOST_USER) print(settings.EMAIL_HOST_PASSWORD) mailServer.login(settings.EMAIL_HOST_USER,settings.EMAIL_HOST_PASSWORD) print("conectando...") # averiguo la dirección de email del socio pagoh=PagosHead.objects.get(pk=self.kwargs['pk']) emailsocio=pagoh.numero_socio.email I assume that the problem is related to the google account configuration. Does anybody knows how to check this? Thanks in Adavance, Regards -
Third level HTMX back to original page?
I am using Django & HTMX. I have two sites, lets say site FOO and site BAR They both load HTMX page #1 on load There are links on HTMX page #1 for a modal- HTMX page #2 I am trying to code DRY and need a way for a button on HTMX page #2 to take me back to site FOO or site BAR, depending on where I started. I could add a ? variable in the URL and take it through two levels but I was wondering if there was an easier way. thanks! -
Problem creating django project in Pycharm
When I try to create Django project using Pycharm I receive errors which doesn't allow me to create the project. Now I am only able to create Django project using the terminal. I am able to create a Django project using the terminal but I am currently in python web course where the creation of Django projects happens only with Pycharm so I will be really greatful to solve this problem [[(https://i.stack.imgur.com/0Y33j.png)](https://i.stack.imgur.com/3ecvJ.png)](https://i.stack.imgur.com/opu8j.png) -
aws CLI configured properly but why boto3 not getting the credential?
AWS cli working but boto3 not working. I installed aws CLI on my ubuntu server and the problem is boto3 not getting the credentials from my Ubuntu machine until I hardcode the key in my code like s3_client = boto3.client('s3', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY, region_name=REGION_NAME ) I also run this command to aws s3 ls to verify does aws CLI working or not and it's returning all of my aws bucket name which means CLI configured properly but why boto3 not getting the credential from my ubuntu machine. I am using boto3 in my django project. -
Django TypeError: str returned non-string (type NoneType) in admin change view
I'm encountering an error when trying to access the admin change view for an order object in my Django application. The error message states: "TypeError: str returned non-string (type NoneType)." This issue occurs when accessing the URL http://127.0.0.1:8000/admin/accounts/order/38/change/. Here are some additional details about the problem: Django version: 4.2 Python version: 3.11.3 Exception location: C:\Users\Brenn Alexander\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\forms\models.py, line 1504 The error seems to be related to the str method defined in one of my models. Here's the relevant code snippet: class Order(models.Model): # ... def __str__(self): if self.product: return str(self.product) return f"No Product (Order #{self.id})" I suspect that there might be an issue with the product field in the Order model, causing the str method to return None. This error is then propagated to the admin change view, resulting in the mentioned error. I'm unsure how to troubleshoot and resolve this issue. I would greatly appreciate any insights or suggestions on how to fix this error and ensure that the str method returns a string value as expected. Thank you in advance for your help! `class Product(models.Model): CATEGORY = ( ('Residential', 'Residential'), ('Commercial', 'Commercial'), ('Auto', 'Auto'), ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = … -
Django REST Framework NOT NULL constraint failed: afritechjobsapi_postajob.job_category_id
When I try to create a new Job post by posting the following JSON: { "job_title": "Software Developer", "job_category": [ { "id": 1, "name": "Engineering" }, { "id": 2, "name": "IT" } ], "job_skills": [ { "id": 1, "title": "DJ", "category": [ { "id": 1, "name": "Web Development" }, { "id": 2, "name": "Python" } ] }, { "id": 2, "title": "RT", "category": [ { "id": 3, "name": "Frontend Development" }, { "id": 4, "name": "JavaScript" } ] } ], "job_salary_range": 80000, "job_description": "We are looking for a skilled software developer proficient in Django and React...", "job_type": { "id": 1, "job_type_choices": "FT" }, "job_location": [ { "id": 1, "name": "New York" }, { "id": 2, "name": "San Francisco" } ], "job_level": [ { "id": 1, "job_level_choices": "EL" }, { "id": 2, "job_level_choices": "ML" } ], "job_application_link": "https://example.com/apply", "company_name": "ABC Company", "company_hq": "New York", "company_logo": "https://example.com/logo.png", "companys_website": "https://example.com", "company_contact_email": "info@example.com", "company_description": "ABC Company is a leading software development company...", "date_created": "2023-06-09T12:00:00Z", "date_updated": "2023-06-09T14:30:00Z" } I get the following error: IntegrityError at /jobs/create NOT NULL constraint failed: afritechjobsapi_postajob.job_category_id MODELS.PY class Category(models.Model): name = models.CharField(max_length=50, unique=True, null=True, blank=True) def __str__(self): return self.name class JobLocations(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class JobType(models.Model): … -
How to successfully set up both the html templace and view for Recaptcha v2 without using forms
I read other related questions about recaptcha and django without forms but I didn't find a complete solution or the posts where too old. My situation is this: I am using the package django-recaptcha. I added the "captcha" app in INSTALLED_APPS and setted up the private and public keys for recaptcha. This is currently my code in views: def verify_recaptcha(response): url = 'https://www.google.com/recaptcha/api/siteverify' params = { 'secret': settings.RECAPTCHA_PRIVATE_KEY, 'response': response, } response = requests.post(url, data=params) data = response.json() return data['success'] def contact(request): context = { 'RECAPTCHA_PUBLIC_KEY': settings.RECAPTCHA_PUBLIC_KEY } if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') captcha_response = request.POST.get('recaptcha_response') if name and email and message: if verify_recaptcha(captcha_response): send_mail( subject="Contact Form Submission", message=f""" Name: {name} Email: {email} Message: {message} """, from_email=FROM_EMAIL, recipient_list=[TO_EMAIL], fail_silently=False, ) context['message'] = 'Your message has been sent!' else: context['error'] = 'Invalid reCAPTCHA response.' else: context['error'] = 'Please fill in all required fields.' return render(request, 'contact.html', context) And this is the extract of my html template: <div class="field"> <div class="g-recaptcha" data-sitekey="{{ RECAPTCHA_PUBLIC_KEY }}"></div> <input type="hidden" name="recaptcha_response"> </div> <div class="field has-text-centered"> <button type="submit" class="button is-success has-background-success-dark"> Submit </button> </div> I am using the recaptcha v2. The widget seems to work just fine in the … -
How to log user into Superset UI
I'm using Django and superset. I'm able to login programmatically in one of my views and get an access token and a csrf token with my username and password. However, my end goal is to log the user into an embedded superset dashboard in one of my templates. In my view I'm using request sessions and I can see my cookie session value. In my UI, the cookie that is set is a different value. Is there a way that I can tell Django to use the same request session in my template as what is being used in my view? Or, perhaps there is another way to accomplish the same task of logging a user into the UI automatically. I'm open to that too, it just seems like I'm so close. The code I'm using is below, specifically the programmatic_login function. It all works, I would just like to let my template know that the user has already been authenticated. class SuperSetApi(): csrf_token = '' access_token = '' refresh_token = '' session = None base_url = 'http://superset:8088/' username = '' password = '' guest_token = '' custom_token = '' def url(self, base_url, url_path): return base_url + url_path def add_remote_user_header(self, … -
How to display Comments total on other page using in django using annotate()
any one to help me on how to use annotate() to display the comments total for each object in django model. below is my code. models.py class GameArticle(models.Model): sno=models.AutoField(primary_key=True) status=models.CharField(max_length=10, choices=STATUS, default='Draft') uid= ShortUUIDField(help_text='Place for the Article ID ', unique=True, max_length=10, length=5, prefix='ar',alphabet='aBcDeFgHjKlM12345') title = models.CharField(max_length=200, help_text='Enter The Article Title') class GameArticleComment(models.Model): sno=models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User, on_delete=models.CASCADE) article=models.ForeignKey(GameArticle, on_delete=models.CASCADE, related_name='comments') parent=models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp=models.DateTimeField(default=now) class Meta: ordering=['-timestamp'] Views.py def game_article(request): article_list = GameArticle.published.all() #............ def article_detail(request, uid): data = get_object_or_404( GameArticle, slug=uid, status='p') comments = GameArticleComment.objects.filter(article= get_object_or_404(GameArticle, slug=uid), parent=None) any one to direct me on how to use annotate and return the total of the comments for each object -
Django form error using ManyToMany relationship - TypeError: Field 'id' expected a number but got <Profile: user1>
I am making a recommendation app where a user can recommend a movie/show/book to one or more users. The form is set up so that it displays a list of all users and you can check a box next to the users you want to send the recommendation to, but I am getting this error (Field 'id' expected a number but got <Profile: user1>) when I hit "Submit" on my form after checking the box next to the username and I'm not sure where I went wrong. Most of the other questions related to this are using ForeignKey rather than ManyToManyField in their model. models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField( 'self', related_name='followed_by', symmetrical=False, blank=True, ) def __str__(self): return self.user.username class Recommendation(models.Model): user = models.ForeignKey( User, related_name="recs", on_delete=models.DO_NOTHING ) recipients = models.ManyToManyField( User, related_name="received_recs", symmetrical=False, blank=True ) title = models.CharField(max_length=300) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return ( f"{self.user} " f"({self.created_at:%y-%m-%d %H:%M}): " f"{self.title}" ) views.py: from django.shortcuts import render, redirect from .models import Profile, Recommendation from .forms import RecForm def dashboard(request): all_recs = Recommendation.objects.all() if request.method == "POST": … -
Is it bad written my custom authentication backend in Django?
I'm trying to implement a custom authentication backend in Django, mi custom Auth model and my custom user creation form works ok, but when I'm try to login using my custom authentication backend, it raise me this excepcion. Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Projects\revenue\authentication\views.py", line 12, in login usuario = UsuarioAuthBackend.authenticate(request, email=email, password=password) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: UsuarioAuthBackend.authenticate() missing 1 required positional argument: 'request' [09/Jun/2023 10:47:15] "POST /login/ HTTP/1.1" 500 66119 It tells me that I got 1 missing required positional argument, the request. But that argument was passed in the code, I'll share you my code. The Custom User Model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # choices CALIFICACION_USUARIO_CHOICES = [ (0,0), (1,1), (2,2), (3,3), (4,4) ] # Create your models here. class UsuarioManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('El usuario debe tener un correo electrónico') email = self.normalize_email(email) usuario = self.model(email=email, **extra_fields) usuario.set_password(password) usuario.save(using=self._db) return usuario def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, … -
Why is my django application on cpanel only recognising the root url and not any other url after the root url?
I recently deployed my Django application on a subdomain through Cpanel. However, when I try to access the application, only the root url is working. Any other address is not being sent. In the browser, anything after the / of the root url is grayed out and the logs of the application also suggest they are not receiving the entire address. I have attached screenshots herein for clarity. Any help will be appreciated. -
Django DB issue (Interface error: connection closed)
Calling all Pythonistas! I'm embarrassed to say, but this issue has been plaguing us for 3 weeks! It's intermittent with no rhyme or reason. Ubuntu 22.04 running Docker containers (uses the solid cookiecutter-django) as a base which we've used successfully for many years. django==4.1.9 gunicorn==20.1.0 psycopg2==2.9.6 When submitting a simple registration form, randomly, but very frequently we get the following error: InterfaceError connection already closed This issue is ALWAYS at django/db/backends/postgresql/base.py in create_cursor at line 269 which is cursor = self.connection.cursor() In Sentry it shows as a "System" error, not an "In-App" error (ie - code flaw). The form: class GuestForm(forms.ModelForm): time = forms.ChoiceField(choices=[]) # time = forms.ChoiceField(choices=[("18:30", "6:30 PM")]) class Meta: model = Guest fields = ["first_name", "last_name", "email", "opt_in"] def __init__(self, *args, **kwargs): logger.debug("=> Init GuestForm") super().__init__(*args, **kwargs) self.fields["time"].choices = get_choices() def clean_time(self): """Return a time.""" cleaned_data = super().clean() hours, minutes = cleaned_data["time"].split(":") try: return datetime.time(int(hours), int(minutes)) except ValueError as exc: raise ValidationError( "Invalid value: %(hours)s %(minutes)", code="invalid", params={"hours": hours, "minutes": minutes} ) from exc The view: class RegisterView(FormView): form_class = GuestForm template_name = "tour/register.html" tourgroup = None @transaction.atomic def form_valid(self, form): """While we are creating a Guest, we are ultimately creating a TourGroup.""" # Create or get … -
Django admin _continue and _addanother not working
I have 3 buttons in django admin: save, save and add another, save and continue. They have their input names in html like _save, _addanother and _continue. All of these buttons do the same thing - save model and redirect to the main page (like when I click on the save button) class StudyFormAdmin(admin.ModelAdmin): list_display = ['name'] fields = ['name'] I found out that response_add method contains redirect functionality (https://github.com/django/django/blob/ef62a3a68c9d558486145a42c0d71ea9a76add9e/django/contrib/admin/options.py#L1316). Then I tried to check what in my request.POST. I add these lines to my model: def response_add(self, request, obj): print(request.POST) return super().response_add(request, obj) Output: <QueryDict: {'csrfmiddlewaretoken': ['2IOoriUmt5IzfIKU7MY53hZ9dgupnM3sNU6ltcaKXXzwmDB73xekyXn55Pw197dF'], 'name': ['adfgdfg']}> I have tried all these buttons for each model I have but response always the same -
How to Fill in django form with a json file?
I'm building a django system that will receive a file and will return a json file and some graphics. The graphics is working but now and i need to fill in a django form with a json file. Basically, when the user make the upload a django form will filled and after that the graphics will return. How can i do that ? -
Django ModelForm CharField changed to ModelChoiceField results in not filled in values in edit mode
I have a model that has owner as CharField that should "house" the username of the owner of the object. I am using a ModelForm to create the form to create the object and the same to edit it later on. Now I want this owner field to be a choice field with the usernames of the current users. This is easily done by adding owner = forms.ModelChoiceField.... to the ModelForm. This works for creating new objects. Now when editing (going to the /{object_id}/edit link using a GET request) the object I call the ModelForm with the object instance. All fields are then nicely filled in except for my owner field, that just shows the default '-----' and you have to reselect it again. What I want is that that field is filled in with the value it currently is and I can then change it if I want based on the choices of current users. Just to preempt this answer: I do not want to make owner a ForeignKey relationship with user. My minified code: Model: class MyObjects(models.Model): owner = models.CharField(max_length=1024, blank=True) Form: class MyModelForm(ModelForm): owner = forms.ModelChoiceField(queryset = User.objects.all().only('username') def __init__(self, *args, **kwargs): super().__init__....... <bunch of code for … -
How to annotate Django models with new field based on existing fields?
I have Django models with a text field that is just a string. In views, I want to create a new field using annotate with the new fields being a comparison that compares the string of each of these objects text fields with another string, and ordering the queryset by that newly made comparison field. First I have this to get only objects that at least contain the other string: queryset = textObject.objects.filter(text_icontains=queryString) The next part is where I am confused. How can I access each objects text field from this queryset so that I can make a new field with annotate based on these comparisons? -
How display Average Ratings on several pages in Django
Am trying to display the Average ratings on other pages in Django, but it fails. Below its my code. models.py class ActionGame(models.Model): publication_status = models.CharField(max_length=20, choices=STATUS, default="Draft") cid =ShortUUIDField(help_text='Place for the Game ID ', unique=True, max_length=10, length=7, prefix='act',alphabet='abcdfgh12345' ) game_name = models.CharField(max_length=50, help_text='Enter The Name Of Game') game_image = models.ImageField(help_text='Enter The Game Picture Here',default='Action-images/default.jpg',upload_to='Action-images') RATING=[ (1,"★"), (2,"★★"), (3,"★★★"), (4,"★★★★"), (5,"★★★★★"), ] class ActionGameReview(models.Model): game_name =models.ForeignKey(ActionGame, on_delete=models.CASCADE, related_name='reviews') user =models.ForeignKey(User, on_delete=models.CASCADE) review =models.TextField(max_length=5000, blank=False) rating = models.IntegerField(default=1, choices=RATING) created_at=models.DateTimeField(auto_now_add=True) Views.py def action_description(request, cid): description=ActionGame.objects.get(cid=cid) #getting Average Review avg_rating=ActionGameReview.objects.filter(game_name=ActionGame.objects.get(cid=cid)).aggregate(rating=Avg('rating')) # ...... def action(request): action_pages = ActionGame.published.all() # ..... The issue is, l cant display the ratings average in the action view template yet on the action-description Works veryfine. how can l imprement the Average Rating on other pages, Anyone to help me. -
Django Templates: Render a dictionary object stored in a context object?
In Django I have a dictionary object like this: car = { 'color': 'red', 'doors': 4 } I would like to store this dictionary in an Django ORM Model class like so: class Things(models.Model): car = models.TextField() ... other fields My template is a view for Things. Is it possible to access values for car in the template a way such as this: Car color: {{ things_object.car.color }} Note, it is not a requirement to use TextField to save the car dictionary. -
Let Django access serial port in Lubuntu
So, I need my Django to access the serial port I'm correctly using it via pyserial package the issue is that, every time I boot the OS I got the error of Access denied. The only way to make it work is to grant access to the specific serial for everyone via sudo chmod 666 /dev/ttyUSB0 Is there a way to let Django access the serial anyway, instead of let eveyone access it with 666?