Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i need to show doctors in different sections as per their experience in django project. what can i do for this?
def appointment(request): doctors = Doctor.objects.all() context = {'doctors': doctors} if request.user.is_authenticated: return render(request, 'patient/appointment.html', context) else: return redirect('home') here is the function for appointment where i need to apply filter as per doctors experience. i want to filter this doctors regarding their experience. i want this to show doctors in different sections as per their experience so i don't want to give the experience in url of website. the field name in table for experience is 'experience'. -
ModelForm customization with initial form values derived from model
I have a basic model that contains an integer. class Example(models.Model): bare_int = models.PositiveIntegerField() other_fields = models.TextField() I can create a ModelForm form where this value is inserted into a form widget for a bound form. class ExampleForm(ModelForm): class Meta: model = Example fields = ['bare_int', 'other_fields'] I want to customize the ModelForm so that the display layer applies a simple transformation: f'S{bare_int}' to the value for each model instance. The best I can do now is to apply a static default independent of model instance. class ExampleForm(ModelForm): transformed_int = CharField() class Meta: model = Example fields = ['other_fields'] def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.fields['transformed_int'].initial = f'S{123}' How do I get the value of bare_int to insert in this field as the initial value? My actual model is more complex; I am trying to use the ModelForm to avoid repeating the other Example class fields rather than redefining the entire form from scratch. -
Got an error while pushing static files from Django project to bucket in google cloud storage using collect static
I am using following command to push all static files from my local Django project to bucket in Google cloud storage. DJANGO_SETTINGS_MODULE=my_project.settings.production python manage.py collectstatic settings/production.py #----------------- Cloud Storage---------------------# # Define static storage via django-storages[google] GS_BUCKET_NAME = 'project-bucket' GS_PROJECT_ID = 'xxxxxx' # STATICFILES_DIRS = [] DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATIC_URL = 'https://storage.googleapis.com/project-bucket/static/' # GS_DEFAULT_ACL = "publicRead" from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file(os.path.join(BASE_DIR, 'db/key.json')) When I run './manage.py collectstatic' got following error raise exceptions.from_http_response(response) google.api_core.exceptions.Forbidden: 403 GET https://storage.googleapis.com/storage/v1/b/project-bucket/o/admin%2Fcss%2Fautocomplete.css?projection=noAcl&prettyPrint=false: project@project.iam.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object. Please help me in understanding this and give me respective solution. Thanks in advance! -
Django: How to pass data to redirect
def game(request): #... storage = messages.get_messages(request) for message in storage: game_msg=message break if request.method == 'POST': #some code... messages.add_message(request, messages.INFO, game_msg) return HttpResponseRedirect('game') else: form = betForm(user=request.user) print(game_msg) return render(request, 'crash/game.html', {'form': form, 'game_msg':game_msg}) my issue is when I print game_msg it shows the dictionary with all the correct info, but when I try to render it nothing shows up. if I remove the add_message and the redirect, and set game_msg like below it will display correctly. game_msg = {'isWinner':isWinner['won'], 'bet':bet, 'multiplier':multiplier, 'winnings':round(abs(winnings),2), 'crash_multiplier':round(isWinner['multiplier'],2)} if someone could explain what I'm doing wrong or a better method to send form data after a redirect without using URL parameters it would be really helpful -
How to Config Javascript ' script in Django?
I built an app using Django 3.2.3., but when I try to settup my javascript code for the HTML, it doesn't work. I have read this post Django Static Files Development and follow the instructions, but it doesn't resolve my issue. Also I couldn't find TEMPLATE_CONTEXT_PROCESSORS, according to this post no TEMPLATE_CONTEXT_PROCESSORS in django, from 1.7 Django and later, TEMPLATE_CONTEXT_PROCESSORS is the same as TEMPLATE to config django.core.context_processors.static but when I paste that code, turns in error saying django.core.context_processors.static doesn't exist. I don't have idea why my javascript' script isn't working. The configurations are the followings Settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = ( 'C:/Users/pansh/Documents/SarahPortfolio/Portfolio/Portfolio/static/', 'C:/Users/pansh/Documents/SarahPortfolio/Portfolio/formulario/static/formulario', ) urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path from django.urls.conf import include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('formulario/', include("formulario.urls")) ] from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() Template {% load static %} <!DOCTYPE html> <html lang='es'> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href= "{% static 'formulario/style.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'formulario/scriptinfra.js' %}" type="text/javascript"></script> <title>Análisis de Infraestructura</title> </head> Directory Tree ├───formulario │ ├───migrations │ │ └───__pycache__ │ … -
Ban user from Posting a Post
I am building a small Group App and I am trying to implement a feature of banning a user by Admin for certain or particular time. When admin open - ban form then form asks for ban period of the user, which says for 10 days and 20 days. So if user selects 20 days then the ban will automatically delete after 20 days. models.py BAN_CHOICES = [ ('10_days':10_days), ('20_days':20_days), ] class Group(models.Model): user = models.ForeignKey(User, models=on_delete.CASCADE) admin = models.ManyToManyField(User,related_name='admin') time = models.BooleanField(max_length=30, choices=BAN_CHOICES) ban_users = modelsManyToManyField(User,related_name='ban_users') views.py def banning_user(request): d = timezone.now() - timedelta(days=10) ban_users = Group.objects.all() if ban_users.time == '10_days': ban.user.delete() elif ban_users.time == '20_days': ban.user.delete() BUT When i run this code then it is showing Nonetype has no attribute time. I also tried by using:- for b in ban_users: BUT it didn't work. I am new in django and I have no idea how can do it and where is the mistake. Any help would be much Appreciated. Thank you in Advance. -
Refer to variables dynamically
Context: I am creating a Django management command which will accept a positional argument. This argument is a location. My goal is to use the location value to refer to a corresponding variable. I have a global variable named Boston_webhook. This is a simple string which contains a long URL which is just a MSteams webhook... I have an additional global variable named Budapest_webhook which contains the same data type, but instead refers to a webhook related to the Budapest location. In my script, a connector variable has to be defined in order to send the message to the correct place. myTeamsMessage = pymsteams.connectorcard() If someone entered python manage.py report Boston I want to insert this into the connector params, but I am unsure how to refer to variables dynamically. Is it possible to refer to Boston_webhook when the location == 'Boston' using some sort of concatenation...? something like myTeamsMessage = pymsteams.connectorcard(location + _webhook) would be ideal I would like to avoid using conditionals as it is not scalable. I need to be able to add locations to the database without having to change code... -
Django Channels - Connection Failed (Producing error log - How to?)
I am currently setting up a basic Django Channels based chat app within my Django application. I have created all the necessary files and I have followed the instructions with regards to configuring my WebSockets for my application. Although, in the Console panel on Chrome, I am seeing the following statuses: SUCCESS {response: "Successfully got the chat.", chatroom_id: 1} (index):298 setupWebSocket: 1 (index):367 ChatSocket connecting.. (index):313 WebSocket connection to 'ws://<ip>/chat/1/' failed: setupWebSocket @ (index):313 success @ (index):385 fire @ jquery-3.6.0.js:3500 fireWith @ jquery-3.6.0.js:3630 done @ jquery-3.6.0.js:9796 (anonymous) @ jquery-3.6.0.js:10057 (index):361 ChatSocket error Event {isTrusted: true, type: "error", target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …} (index):353 Chat socket closed. Where it says <ip> above, my server IP address is actually listed there, I've just removed it on here as a precaution :-) Does anyone know how if Django-Channels produces logs for error handling so I can debug the failed connection error in greater detail? I'm a little lost to where the root of the failed connection issue is occurring from within my project without some sort of log files. I do have Redis configured, and I have added my Redis Channel Layer in to my settings.py file along with listing both … -
changing django model filed data before saving to database
i want to update model field data before saving to database. class mynumber(TimeStampedModel): text = models.TextField(max_length=10000, null=True, blank=True) number = models.DecimalField(default=0, max_digits=9, decimal_places=2) #serializer file class mynumberSerializer(serializers.ModelSerializer): class Meta: model = mynumber fields = "__all__" #view class MyquantityViewSet(CreateListMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): serializer_class = mynumberSerializer queryset = mynumber.objects.all() i want to divide number field before saving to database. what should be the best aproach? -
Can't call objects from class in loop Python Django
I an newbee to Django and I realise that it is a very silly question but, when I put objects in a HTML code to call index from data base I recieve just text of what I am calling: List of news(item.title)(item.title)(item.title)(item.title) views.py: from django.shortcuts import render from django.http import HttpResponse from .models import News def index(request): news = News.objects.all() res = '<hi>List of news</h1>' for item in news: res += f'<div><p>(item.title)</p></div>' return HttpResponse(res) -
GenericRelation inherited from Abstract model in other app failing to generate migration
So I'm trying to create a new model in a new app B, inheriting from an abstract model in app A: # app_b/models.py from app_a.models import Foo class ConcreteModel(Foo): pass Foo has a GenericRelation to another model of app A: # app_a/models.py from django.contrib.contenttypes.fields import GenericRelation class Foo(models.Model): class Meta: abstract = True some_relation = GenericRelation( "Bar", content_type_field="foo_type", object_id_field="foo_id" ) class Bar(models.Model): # whatever Generation of the initial migration of app B fails with the following SystemCheck errors: <function GenericRelation.contribute_to_class..make_generic_foreign_order_accessors at 0x7fa2a6747c80>: (models.E022) <function GenericRelation.contribute_to_class..make_generic_foreign_order_accessors at 0x7fa2a6747c80> contains a lazy reference to app_b.bar, but app 'app_b' doesn't provide model 'bar'. app_b.ConcreteModel.some_relation: (fields.E307) The field app_b.ConcreteModel.some_relation was declared with a lazy reference to 'app_b.bar', but app 'app_b' doesn't provide model 'bar'. Indeed, app_b does not provide Bar, app_a does. I tried explicitly mentioning app_a in the GenericRelation: some_relation = GenericRelation( "app_a.Bar", content_type_field="foo_type", object_id_field="foo_id" ) but this does not generate a migration for app_a, nor does it fix the problem. I'm using Django 2.2. Is there a workaround besides moving ConcreteModel to app_a ? -
How can i deal with aws django-storages storages error
when i run django on elastic beanstalk, I used this requirements.txt #requirements.txt asgiref==3.3.4 boto3==1.17.94 botocore==1.20.94 Django==3.2.4 django-storages==1.11.1 jmespath==0.10.0 python-dateutil==2.8.1 pytz==2021.1 s3transfer==0.4.2 six==1.16.0 sqlparse==0.4.1 urllib3==1.26.5 #settings.py DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' to upload media files to s3 But at the same time i got this error /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/storages/__init__.py:9: UserWarning: This library has been designated as the official successor of django-storages and releases under that namespace. Please update your requirements files to point to django-storages. I did reinstall django-storages and any other thing which is on google but it didn't work How can i deal with this error? -
django.db.utils.OperationalError: 3780 Referencing column and referenced column are incompatible
I'm trying to add a foreign key relation between two models in Django, but I'm getting this error. Notification model: class Notification(models.Model): ... lab_extension = models.ForeignKey(Labs, on_delete=models.CASCADE, null=True, to_field='lab_id') Lab model class Lab(models.Model): lab_id = models.AutoField(primary_key=True) lab_name = models.CharField(max_length=40) lab_model = models.IntegerField() After assigning this foreign key field to the Notification model, I get this error when doing python manage.py migrate: django.db.utils.OperationalError: (3780, "Referencing column 'lab_extension_id' and referenced column 'lab_id' in foreign key constraint [constraint name] are incompatible.") It's likely this error will not persist if I remove AutoField from the Lab model, and use the default id field. But I'm at a point into the project where I can't do that. I also realize a foreign key field is generally not nullable, but for this project, the Notification model may or may not point to a Lab model. -
Why is adding styling or widgets to Django forms will prevent data from being saved in database?
I just tried multiple ways of styling my Django form but every time I did it prevents data from being saved in Django's admin database. Here is my code : models.py : class listing(models.Model): title = models.CharField(max_length=64) describtion = models.CharField(max_length=300) bid = models.FloatField() category = models.ForeignKey(categories, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT) user = models.ForeignKey(User,default='', verbose_name="User", on_delete=models.SET_DEFAULT) image = models.CharField(max_length=400) def __str__(self): return f"{self.title} " class create(ModelForm): class Meta: model = listing fields = [ 'title', 'describtion','bid','category','image'] After adding widgets : class create(ModelForm): class Meta: model = listing fields = [ 'title', 'describtion','bid','category','image'] widgets={ 'title': TextInput(attrs={'class':'form-control'}), 'describtion': TextInput(attrs={'class':'form-control'}), 'image': TextInput(attrs={'class':'form-control'}), 'bid': NumberInput(attrs={'class':'form-control'}), 'category': SelectMultiple(attrs={'class':'form-control'}), } Views.py: def CreateListing(request): user = request.user if request.method == "POST": form = create(request.POST, request.FILES) if form.is_valid(): form.instance.user = user form.save() return redirect('listing') else: return render(request, "auctions/Create.html",{ 'form': create }) Ps : without widgets, data will be saved in the Database. -
Update field with Django ORM based on computed value
I have a basic model: class MyModel(Model): id = models.IntegerField() is_admin = models.BooleanField() What I want to achieve is to update the value of the is_admin field for the entire table at once, based on whether or not the id value is in a certain list of values. Basically, in raw SQL, this is the query I want: UPDATE my_model SET is_admin = (id IN (1, 2, 3, 4)) How can I achieve this with Django's ORM? This is what I tried so far: from django.db.models import F, Value admin_ids = (1, 2, 3, 4) MyModel.objects.update(is_admin=F("id") in admin_ids) # Resulting query is: # UPDATE my_model SET is_admin = false MyModel.objects.update(is_admin=F("id") in Value(admin_ids)) # TypeError: argument of type 'Value' is not iterable MyModel.objects.filter(id__in=admin_ids).update(admin=True) MyModel.objects.exclude(id__in=admin_ids).update(admin=False) # it works... but can I do this in a single query instead of two? I'm using Django 3.2 and PostgreSQL. -
Search model field with TrigramSimilarity
i have a model named cars, the method search_text() is a str containing the values of model and modelcatregory. Then i have my searchview but i cant use search on the method search_text(). I get a error Unsupported lookup 'profession.search_text()' for AutoField or join on the field not permitted. is it possible to make a searcheable model field by joining to other fields? And how can i cal that function in my search? Model: class Cars(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(_('active'), default=True) model = models.ForeignKey(Model, on_delete=models.SET_NULL, null=True) modelcategory = models.ForeignKey(Modelcategory , on_delete=models.SET_NULL, null=True) posted_on = models.DateTimeField(_('registrerad'), auto_now_add=True) updated_on = models.DateTimeField(_('last updated'), auto_now=True) years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True) def search_text(self): searchtext = str(self.model) + ' - ' + str(self.modelcategory) return searchtext Search view def cars_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = User.objects.filter(is_active=True).exclude(Q(cars__isnull=True) | Q(id=request.user.id)) results = results.annotate( similarity=TrigramSimilarity('cars__search_text', query), ).filter(similarity__gt=0.3).order_by('-similarity') return render(request, 'users/search.html', {'form': form, 'query': query, 'results': results}) -
Combining View and Viewset Django
I have a serializer for StacItem and a simple viewset for it say class StacItemSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() id = serializers.SerializerMethodField() ... class StacItemViewSet(viewsets.ModelViewSet): serializer_class = StacItemSerializer queryset = StacItems.objects.all() I also created a custom view class StacItemMainView(APIView): def get(self, request): items = {} items['type'] = "Example" return Response(items) In my urls urlpatterns = [ url(r'items', StacItemMainView.as_view()), ] router.register(r'items/<id>', StacItemViewSet, basename='item') urlpatterns += router.urls What I want to achieve is to have an endpoint to apps/items/ using the APIView and on the same time I want the endpoint for each Item i.e. apps/items/{id} from the viewset using the serializer. How can I customize the urls to point it correctly? -
Django filtering doesn't work with checkboxes
As far as i've understood my view doesn't get checked checkboxes. I can create 5 variables for 5 checkboxes but it seems to me wrong. I need to get all checked colors in variable 'color' and materials in 'material'. Then need to get all objects from database that satisfying these checked checkboxes My form: <form action="{% url 'filter' %}" method="POST">{% csrf_token %} <h2>Color:</h2> <input type="checkbox" name="red" id="" value="Red">Red<br> <input type="checkbox" name="blue" id="" value="Blue">Blue<br> <h2>Material:</h2> <input type="checkbox" name="wood" id="" value="Wood">Wood<br> <input type="checkbox" name="plastic" id="" value="Plastic">Plastic<br> <input type="checkbox" name="metal" id="" value="Metal">Metal<br> <button type="submit" value="Submit">Find!</button> </form> My django model: class Toy(models.Model): COLORS = ( ('Blue', 'Blue'), ('Red', 'Red') ) MATERIALS = ( ('Plastic', 'Plastic'), ('Wood', 'Wood'), ('Metal', 'Metal') ) photo = models.ImageField(upload_to='images/', blank=True) title = models.CharField(max_length=128, blank=False) description = models.CharField(max_length=5000, blank=False) price = models.PositiveIntegerField(blank=False) count = models.PositiveIntegerField(blank=False) color = models.CharField(max_length=128, blank=False, choices=COLORS) material = models.CharField(max_length=128, blank=False, choices=MATERIALS) My views.py def filter(request): products = Toy.objects.all() material = request.POST.get("what do i need to add here to find all products that satisfiying checked material checkboxes?") color = request.POST.get("the same but with color") if material: products = products.filter(material__in=material) if color: products = products.filter(color__in=color) return render(request, 'catalog/products.html', {'products': products}) -
Django NoReverseMatch and Django-Verify-Email
I hope someone can help me with this bug. So, I am using Django-Verify-Email as a library to send verifications emails from my app, and, according to the wiki, they use the LOGIN_URL variable in the settings of the app. The problem is that, at the moment, I want to change this LOGIN_URL to the homepage ('index'or '/' or 'mainpage') but it throws me a error (Django 3.2). Any help is apreciatted! Reverse for 'index' not found. 'index 'is not a valid view function or pattern name. Index is at the core of the project, and not inside any app. urls.py: from django.urls import path, include import user.urls from .views import index import calculator.urls urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='mainpage'), ] views.py: from django.shortcuts import render def index(request): return render(request, 'index.html') -
Django Channels websocket unexpectedly disconnects with 1011 error
I'm writing an app which requires a socket connection, and I'm having problems with websockets being disconnected after ~4/5 seconds, with my front getting an 1011 error code. My consumer gets connected, I can send messages to it, and it will send them back to me correctly before disconnecting unexpectedly. My consumer file looks like this : class GameConsumer(WebsocketConsumer): def connect(self): print("[info] new client connected") self.accept() def receive(self, text_data=None, bytes_data=None): print("[info] receiving message") self.send(text_data="ALLO") print("[info] message sent back") def disconnect(self, event): print("[info] client disconnected") My settings: ASGI_APPLICATION = 'restAPI.asgi.application' CHANNEL_LAYERS = { "default": { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [("redis", 6379)], } }, } And my asgi application: import os from channels.routing import get_default_application from channels.routing import ProtocolTypeRouter from api.routing import websockets os.environ.setdefault("DJANGO_SETTINGS_MODULE", "restAPI.settings") application = ProtocolTypeRouter({ "websocket": URLRouter([ path( "ws/game/<str:uuid>", GameConsumer.as_asgi(), name="game", ), ]), }) I can write debug strings when websockets are connected from both sides, when messages are sent and read, and when I disconnect by myself, without waiting for the error to trigger. But if I wait more than 5 seconds before closing it the connection will shutdown with the 1011 error code. Can anyone tell me what can be failing in this ? I'm using … -
Django - 404 Error for static files after Cache Busting
Django version 3.2.3 I am trying to implement cache busting in Django. # settings.py DEBUG = False STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = 'assets' STATIC_URL = '/assets/' # Collecting all static files from this Dir STATICFILES_DIRS = [ BASE_DIR / 'static',] python manage.py collectstatic successfully generated the static files with hash in my assets folder. Example: style.7b0b119eddb7.css Now, after running the server all static files end up with a Error-404 Later, I ran it with Debug = False and obviously all static files loaded correctly but they weren't the hashed files. GET /assets/css/bootstrap.min.css HTTP/1.1 200 GET /assets/css/bootstrap.min.2618ae4d1f4a.css HTTP/1.1 404 -
How can I load a cropped image with previously obtained data?
I'm using jcrop to obtain some user input on where they want to crop an Image, but instead of saving the cropped image, I'm trying to save only information about the area cropped so I can render it later in other pages, I was wondering if it's possible, so far I've tried to apply css with javascript but so far without success -
|as_crispy_field got passed an invalid or inexistent field while passing context from my django form
Help!!! I'm lost on this erro: while trying to submit this form and pass it content as a context: I see that the identition of my view is correct as well as the definitions of my form View def costm_questions(request): if request.method == 'POST': form = labor_questions(request.POST) if form.is_valid(): cost_dict= dict() cost_dict['Union_PWR']= form.cleaned_data['Union_PWR'] cost_dict['UnionLabor_area']= form.cleaned_data['UnionLabor_area'] cost_dict['After_Hours_Req']= form.cleaned_data['After_Hours_Req'] cost_dict['infectious_control_Req']=form.cleaned_data['infectious_control_Req'] cost_dict['No_Core_Drills']= form.cleaned_data['No_Core_Drills'] cost_dict['Armored_fiber_req']= form.cleaned_data['Armored_fiber_req'] cost_dict['cost_dict']= cost_dict context = { 'cost_dict': cost_dict, } return render(request, 'building_form.html', context) else: form = labor_questions()`enter code here` return render(request, 'cost_questions_form.html', {'form': form}) Forms class labor_questions(forms.Form): BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) LABOR_AREA_CHOICES= ((1, '1) Chicago'), (2 ,'2) Manhattan'), (3 ,'3) NYC Metro'), (4 ,'4) Los Angeles'), (4 ,'5) San Francisco'), (5 ,'6) Philadelphia'), (5 ,'6) Other')) AFTER_HOURS_CHOICES= ((1, '1) No'), (2, '2) Yes, Mon-Fri'), (3,'3) Yes, weekends only')) Union_PWR = forms.ChoiceField(choices = BOOL_CHOICES, label="Is Union Labor or Prevailing Wage Required?", initial='', widget=forms.Select(), required=True) #Is Union Labor or Prevailing Wage Required? UnionLabor_area= forms.ChoiceField(choices = LABOR_AREA_CHOICES, label="if yes please choose union area", initial='', widget=forms.Select(), required=True) After_Hours_Req= forms.ChoiceField(choices = AFTER_HOURS_CHOICES, label="Is after-hours work required?", initial='', widget=forms.Select(), required=True) infectious_control_Req= forms.ChoiceField(choices = BOOL_CHOICES, label="Is tenting required for infectious control?", initial='', widget=forms.Select(), required=True) No_Core_Drills = forms.IntegerField(label='How many core drills will be required?', required=True) … -
problem in otp validation during login in django rest
I am trying to send otp and then validate otp for login. I am able to send otp but it is not validating for some reason. the code for sending otp is below and it is working fine- class SendOTP(APIView): permission_classes = (AllowAny, ) def post(self, request, *args, **kwargs): email = request.data.get('email') if email: email = str(email) user = User.objects.filter(email__iexact = email) if user.exists(): key = send_otp(email) if key: old = User.objects.filter(email__iexact=email) if old.exists(): old = old.first() count = old.count old.count = count + 1 old.save() print('Count Increase', count) return Response({ 'status': True, 'detail': 'OTP sent successfully.' }) code for generating 6 digit otp is - def send_otp(email): if email: digits = [i for i in range(0, 10)] key = "" for i in range(6): index = math.floor(random.random() * 10) key += str(digits[index]) print(key) return key else: return False code for validating email and otp is below but it is not working- class ValidateOTP(APIView): permission_classes = (AllowAny, ) def post(self, request, *args, **kwargs): email = request.data.get('email' , False) otp_sent = request.data.get('otp', False) if email and otp_sent: e_mail = User.objects.filter(email__iexact = email) if old.exists(): e_mail = e_mail.first() otp = e_mail.otp print(otp, e_mail, otp_sent) if str(otp_sent) == str(otp): old.validated = True old.save() … -
I want to send list from javascript to django views.py
in this i want to send variable list[] to django. And i have tried many methods but i didnt get how to pass this list to django plz help me to get rid of this. Thanku in Advance. function add_item(item,next){ list.push(item.name); item.parentNode.style.display = "none"; next.style.display = "block"; console.log(list); } function remove_item(item,prev){ for (var i = 0; i <= list.length; i++) { if (list[i]===item.name) { list.splice(i,1); } } item.parentNode.style.display = "none"; prev.style.display = "block"; } $(document).ready(function() { $.ajax({ method: 'POST', url: '/food_output', data: {'list': list}, success: function (data) { //this gets called when server returns an OK response alert("it worked!"); }, error: function (data) { alert("it didnt work"); } }); });```