Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I indicate ManyToMany relationship in Django models when both are primary keys?
I'm creating Django models and I'm having an issue designating a ManyToMany relationship so that a join table is created in the database. The two models I'm trying to join look like this: class Host(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio_information = models.ForeignKey(Bio, on_delete=models.CASCADE) class Team(models.Model): name = models.CharField(max_length=50) creator = models.ForeignKey(Host, on_delete=models.CASCADE) They need to join on the primary keys, so that I end up with a join table that looks like this with the table name host_team: id int [PK] host_id int team_id int Since you don't include the ID when creating models, how do I designate the MtoM relationship and get django to create the join table? -
Onetimesecret on django rest
I trying to do service onetimesecret(https://onetimesecret.com/) on DRF. I dont know, how I can add code word to get the phrase.I will be very glad, if you help me models.py class Secret(models.Model): """ Secret """ secret = models.TextField() # Поле для ввода секрета code_word = models.CharField(max_length=22) # Поле для ввода кодовой фразы slug = models.SlugField(max_length=255, unique=True, verbose_name='URL') def __str__(self): return f'{self.id} = {self.code_word}' def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) views.py from rest_framework import generics from rest_framework.response import Response from rest_framework.views import APIView from .logic import link_generate from .models import Secret from .serializers import SecretSerializer class SecretCreateView(generics.CreateAPIView): serializer_class = SecretSerializer def post(self, request, *args, **kwargs): serializer = SecretSerializer(data=request.data) if serializer.is_valid(): serializer.validated_data['slug'] = link_generate() serializer.save() return Response({ 'Slug': serializer.validated_data['slug'], }, status=201) return Response(serializer.errors, status=400) class GetSecretViewSet(APIView): def get(self, request, slug): secrets = Secret.objects.get(slug=slug) serializer = SecretSerializer(secrets) return Response(serializer.data) -
Django only reading some environmental values
I have a Django project deployed with Docker, and now the project doesn't load all my environmental values specified in the .env file. Only some of them are read. This is my .env file: DJANGO_DEBUG=changeme(1/0) DB_NAME=changeme DB_USER=changeme DB_PASS=changeme SECRET_KEY=changeme EMAIL_PASSWORD=changeme EMAIL=email@example.com DOMAIN=example.com And in setting.py I access the values that way: DEBUG = bool(int(os.environ.get('DJANGO_DEBUG', 0))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), } } EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com.' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') All the database related values are read properly as well as the secrey key. But the rest of the values are not read, and I don't understand why. Which could be the problem? -
Google Places API - Autocomplete not firing
I asked a question on the same topic a couple of days ago, but made some progress (I found some code) so I thought I would create a new question. I am still trying to input the Google Places API into a form for businesses. I tried all sorts of combinations from the various posts I have seen on here, but still no luck. So it's likely I am either missing something or have made a typo that I cannot spot. Starting with the JavaScript file In a very simple version of the file, calling auto complete works. function initAutocomplete(){ autocomplete = new google.maps.places.Autocomplete(document.getElementById("autocomplete"),{ componentRestrictions: {'country':['uk']}, fields: ['name','geometry','address_components'], types:['establishment','geocode'] }); autocomplete.addListener('place_changed'); } (I do get a message saying "Uncaught TypeError: Cannot read properties of undefined (reading 'apply')" but I still get a return) However, I soon as I start adding more code, something breaks and I am told that "initAutocomplete is not a function". I found a solution to that. Reading a few post on here, an easy way to get rid of this message is simply to get rid of "&callback=initAutocomplete" at the end of the script. But a new problem turns up: the auto complete simply doesn't fire … -
why i am getting error while installing package from requirement file in django
Hi Everyone i have clone my django project on ubuntu machine(22.04.1 LTS) python version is- 3.8.10 and django version is 2.2 while installing packages using cmd pip install -r requirements.txt then after installing some packages i got error, as per me this is mysqlclient error Note-mysql db working fine. please help me out. Error Collecting mysqlclient==2.0.3 Using cached mysqlclient-2.0.3.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-490urkf8/mysqlclient_91ecf52f39004862be75d78177e00bdb/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-490urkf8/mysqlclient_91ecf52f39004862be75d78177e00bdb/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-490urkf8/mysqlclient_91ecf52f39004862be75d78177e00bdb/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. … -
Create a view with two functionalities so that it can all be in one template?
I need my template to display an edit button after the comment is done but I have no idea on how I could and should do that. Is it a view or a method in FeedbackView that I shoul make? Usually I would a view for each action but wouldn't it require me to do a different template for each one of the views? Also, how can a user be restricted to only doing one comment? # VIEW class ProductFeedbackView(DetailView): model = Product template_name = 'store/product_feedback.html' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) connected_comments = Comment.objects.filter(product=self.get_object()) number_of_comments = connected_comments.count() data['comments'] = connected_comments data['no_of_comments'] = number_of_comments data['comment_form'] = CommentForm() return data def post(self , request , *args , **kwargs): if self.request.method == 'POST': comment_form = CommentForm(self.request.POST) if comment_form.is_valid(): content = comment_form.cleaned_data['content'] new_comment = Comment(content=content, author=self.request.user, product=self.get_object()) new_comment.save() return redirect(self.request.path_info) # FORM class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] # MODEL class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=False, blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date'] # TEMPLATE {% if user.is_authenticated %} <form action="" method="POST" id="main_form"> <div> <label for="comment">Type comment</label> {{ comment_form }} {% csrf_token %} … -
django-dramatiq pipelines only run first stage
I am trying to use django-dramatiq to run a pipeline of several stages, each defined as dramatiq Actors, using the pipeline(<stages>).run() method but it's only running the first stage/Actor and not attempting the other stages. I've defined some cutdown fake actors to illustrate the problem: import dramatiq @dramatiq.actor def fake_extract(process_pk, *args, **kwargs): print(f"fake_extract: Process PK= {process_pk} Running extract on {kwargs['fits_file']}") @dramatiq.actor def fake_astromfit(process_pk, *args, **kwargs): print(f"fake_astromfit: Process PK= {process_pk} Astrometric fit on {kwargs['ldac_catalog']}, updating {kwargs['fits_file']}") @dramatiq.actor def fake_zeropoint(process_pk, *args, **kwargs): print(f"fake_zeropoint: Process PK= {process_pk} ZP determination on {kwargs['ldac_catalog']} with {kwargs['desired_catalog']} ref catalog") I've then defined the stages and built a pipeline: import os from dramatiq import pipeline from test_dramatiq.dramatiq_tests import fake_extract, fake_astromfit, fake_zeropoint fits_filepath = '/foo/bar.fits' fits_file = os.path.basename(fits_filepath) steps = [{ 'name' : 'proc-extract', 'runner' : fake_extract, 'inputs' : {'fits_file':fits_filepath, 'datadir': os.path.join(dataroot, temp_dir)} }, { 'name' : 'proc-astromfit', 'runner' : fake_astromfit, 'inputs' : {'fits_file' : fits_filepath, 'ldac_catalog' : os.path.join(dataroot, temp_dir, fits_file.replace('e91.fits', 'e91_ldac.fits')), 'datadir' : os.path.join(dataroot, temp_dir) } }, { 'name' : 'proc-zeropoint', 'runner' : fake_zeropoint, 'inputs' : {'ldac_catalog' : os.path.join(dataroot, temp_dir, fits_file.replace('e91.fits', 'e92_ldac.fits')), 'datadir' : os.path.join(dataroot, temp_dir), 'desired_catalog' : 'PS1' } }] pipes = [] for step_num, step in enumerate(steps): inputs = step['inputs'] print(f" Performing pipeline step {step['name']}") pk … -
AWS public ip refused to connect on broswer even tho docker-compose is running fine and all traffics are allowed
I have onfigured all the security groups ports and address, i can connect to the ec2-user from my terminal. when i run docker-compose up --build it fires up successfully, but the ip 13.36.211.140 ec2-13-36-211-140.eu-west-3.compute.amazonaws.com resfuse to connect on the browser. These are all the rules i have i have also read many stackoverflow and blog posts to fix this, i have added many rules to accept ports as you can see below. What might be the best fix for this? I know i am definitely missing something... this is my docker-compose.yaml file version: '3' services: django_app: build: . env_file: - .env volumes: - static_vol:/app/static - media_vol:/app/media ports: - "8000:8000" nginx: build: ./nginx volumes: - static_vol:/app/static - media_vol:/app/media ports: - "80:80" depends_on: - django_app volumes: static_vol: media_vol: Updated >>>>>>>>>>>>>>> when i change the url to http, the url turns to https://django/ this is how it looks -
Deploy django with SQL Server on host [closed]
I want to deploy my first django app on host but everywhere i read documentation about deploying django with sqllite -
Getting M2M field data in template Django
I want to get m2m data in my template through the views but failing to do so. The thing is that I'm able to show the data of m2m field looping it from template itself but it does slow down the website. My Team apps Model looks like this: class Team(models.Model): title = models.CharField(max_length=255) team_country = CountryField(max_length=200, blank=True, null=True) members = models.ManyToManyField(User, related_name='teams') created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE) Now in my tournament app I'm trying to get "members" of the team. My Tournamet Views look like this: def tournament_page(request, slug): page = 'tournament_page' user = request.user tournament = Tournament.objects.get(slug=slug) players = tournament.participants.select_related('user') all_players = Profile.objects.select_related('user') side_tourneys_ongoing = Tournament.objects.filter(state='Ongoing')[:10] side_tourneys_upcoming = Tournament.objects.filter(state='Upcoming')[:10] side_tourneys_completed = Tournament.objects.filter(state='Completed')[:10] teams = Team.objects.select_related('created_by') context = { 'page': page, 'tournament': tournament, 'side_tourneys_ongoing': side_tourneys_ongoing, 'side_tourneys_upcoming': side_tourneys_upcoming, 'side_tourneys_completed': side_tourneys_completed, 'teams': teams, 'players':players, 'all_players':all_players } Now I'm able to show the teams with their members in the template using for loop inside the template itself as: Html template <div class="grid-x"> {% for team in teams %} {% for player in players %} {% if team.id == player.active_team_id and team.game == tournament.game %} <div class="wf-card event-team"> <div> {{team.title}} </div> <div class="event-team-players"> {% for member in team.members.all %} {{ member.username }} {% … -
Refuse connect to my local server database MySQL
I working with a project in Python and Postgress And I should had a methode to connect to db from MySQL I write this function def connexion (): db = mysql.connect( host = "localhost", user = "root", passwd = "", database = "Test", port ="3306" ) return db when I call this function to verify linking database I had this error raise exception.with_traceback(None) from new_cause mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused) What I should I do to make this connection validated RQ: I'm sure about name and port number -
Django filter query when two datetime columns have same date
I want to filter a Django queryset when two datetime columns have the same date. I have tried the following two codes that do not work : drivers = drivers.filter(deleted_at__date=F("created_at__date")) and drivers = drivers.filter(deleted_at__date=F("created_at")) -
Reverse for 'app_list' with keyword arguments '{'app_label': 'common'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|otp_totp)/$']
config/urls.py from django_otp.admin import OTPAdminSite from django.contrib.auth.models import User from django_otp.plugins.otp_totp.models import TOTPDevice from django_otp.plugins.otp_totp.admin import TOTPDeviceAdmin class OTPAdmin(OTPAdminSite): pass admin_site = OTPAdmin(name='OTPAdmin') admin_site.register(User) admin_site.register(TOTPDevice, TOTPDeviceAdmin) urlpatterns = [ re_path(r'^admin/', admin_site.urls) ] common/admin.py from common.models import ConfigVar, ConfigVarFile, Source from config.urls import admin_site admin_site.register(ConfigVar) admin_site.register(ConfigVarFile) admin_site.register(Source) error {"@timestamp": "2022-08-24T16:21:04.889396Z", "ecs.version": "1.0.0", "log.level": "ERROR", "message": "Internal Server Error: /admin/", "process.thread.name": "Thread-1", "log.logger": "django.request", "fileName": "log.py", "funcName": "log_response", "lineNo": 241, "spanId": "d5bb9ad916674801", "traceId": "d5bb9ad916674801", "error.type": "<class 'django.urls.exceptions.NoReverseMatch'>", "error.message": "Reverse for 'app_list' with keyword arguments '{'app_label': 'common'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|otp_totp)/$']", "error.stack_trace": "Traceback (most recent call last):\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/core/handlers/exception.py\", line 55, in inner\n response = get_response(request)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/core/handlers/base.py\", line 197, in _get_response\n response = wrapped_callback(request, *callback_args, **callback_kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 261, in wrapper\n return self.admin_view(view, cacheable)(*args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/utils/decorators.py\", line 133, in _wrapped_view\n response = view_func(request, *args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/views/decorators/cache.py\", line 62, in _wrapped_view_func\n response = view_func(request, *args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 242, in inner\n return view(request, *args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 553, in index\n app_list = self.get_app_list(request)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 537, in get_app_list\n app_dict = self._build_app_dict(request)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 519, in _build_app_dict\n \"app_url\": reverse(\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/urls/base.py\", line 88, in reverse\n return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/urls/resolvers.py\", line 802, in … -
A shutdown hook for Django with mod_wsgi
I have a simple Django server that runs and manages some services in the backgrounds. I want to stop those services when the server stops. After looking online, I have found this solution: signal.signal(signal.SIGINT, _stop_services) And it works great when I run the server with python manage.py runserver. But, when I run the server with Apache engine and mod_wsgi and restarting/stopping the apache server, the callback is not invoked. I also tried using SIGTERM and even the atexit module, but none of them worked. Is there any built-in solution in Django for this? I know that in packages like aiohttp you can add a listener that will be called when the server shuts down. -
How to make create and retrieve work in the same serializer?
i have a somewhat tangled problem, I have the following models class ModelA(models.Model): name = models.CharField(max_length=64) class ModelB(models.Model): model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) and the serializers class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = '__all__' class ModelBSerializer(serializers.ModelSerializer): terminal = ModelASerializer(read_only=True) class Meta: model = ModelB fields = '__all__' when I want to create a ModelB object including the model_a_id it has 2 responses depending on whether I put the read_only=True or False I would like that when I try to create via POST in an object of ModelB I only have to send the mode_a_id, but at the same time when I do a GET it returns the serialized data of ModelASerializer in the model_a field. If I put the read_only = True it only works to receive the serialized data in GET, but via POST I cannot assign an id to model_a in case of read_only=False, I can't assign the id to that object either since it asks me for a dictionary, I imagine to create a new ModelA Object, but I only want to assign one that already exists. A solution may be to place the serializer with another variable name, but I would really like it to … -
show dynamic data from form value change in template
I'm new to django, i'm used to angular. i'm trying to do something that make sense to me in angular and I can't achieve in django. I'm working with python 3.9 and django 4.1 I simplified my case to this.. I have a form that I created and and a view for it, i have a select element, whenever i select something, i want to show what i selected. so I created a LocationForm form class: class LocationForm(forms.Form): apartment_type = forms.ModelChoiceField(queryset=ApartmentType.objects.all()) apartment type is just a list of apartment types (building, apartment, garden and so on) i past the form to the view: def location(request): context = {'form': LocationForm} return render(request, 'prospects/location.html', context) and the code for the view: {% load static %} <form> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> CCC{{ form.apartment_type.value }}DDD<br/> the problem is that no matter what I select, form.apartment_type.value still shows None, it's not being updated. i guess i'm used to angular too much but this issue is really alarming for me if django only parses things statically, i guess i'm not used to it and i have no idea how to resolve it otherwise. in my full code i want to … -
Fcm-Django IOS no sound
So everything works fine in terms of notifications being sent. however, no sound gets played when a notification is delivered to an IOS device I am using fcm-django as the package. here is the code I use: myself is just the user sending the notification to. fcmdevicee = FCMDevice.objects.get(user=usertosendto) fcmdevicee.send_message(Message( notification=Notification( title=f"{myself.username}new notification") )) -
Django- Only pulling through the base template when trying to extend
I'm making my first Django app and I'm trying to set up my signup.html page while extending my base.html. The URL I have configured works, however it only pulls through the base.html template. I've checked the view, url and the signup.html template and I'm not sure what I'm getting wrong. signup.html: {% extends './layout/base.html' %} {% load static %} {% block content %} <h1>Signup</h1> {% endblock content %} base.html: <!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"> {% load static %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300&family=Oswald&display=swap" rel="stylesheet"> <link rel="icon" href="{% static 'favicon.ico' %}"> <a target="_blank" href="https://icons8.com/icon/DpuVIej1M9Br/health">Health</a> icon by <a target="_blank" href="https://icons8.com">Icons8</a> <title>Your Health Now</title> </head> <body> <h1>Hello, world!</h1> </body> </html> urls.py: from django.urls import path from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView from . import views app_name = 'HealthHub' urlpatterns = [ path('signup/', views.signup, name='signup'), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))) ] views.py: from django.shortcuts import render def signup(request): return render(request, 'HealthHub/signup.html') -
Django query with TruncHour for multiple product with each group latest sum. How to do that?
The scenario is: The product database price update every hour. People can add product to wishlist. Wishlist page has some graph. That shows last 24 hours price changes. I want to show every hour price change of all his wishlist product for last 24 hours. I am trying but I can't complete the query. What I am trying is given below: now = datetime.datetime.now() last_day = now - datetime.timedelta(hours=23) x = ( FloorPrice.objects.filter( product__in=vault_products_ids, creation_time__gte=last_day ) .annotate(hour=TruncHour("creation_time")) .values("hour", "floor_price") ) Suppose I add in wishlist 4 product. Now I want each hour 4 products sum with that hour latest entry(each hour each product has multiple floor price, so we need to pick the last entry of each product on that hour). -
Can't insert an element to a MS SQL Server table without identity field in Django
I have a legacy table in MS SQL Server in which the ID is not an identity field, and I can't insert entities because it hasn't an identity property. In order to find the error I created a new table with the same characteristics and just two fields: ID and name. When I try to insert a record I get the same message: Table 'base_test' does not have the identity property. Cannot perform SET operation. (8106) (SQLExecDirectW) If my table has an identity record it inserts it correctly. I tried with ODBC Driver 17 for SQL Server, ODBC Driver 13 for SQL Server, pydobc, mssql, always the same message. Is it possible that the ODBC driver is not prepared for this situation? -
django form errors not showing on template
I'm using the basic django registration form and I'm not getting any errors displayed. I've seen a bunch of answers and nothing is working for me. I'm not sure if it's because I have custom css for the page or bootstrap or something else. Basically how do I display the errors in this particular case. Here's my form: <div class="form-content"> <h1>Sign Up</h1> {% if user.is_authenticated == False %} <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn form-btn">Sign Up</button> <h4><span>or</span></h4> <a class="btn google-btn" href="{% provider_login_url 'google' %}" role="button" style="text-transform: none; width: 100%" > <img width="20px" style="margin-bottom: 3px; margin-right: 5px" alt="Google sign-in" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png" /> Sign up with Google </a> </form> {% else %} <p>You're already registered...</p> {% endif %} </div> Here's my view: class UserRegistration(generic.CreateView): form_class = RegisterForm template_name = 'registration/registration.html' def form_valid(self, form): user = form.save() form.registration_notification() login(self.request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect(self.request.GET.get('next')) and form: class RegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def registration_notification(self): email = self.cleaned_data['email'] username = self.cleaned_data['username'] if self.is_valid(): registration_notification_task.delay(email, username) I'm not sure where to return the errors or where to validate the form and no answers for other questions have … -
Django Error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
I'm having some problems when running django on my machine, even though it's inside the virtual machine it accuses an error, I'm using macOS. Below is an image of my manage.py Print screen Manage.py -
Django Admin changelist submit redirect
Is it possible to have django redirect to another page after submitting changes directly in the changelist view? (After specifying the list_editable fields) Already tried with different methods response_post_save_change, response_change or response_add but none of them worked. I suspect it may be within the changelist_view, not sure how to tackle it since it handles the form saving. -
Django filter using Conditional Expressions
I have a model (let's say class Foo) that holds 2 important attributes and each attribute can have one of the two values, here is some pseudocode: period_condition = cons.BEFORE or cons.AFTER period_days = const.START_DATE or cons.END_DATE Now, I need to construct a filter dynamically based on those 2 values. I can do it with if-else but it seems pretty ugly and hard to read/follow: def list_subscriptions_for_sending(foo: Foo) -> QuerySet[Subscription]: days = foo.days if foo.period_condition == BEFORE: if foo.period_date == START_DATE: filter = Q(start_date=get_today() + timedelta(days=days)) if foo.period_date == END_DATE: filter = Q(end_date=get_today() + timedelta(days=days)) if foo.period_condition == AFTER: if foo.period_date == START_DATE: filter = Q(start_date=get_today() - timedelta(days=days)) if foo.period_date == END_DATE: filter = Q(end_date=get_today() - timedelta(days=days)) I was trying using Case and When - then Django's conditional expressions, but was getting the following error: *** TypeError: Cannot filter against a non-conditional expression. I cannot understand how the expression is non-conditional. In my understanding, it goes through each When of the Case and if the expression is True it assigns the Q expression from then : filter = Case( When( Q( foo.period_condition == BEFORE ) & Q( foo.period_date == START_DATE ), then=Q(start_date=get_today() + timedelta(days=days)), ), When( Q( foo.period_condition == BEFORE … -
How to get an attribute of a dictionary in a Django template?
I am trying to parse RSS feeds with a Django app. So far it works, but I can't get the images in the feeds to be shown. My views.py looks like this: from django.shortcuts import render from web.models import airline, world import feedparser from django.http import HttpResponse def news(request, selection): news = ['https://www.aerotelegraph.com/feed', 'https://www.aviationweek.com/rss.xml', 'https://www.airway1.com/rss'] selection = news[selection] feeds = feedparser.parse(selection) context_dict = {} context_dict['url'] = feeds.feed.link context_dict['titel'] = feeds.feed.title context_dict['feeds'] = feeds return render(request, 'web/news.html', context=context_dict) My template news.html looks like this: {% load static %} {% block body_block %} <h4>News from <a href="{{ url }}" target="news">{{ titel }}</a></h4> <ul class="list-group"> {% for entry in feeds.entries %} <li class="list-group-item"> <a target="news" href="{{entry.link}}"><b>{{entry.title}}</b></a><br> <img src="{{entry.image}}{{entry.media_content}}" width="250"><br> <p>{{entry.description}}</p> </li> {% endfor %} </ul> {% endblock %} Now instead of the actual image, it inserts the following string. [{'url': 'https://aerotelegraph.imgix.net/production/uploads/2022/08/brussels-a330.png?auto=compress%2Cenhance%2Cformat&ch=Save-Data&crop=edges&dpr=1&fit=crop&h=316&w=653&s=7e73358df59ca8274c54497fbe55ed6c', 'medium': 'image'}] This looks like a dictionary object, but I have tried to do the following variants, but all come up with an error. <img src="{{entry.image}}{{entry.media_content[0]['url']}}" width="250"><br> <img src="{{entry.image}}{{entry.media_content['url]}}" width="250"><br> <img src="{{entry.image}}{{entry.media_content.['url']}}" width="250"><br> <img src="{{entry.image}}{{entry.media_content.url}}" width="250"><br> It kees saying TemplateSyntaxError at /web/news/2, Could not parse the remainder: '[0].['url'] from 'entry.media_content[0].['url'] (or similar with the other variants). Is it possible to get that …