Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Objects created from celery task not firing django post_save signal
I have a celery task that creates a modal object. I'm trying to run some code after the object is created using django post_save signal. but for some reason, the signals are not firing. models.py class Alert(models.Model): description = models.TextField() @receiver(post_save, sender=Alert, dispatch_uid="create_jira_issue") def create_issue(sender, instance, **kwargs): //do something here tasks.py @shared_task def create_alert(): Alert.objects.create() this is how the code looks like. the Objects are being created through the celery task. but it's not triggering the post_save signal. any input is appreciated. -
crontab not getting my current envrioment variables
I want a cron job and everything is already set up and cron is also working but unfortunately, cron is not getting my environment variables. I'm getting my environment variables using os and they're working fine across the project but not in my cron. settings.py SECRET_KEY = os.environ.get('SECRET_KEY') # Cron Jobs CRONJOBS = [ ('* * * * *', 'projects.cron.notifications_cron', '>> /cron/django_cron.log 2<&1') ] crontab -e * * * * /usr/local/bin/python /app/manage.py crontab run 744fbefdbf3ad30bec13 error in log file raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") when I set the SECRET_KEY hardcoded in my settings.py then it is working fine but I want to get it from my environment variables. -
Django all-auth allow users to login allow only business emails
I am using the django-allauth, but it is allowing the all gmail accounts is there any way that we can restrict . only allow business emails like venkatesh@xyz.com instead of all@gmail.com -
Django: select_related query is ignored and the related queries are still executed
I have a menu model with the following fields: class MenuItem(models.Model): name = models.CharField() parent = models.ForeignKey(self, ...) and 2 serializers: class MenuItemSerializer(serializers.ModelSerializer): children = serializer.SerializerMethodField() class Meta: model = MenuItem def get_children(self, data): return MenuItemSerializer(data.children, many=True).data class MenuSerializer(serializers.Serializer): first_menu = serializer.SerializerMethodField() def get_default(self, __): return MenuItemSerializer(MenuItem.objects.filter(...).select_related("parent")), many=True).data I add a select_related to the menu item query, thinking that this should filter the menu items and then retrieve their children as well but there are a lot of queries executed. The first one is the join, but then there are 20+ other where each menu item is retrieved by id. Why isn't this working? -
Django customer user model and connexion
Hello, I'm developing a shop with Django [3.2] I would like to develop a login system for my customers so that they can see their invoices, pay online. I'm looking for documentation on how to manage their password but each time I come across back office user management. I obviously don't want my clients to have access to the back office. Should we make entries in the back office user table for front-end users (customers) and give them no right or should we develop a custom system. Are there things planned in Django for my case? Thanks a lot -
Setting up a working environment and using Django for Python on a Mac
I'm very new to programming especially on a Mac (only started using the terminal today). I need to set up python on this new Mac and setup virtual environments, then use Django to create simple Journal App. I have tried following various guides however I seem to struggle whenever I am asked to edit files as I don't know which files to edit, what their path is etc. I am using zsh not bash which makes a lot of guides redundant and I am using my work MacBook so I cannot change some of those settings. I have installed python 3.10 however my terminal still wants to use the default 2.7 which it had already, I have also installed honeybees, pip, Django, and some various other things these guides have instructed me to do. However I have no idea how this pathing stuff works and every time I try to use Django it essentially just doesn't recognise that I Have it installed. What I'm really asking for is a step by step guide to setting up Python and Working environments, (bearing in mind I'm unclear on how the pathing works) and then to use Django frameworks. If this is poorly … -
How to Integrate Product bundle like amazon buy it with in Django e-commerce site
i have built e-commerce site in django framework i want integrate one feature bundle like amazon buy it with feature is there any idea how to do like table relation and strategy. -
Creating a field in a model that allows multiple entries that is saved to the DB incrementally
I have a model called Handoff, users create a new handoff everyday and will add notes to this handoff to pass over to the next shift. I need a field that can capture user entry and save to the DB, but this field needs to be able to write to the database iteratively. For context, the user will add a new note each time they have something to add to the handoff and this needs to be written to the DB individually (for example, if the field was called new_note, the data should write to the DB and each new note will be saved as new_note_1). These notes will then be collated in a table to present to the next shift during a handoff. What are the best methods for approaching this? -
How to annotate django complex queryset
I want to have count of usecases. I have three models Customer (all users records), Usecase (all usecases records) and CustomerUsecaseAssociation (users and subscriptions records). I want to count the subscriptions of each usecase subscribed by users. and I want the union of two or more usecase if customers subscribed two amoung them. Models Class Customer(models.Model): customer_name = models.CharField(max_lenght=50) class Usecase(models.Model): usecase_name = models.CharField(max_lenght=50) class CustomerUsecaseAssociation(models.Mode): customer = models.ForignKey(Customer, on_delete=models.CASCADE) usecase = models.ForignKey(Usecase, on_delete=models.CASCADE) Preloaded Customer id customer_name 1 abc 2 efg 3 hij Usecase id usecase_name 1 AT 2 BT 3 CT CustomerUsecaseAssociation id usecase customer 1 1 1 2 2 1 3 2 2 4 3 3 Desired Output [ { "usecase_name": "AT-BT", "subscriptions": "1" }, { "usecase_name": "BT", "subscriptions": "1" }, { "usecase_name": "CT", "subscriptions": "1" } ] Notes I will highly recommend annotation if anyone would help me. -
Displaying Django form answers
I couldn't find a solution to this on the Django website, currently I have a form as shown: It saves to my models.py like the following: What I want to do is use the answers from a form and create a new form using the answers of this form as the questions for it, basically recreating this form and reusing the fields but changing the fields and displaying it on a unique URL class InitialForm(forms.Form): Teacher_Name = forms.CharField(label='Teacher Name') Test_Name = forms.CharField(label='Label this test') Subject = forms.CharField(label = 'Subject') Question = forms.CharField(label = 'What is the first question?') Topic = forms.CharField(label = 'What topic is this on?') Option1 = forms.CharField(label = 'What is the first option?') Option2 = forms.CharField(label = 'What is the second option?') Option3 = forms.CharField(label = 'What is the third option?') Option4 = forms.CharField(label = 'What is the fourth option?') Answer = forms.CharField(label = 'Which option is the correct option?', widget=forms.Select(choices=Options)) class Questions(models.Model): testID = AutoSlugField(unique=True) test_label = models.CharField(max_length=1000) teacherName = models.CharField(max_length=1000, null = True) studentID = models.ForeignKey(Student, on_delete=models.CASCADE, null = True) Subject = models.CharField(max_length=1000) Q1 = models.CharField(max_length=1000, null = True) Topic1 = models.CharField(max_length=1000) Option1_Q1 = models.CharField(max_length=1000) Option2_Q1 = models.CharField(max_length=1000) Option3_Q1 = models.CharField(max_length=1000) Option4_Q1 = models.CharField(max_length=1000) AnswerQ1 … -
Django Rest Framework Swagger Documentation
Good day everyone! I am writing a game application using Django and Django rest framework. I have been working on swagger documentation and the main problem is, that autogenerated schema is without any params. Here are examples of my realization: Tempaltes.html {% load static %} <!DOCTYPE html> <html> <head> <title>School Service Documentation</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url schema_url %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout" }) </script> Urls.py urlpatterns = [ path('api_schema/', get_schema_view( title='API Schema', version="3.0.0", description='Guide for the REST API', ), name='api_schema'), path('docs/', TemplateView.as_view( template_name='index.html', extra_context={'schema_url': 'api_schema'} ), name='swagger-ui'), path('admin/', admin.site.urls), path('game/', include('GameWorld.urls')) ] Views.py class EventDetailsView(GenericAPIView): serializer_class = serializers.EventDetailsSerializer """ hard_token event_type event_id = """ # schema = ManualSchema(fields=[ # coreapi.Field( # "hard_token", # required=True, # location="query", # schema=coreschema.String() # ), # coreapi.Field( # "event_type", # required=True, # location="query", # schema=coreschema.String() # ), # coreapi.Field( # "event_id", # required=True, # location="query", # schema=coreschema.Integer() # ), # ]) @auth def post(self, request, *args, **kwargs): event_id = request.data.get('event_id') for_user_events = engine_models.Event.objects.filter(owner__pk=request.user.pk) event = for_user_events.get(pk=event_id) return Response(event.data) As you can see in the post. I also tried to … -
How can I display a dynamic list of saved items in my application
I am trying to get Django to show the List of saved inputs from the user on the index page. ( I know my frankenstein-ed code is horrible, it has a lot of tiny bits of things I tried out and didn't get to work. I don't have much programming experience, I'm just trying to get this done for a graded project at my uni. ) The whole project should be a prototype for a food storage application, the user puts the food in via dropdown menu (I will expand it with subcategories e.g. Milk based food => cheese) and should be able to view what is in storage and be able to remove items. Right now I am getting stuck on making the list viewable by the user. Any help is much appreciated! Models.py from django.db import models # Create your models here. class FoodCategory(models.Model): MILK = 'MLK' VEGETABLE = 'VG' MEAT = 'MT' PASTA = 'PST' FRUIT = 'GR' FOOD_CATEGORY_CHOICES = [ (MILK, 'Milk based foods'), (VEGETABLE, 'Vegetables'), (MEAT, 'Meats'), (PASTA, 'Pasta'), (FRUIT, 'Fruits'), ] foodcategory = models.TextField( choices= FOOD_CATEGORY_CHOICES, default= MILK, ) class Meta: verbose_name = 'foodcategory' verbose_name_plural = 'food_list' def __str__(self): return self.foodcategory View.py class IndexView(generic.ListView): … -
PayTm payment gateway showing "KeyError at /payments/response/ 'CHECKSUMHASH'" in django
I am setting up paytm payment gateway for my django webapp. but I have a problem like this KeyError at /payments/response/ 'CHECKSUMHASH' . views.py def VerifyPaytmResponse(response): response_dict = {} if response.method == "POST": data_dict = {} for key in response.POST: data_dict[key] = response.POST[key] MID = data_dict['MID'] ORDERID = data_dict['ORDERID'] verify = Checksum.verify_checksum(data_dict, settings.PAYTM_MERCHANT_KEY, data_dict['CHECKSUMHASH']) if verify: STATUS_URL = settings.PAYTM_TRANSACTION_STATUS_URL headers = { 'Content-Type': 'application/json', } data = '{"MID":"%s","ORDERID":"%s"}'%(MID, ORDERID) check_resp = requests.post(STATUS_URL, data=data, headers=headers).json() if check_resp['STATUS']=='TXN_SUCCESS': response_dict['verified'] = True response_dict['paytm'] = check_resp # response_dict['pack_type'] = data_dict['PACK_TYPE'] return (response_dict) else: response_dict['verified'] = False response_dict['paytm'] = check_resp return (response_dict) else: response_dict['verified'] = False return (response_dict) response_dict['verified'] = False return response_dict @login_required def payment(request): order_id = Checksum.__id_generator__() pack_type = request.GET.get('pack_type') bill_amount = None if pack_type == '1': bill_amount = "199" elif pack_type == '2': bill_amount = "999" data_dict = { 'MID': settings.PAYTM_MERCHANT_ID, 'INDUSTRY_TYPE_ID': settings.PAYTM_INDUSTRY_TYPE_ID, 'WEBSITE': settings.PAYTM_WEBSITE, 'CHANNEL_ID': settings.PAYTM_CHANNEL_ID, 'CALLBACK_URL': settings.PAYTM_CALLBACK_URL, # 'MOBILE_NO': '7405505665', 'EMAIL': request.user.email, 'CUST_ID': '123123', 'ORDER_ID':order_id, 'TXN_AMOUNT': bill_amount, 'PACK_TYPE': pack_type, } # This data should ideally come from database data_dict['CHECKSUMHASH'] = Checksum.generate_checksum(data_dict, settings.PAYTM_MERCHANT_KEY) context = { 'payment_url': settings.PAYTM_PAYMENT_GATEWAY_URL, 'comany_name': settings.PAYTM_COMPANY_NAME, 'data_dict': data_dict } return render(request, 'payments/payment.html', context) @csrf_exempt def response(request): resp = VerifyPaytmResponse(request) if resp['verified']: # save success details to db; … -
'django model' object is not subscriptable
I get this error when I try to do a query set on the Django model 'AppUser' object is not subscriptable despite it is working normally in a print statement but the error only appears when I put it in an IF statement here is my code : def to_representation(self, instance): data = super().to_representation(instance) print("reached here") #print normaly print(AppUser.objects.filter(mobile=instance['mobile']).count() > 0) #print normally (False) if AppUser.objects.filter(mobile=instance['mobile']).count() > 0: # Raises an Exception if instance.playerprofile_set.all().count() > 0: player_profile = instance.playerprofile_set.all()[0] data['player_profile'] = PlayerProfileSerializer( player_profile).data for item in Team.objects.all(): if player_profile in item.players.all(): data['team'] = TeamSerializer(item).data if item.cap.id == player_profile.id: data['team'] = TeamSerializer(item).data # data["team"] = instance. return data -
Django Test assertTemplateUsed() failed: AssertionError: No templates used to render the response
I have an About page and written a test against it. The template renders well in the browser while the assertTemplatedUsed failed even the template name, url name and status code (returns 200) are all correct. Which part went wrong? Thank you! The error below: System check identified no issues (0 silenced). ...F...... ====================================================================== FAIL: test_aboutpage_template (pages.tests.AboutPageTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/code/pages/tests.py", line 54, in test_aboutpage_template self.assertTemplateUsed(self.response, 'about.html') File "/usr/local/lib/python3.8/site-packages/django/test/testcases.py", line 655, in assertTemplateUsed self.fail(msg_prefix + "No templates used to render the response") AssertionError: No templates used to render the response ---------------------------------------------------------------------- Ran 10 tests in 0.070s FAILED (failures=1) My test.py: class AboutPageTests(SimpleTestCase): def setUp(self): url = reverse('about') self.response = self.client.get(url) def test_aboutpage_status_code(self): self.assertEqual(self.response.status_code, 200) def test_aboutpage_template(self): self.assertTemplateUsed(self.response, 'about.html') -
How to get the Primary key of annotate Count in django
Hi stackoverflow community, my question is about django annotate. Basically what I am trying to do is to find duplicated value with same values from two different fields in two different tables. This is my models.py class Order(models.Model): id_order = models.AutoField(primary_key=True) class OrderDelivery(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) delivery_address = models.TextField() class OrderPickup(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) pickup_date = models.DateField(blank=True, null=True) This is my current code: dup_job = Order.objects.filter( orderpickup__pickup_date__range=(start_date, end_date) ).values( 'orderdelivery__delivery_address', 'orderpickup__pickup_date', ).annotate( duplicated=Count('orderdelivery__delivery_address') ).filter( duplicated__gt=1 ) Based on what I have, I am getting result like this (delivery_address is omitted for privacy purpose): {'orderdelivery__delivery_address': '118A', 'orderpickup__pickup_date': datetime.date(2022, 3, 9), 'duplicated': 2} {'orderdelivery__delivery_address': '11', 'orderpickup__pickup_date': datetime.date(2022, 3, 2), 'duplicated': 6} {'orderdelivery__delivery_address': '11 ', 'orderpickup__pickup_date': datetime.date(2022, 3, 3), 'duplicated': 5} {'orderdelivery__delivery_address': '21', 'orderpickup__pickup_date': datetime.date(2022, 3, 10), 'duplicated': 3} {'orderdelivery__delivery_address': '642', 'orderpickup__pickup_date': datetime.date(2022, 3, 7), 'duplicated': 2} {'orderdelivery__delivery_address': '642', 'orderpickup__pickup_date': datetime.date(2022, 3, 8), 'duplicated': 2} {'orderdelivery__delivery_address': 'N/A,5', 'orderpickup__pickup_date': datetime.date(2022, 3, 8), 'duplicated': 19} Is there a way to get the id_order of those 'duplicated'? I have tried include id_order in .values() but the output will not be accurate as the annotation is grouping by the id_order instead of delivery_address. Thank you in advance -
How to start cron through Dockerfile entrypoint
I'm trying to run cron job through Docker entrypoint file. Dockerfile: FROM python:3.8-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update -y && apt-get install -y build-essential postgresql python-scipy python-numpy python-pandas cron libgdal-dev && apt-get clean && rm -rf /var/lib/apt/lists/* COPY ./django-entrypoint.sh . RUN mkdir /industrialareas WORKDIR /industrialareas COPY ./project . COPY ./requirements.txt . RUN chmod 755 /django-entrypoint.sh RUN pip install --no-cache-dir -r requirements.txt EXPOSE 8000 CMD ["/django-entrypoint.sh"] django-entrypoint.sh: #!/bin/bash # Django python /industrialareas/manage.py collectstatic --noinput python /industrialareas/manage.py migrate python /industrialareas/manage.py runserver 0.0.0.0:8000 # Cron service cron restart service cron status python /industrialareas/manage.py crontab add python /industrialareas/manage.py crontab show exec "$@" But only works Django commands because i check it service cron status and is stopped and python manage.py crontab show and method not added. If i run script manually works well ./django-entrypoint.sh. The cron job is executed and i can see the output on log file. Anybody could help me please ? Thanks in advance. -
joining Django models
please help me out. I want to have the results from this sql query: select Information.id from Information inner join Search on Information.id=Search.article_id where Search.search_id = 'fish'; my models.py class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) search_id = models.CharField(max_length=100) article_id = models.CharField(max_length=100) def __str__(self): return self.id how can i get these results? I don't like to work with foreign keys -
Django ORM duplicated LEFT OUTER JOIN in SQL when annotate
Problem When I add an annotation based on the reverse field, then a double "LEFT OUTER JOIN" appears in the SQL result. As a result, the sum annotation is considered incorrect (duplicated depending on the number of back annotations) How to make sum annotation correct? Django 4.0.3 Python 3.10 Result SQL SELECT "frontend_book"."id", "frontend_book"."title", "frontend_book"."author_id", COALESCE( SUM("frontend_sell"."price"), 0 ) AS "total_profit_author", COALESCE( SUM(T4."price"), 0 ) AS "total_profit_resolver" FROM "frontend_book" INNER JOIN "frontend_human" ON ( "frontend_book"."author_id" = "frontend_human"."id" ) LEFT OUTER JOIN "frontend_sell" ON ( "frontend_human"."id" = "frontend_sell"."author_id" ) LEFT OUTER JOIN "frontend_sell" T4 ON ( <----- HERE "frontend_human"."id" = T4."resolver_id" ) GROUP BY "frontend_book"."id" Models class Human(models.Model): name = models.CharField( 'Name', max_length=200, blank=True, ) class Book(models.Model): title = models.CharField( 'Title', max_length=200, blank=True, ) author = models.ForeignKey( Human, verbose_name='author', related_name='books', on_delete=models.CASCADE, ) class Sell(models.Model): author = models.ForeignKey( Human, verbose_name='Author', related_name='author_sells', on_delete=models.CASCADE, ) resolver = models.ForeignKey( Human, verbose_name='Resolver', related_name='resolver_sells', on_delete=models.CASCADE, ) price = models.FloatField( 'Price', default=0, blank=True ) Views from rest_framework.response import Response from rest_framework.views import APIView from backend.api.frontend.models import Book from django.db.models import Sum, FloatField from .serializers import BookSerializer class TestView(APIView): def get(self, request): qs = Book.objects.all() qs = qs.annotate( total_profit_author = Sum( 'author__author_sells__price', output_field=FloatField(), default=0, ), total_profit_resolver = Sum( 'author__resolver_sells__price', … -
How to deploy django app on IIS error 403.14
I have a problem with deployment my Django application on IIS. my wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'BETA.settings') application = get_wsgi_application() in my settings.py I have DEBUG = True ALLOWED_HOSTS = [some ip] WSGI_APPLICATION = 'BETA.wsgi.application' my __init__.py is empty in root derictory web.config looks like: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <defaultDocument> <files> <clear /> <add value="login.html" /> </files> </defaultDocument> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor = 'C:\Program Files\Python310\python.exe"|"C:\Program Files\Python310\lib\site-packages\wfastcgi.py' resourceType="Unspecified" </configuration> requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="WSGI_HANDLER" value="BETA.wsgi.application"> <add key="PYTHONPATH" value="D:\Applications\HRtool\dev\wwwroot\BETA"> <add key="DJANGO_SETTINGS_MODULE" value="BETA.settings"> </appSettings> in static web.config is next: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <clear/> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read" /> </handlers> </system.webServer> </configuration> But when I start my app on ISS i have another problem: I am trying to enable Directory Browsing, but it doesn't help. In advance settings in Pool I have .Net 4.5. How to fix it ? -
How to create Azure Virtual machine with VM Extension using the python SDK
I want to create an Azure virtual machine with the VM extension(Custom script extension) using the python SDK. Basically, I want a python program that will create the VM with VM extension using the Azure SDK management libraries, I am able to use the Azure SDK management libraries in a Python script to create a resource group that contains a Linux virtual machine. https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-example-virtual-machines?tabs=cmd But I need my Virtual machine with VM extension in it. -
How do I test a DRF view that updates data on every request?
I'm using Django Rest Framework. I have a model Listing, which has an attribute view_count. Every time data is retrieved from listing_detail_view, view_count is updated using the update method and an F expression. Everything is working as expected, but the test for the view is failing as view_count in the response is always 1 count more. // views.py @api_view(['GET']) def listing_detail_view(request, pk): listing = Listing.objects.filter(pk=pk) serializer = ListingSerializer(listing[0]) listing.update(view_count=F('view_count') + 1) return Response(serializer.data) Note: I'm filtering instead of getting because from my understanding the update method is only available for a QuerySet. // test_views.py def setUp(self): self.listing = Listing.objects.create(id=1) def test_listing_detail_view(self): response = client.get(reverse('listing-detail', kwargs={'pk': self.listing.pk})) listing = Listing.objects.get(pk=self.listing.pk) serializer = ListingSerializer(listing) self.assertEqual(response.data, serializer.data) Here's the AssertionError: {'id': '1', 'view_count': '0'} != {'id': '1', 'view_count': '1'} How do I go about testing this view and its view_count update functionality? -
Django TypeError at /signup/ 'in <string>' requires string as left operand, not list
I have a signup form that verifies if the email field contains gmail and gives an error if not. forms.py def clean_email(self): submitted_data = self.cleaned_data['email'] if '@gmail.com' not in submitted_data: raise forms.ValidationError('You must register using a pathfinder23 address') views.py class SignUpView(View, SuccessMessageMixin): form_class = SignUpForm template_name = 'user/register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Starlab Account' message = render_to_string('user/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('confirm_registration') return render(request, self.template_name, {'form': form}) I want to add few other 'trusted emails' so the form will allow users to register for instance: @yahoo.com, @outlook.com but I cannot add a list or tuple because I get an error: TypeError at /signup/ 'in <string>' requires string as left operand, not tuple Question How can I create a list of trusted email domains and instead '@gmail.com' put list of email domains? -
Django Queryset - Foreign Key Relationship
I am trying to make a query set where I get all menu names from the table based on the group. class Menu(models.Model): name = models.CharField(max_length=50, blank=False, null=False) link = models.CharField(max_length=50, blank=True, null=True) parent = models.ForeignKey(to='menu', blank=True, null=True, related_name="sub_menu", on_delete=models.CASCADE) class MenuGroup(models.Model): menu = models.ForeignKey(to='menu.Menu', on_delete=models.CASCADE, blank=True, null=True, related_name="menu", related_query_name="menus") group = models.ForeignKey(to=Group, on_delete=models.CASCADE, blank=True, null=True, related_name="menu_group", related_query_name="menu_groups") -
Django Date time Seting
I'm new to Django and I wanted to create a project where I can set date and time for a model form i.e., as an admin I will set a date and time to accept / collect data including files too and once the date and time exceeds the form get disabled automatically and cannot be altered. I got to know about validations but am confused. Any guidance will do.