Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
reload a page in django using ajax?
I am building a messaging app and i want to reload my page every 1 minute so that the user can see new messages if there is some i know how to do it in html but i wanna use ajax(i am not so good in it) to reload the page. here is my views.py: class MessagesView(LoginRequiredMixin,View): def get(self, request, chat_id): try: chat = Chat.objects.get(id=chat_id) if request.user in chat.members.all(): chat.message_set.filter(is_readed=False).exclude(author=request.user).update(is_readed=True) else: chat = None except Chat.DoesNotExist: chat = None return render( request, 'users/messages.html', { 'user_profile': request.user, 'chat': chat, 'form': MessageForm() } ) def post(self, request, chat_id): form = MessageForm(data=request.POST) if form.is_valid(): message = form.save(commit=False) message.chat_id = chat_id message.author = request.user message.save() return redirect(reverse('messages', kwargs={'chat_id': chat_id})) and my template is: {% extends 'profile/base.html' %} {% load tz %} {% block title %} Messages {% endblock %} {% block head %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <style> #form { position: fixed; bottom: 0; background-color:#f1f1f1; } .container { border: 1px solid #dedede; background-color: #f1f1f1; border-radius: 5px; padding: 1px; margin: 1px 0; } .container::after { content: ""; clear: both; display: table; } .darker { border-color: #ccc; background-color:#ddd; } .container img { float: left; max-width: 40px; height:40px; width: … -
None type object has no attribute django tenants
I wanted to a many to many field to the db, in a django tenants application getting the above error, the code is as follows @login_required() def create_tenant(request): subscription = Subscription.objects.get(user=request.user) if subscription.status == "active": if request.method == 'POST': form = ClientForm(request.POST or None, request.FILES or None) if form.is_valid(): logo = form.cleaned_data.get('logo') brand = form.cleaned_data.get('brand') seq_no = list(range(5000, 9000)) random.shuffle(seq_no) seq_no = seq_no.pop() schema_name = f'Domain{seq_no}' name = f'UID-{seq_no}' location = form.cleaned_data.get('location') tenant = Client(schema_name=schema_name, name=name, user=request.user, logo=logo, brand=brand, ) instance = tenant.save() for obj in location: print(obj) instance.location.set(obj) return redirect('create_domain') else: form = ClientForm() return render(request, 'form.html', {'form': form}) else: return redirect('home') models.py class Client(TenantMixin): name = models.CharField(max_length=100) brand = models.ForeignKey( Brand, related_name='gym_client', on_delete=models.CASCADE, blank=True, null=True ) location = models.ManyToManyField( Location, blank=True ) user = models.OneToOneField( User, related_name='clients', on_delete=models.CASCADE, blank=True, null=True ) I am getting selected locations as I can see it printing in terminal, the method I tried, I think usually works for many to many, don't know why it is throwing error. Looking for an advice, thank you -
How can I find total number of signups in a week?
I am using django build in User model have one-to-one relation with UserProfile model. I have to count number of signups in a week. How can I do this?. Thanks in advance for your addition. -
Get Dynamic Select option in Clone Node using Javscript
I'm trying to create a form where I'm giving dynamic select option i.e one select option will depend on another select option, as you can see in the Image below, if Gender is male and Child the age group is between 1-18 similarly for Adult its greater than 18. And By clicking Add member I'm cloning the whole Person div, but the script is not working for the cloned node and I'm only getting AgeGroup of the 1st div whose clone is created. I'm trying to build this form in Django if that helps. My code: document.getElementById('addMember').onclick = function() { var addOnDiv = document.getElementById('addon'); var clonedNode = addOnDiv.querySelector('.memberBody').cloneNode(true); addOnDiv.appendChild( clonedNode ); } ## for select $("select").change(function() { var selectedVal = $('#type').val(); var selectedGender = $('#gender').val(); console.log(selectedGender); console.log(selectedVal); if('Child' === selectedVal){ var childGroup = '<select name="h_ageGroup" class="custom-select"> <option value="" disabled="disabled" selected="selected">Choose option</option>........</select>'; $('#selectList').html(childGroup); } if('Adult' === selectedVal ){ var childGroup = '<select name="h_ageGroup" class="custom-select"> <option value="" disabled="disabled" selected="selected">Choose option</option> <option value=">18 Years"> >18 Years </option></select>'; $('#selectList').html(childGroup); } }); How can I get dynamic select on my cloned node too. Is there any other way through which I can achieve this ? -
SMTPServerDisconnected at /userprofileinfo/register/ please run connect() first
Login registration is working fine, but when I verify the user email I can't able to send the verification link to user to verify the email. It shows me above error that please run connect() first. Can someone help me to find out the error ... Views.py from django.shortcuts import render from userprofileinfo.forms import UserForm from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth import authenticate, login, logout from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.views import View from django.contrib import messages from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.template.loader import render_to_string from .utils import account_activation_token from django.urls import reverse from django.contrib import auth @login_required def special(request): return HttpResponseRedirect("You are logged in, Nice!") @login_required def userlogout(request): logout(request) return HttpResponseRedirect(reverse('careforallapp:base')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.is_active = False user.save() current_site = get_current_site(request) email_body = { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } link = reverse('userprofileinfo:activate', kwargs={ 'uidb64': email_body['uid'], 'token': email_body['token']}) email_subject = 'Activate your account' activate_url = 'http://'+current_site.domain+link send_mail( email_subject, 'Hi … -
Reverse for 'admin-color-product-map-edit' with arguments '('',)' not found. 1 pattern(s) tried: ['admin1/colorProductMap_edit/(?P<id>[0-9]+)$']
I'm a new face to Django so please be considerate to if ever my problem is something stupid. So I have been practicing Django, I've run into problems with tegards to NoReverseMatch, I went through answers in stackoverflow but still I couldn't find where I went wrong. Can you help me a bit guys? views.py @login_required(login_url="admin-login") @user_passes_test(check_role_admin) def colorProductMap_edit(request, id): instance = ColorProductMapping.objects.get(color_p_map_id=id) print(instance.color_id) form = ColorProductMapForm(instance=instance) if request.method == 'POST': form = ColorProductMapForm(request.POST, instance=instance) if form.is_valid(): form.save() return redirect('/admin1/colorProductMap') else: form = ColorProductMapForm(instance=instance) return render(request, 'admin1/colorProductMap.html', {'form': form, 'instance': instance}) I properly partnered and connected with the following in my urls.py. urls.py path('colorProductMap_edit/<int:id>', views.colorProductMap_edit, name="admin-color-product-map-edit"), forms.py class ColorProductMapForm(forms.ModelForm): class Meta: model = ColorProductMapping fields = ['color_id', 'prod_id'] models.py class ColorProductMapping(models.Model): color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True) color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") colorProductMap.html {% extends 'admin1/layout/master.html' %} {% block title %}Color Product Map{% endblock %} {% block main %} <h1> <center>Color Product Map</center> </h1> <div class="container"> <div class="row"> <div class="col-lg-2"></div> <div class="col-lg-10"> {%if colorProductMap_show%} <button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add Color Product Mapping </button> <div class="modal fade" id="modal-primary"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Add Color … -
Django | Same form multiple times on the same template
I have a project with a model called "List," and a model called "ListItem." There are multiple list items to each list. Here's what I'd like to do. I'd like the user to be able to create a new list with as many items as they deem necessary on one form. Here's the logic I have so far: models.py: class List(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class ListItem(models.Model): team_list = models.ForeignKey(List, on_delete=models.CASCADE) content = models.TextField() index = models.IntegerField() def __str__(self): return f"{self.team_list} [{self.index}]" forms.py: class NewListForm(forms.ModelForm): name = forms.CharField(max_length=50, label='Card Name') team = forms.ModelChoiceField(queryset=models.Team.objects.all()) class Meta: model = models.List fields = ['name', 'team'] class NewListItemForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea, label='Item', required=True) class Meta: model = models.ListItem fields = ['content'] views.py: def new_list(request): context = { 'title': 'New List', 'list_form': NewListForm, 'list_item_form': NewListItemForm, } if request.method == 'POST': list_form = NewListForm(request.POST) list_item_form = NewListItemForm(request.POST) if list_form.is_valid() and list_item_form.is_valid(): list_instance = list_form.save() list_item_instance = list_item_form.save(commit=False) list_item_instance.team_list = list_instance list_item_instance.index = 1 list_item_instance.save() messages.success(request, "List has been created!") return redirect('home') else: messages.error(request, "That list name is already taken") return render(request, 'lists/new_list.html', context) This works for creating 1 list and just 1 item. Ultimately, I'd like the user to … -
Django How to reuse a URL and View based on an input or state?
I currently have a url and a view to display my objects. Is it possible to create a new URL with the same view then just change the filter of objects without creating a new view? This is my view: path('search/', hrViews.hr_search, name='hr_search'), # Default path('search/with_changed_filter', hrViews.hr_search, name='hr_search'), # In here. This is as simple as I can be. -
Contacting another WebSocket server from inside Django Channels
I have two websocket servers, call them Main and Worker, and this is the desired workflow: Client sends message to Main Main sends message to Worker Worker responds to Main Main responds to Client Is this doable? I couldn't find any WS client functionality in Channels. I tried naively to do this (in consumers.py): import websockets class SampleConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): async with websockets.connect(url) as worker_ws: await worker_ws.send(json.dumps({ 'to': 'Worker' })) result = json.loads(await worker_ws.recv()) await self.send(text_data=json.dumps({ 'to': 'Client' }) However, it seems that the with section blocks (Main doesn't seem to accept any further messages until the response is received from Worker). I suspect it is because websockets runs its own loop, but I don't know for sure. The response { "to": "Client" } does not need to be here, I would be okay even if it is in a different method, as long as it triggers when the response from Worker is received. Is there a way to do this, or am I barking up the wrong tree? If there is no way to do this, I was thinking of having a thread (or process? or a separate application?) that communicates with Worker, and uses channel_layer to … -
Is there a good way to deal with multiple forms and models in Django?
I'm building an app in which I have a model with several manytomany fields and some foreignkey fields, and I need a view that allows me to create all in one page and let me enter multiply times for the manytomanyfields, but I don't know how to deal with a lot of forms in the same page/view. main model class Client(models.Model): company_name = models.CharField(max_length=255, blank=True, null=True) payment_method = models.CharField(max_length=64, null=True, blank=True) owner = models.CharField(max_length=100, blank=True, null=True) operation = models.CharField(max_length=50, blank=True, null=True) value = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) currency = models.CharField(max_length=55, null=True, blank=True) address = models.ManyToManyField(Address, blank=True) contact = models.ManyToManyField(Contact, blank=True) relationship = models.ManyToManyField(Relationship, blank=True) attachment = models.ManyToManyField(Attachment, blank=True) billing = models.ForeignKey(Billing, null=True, blank=True, on_delete=models.CASCADE) delivery = models.ForeignKey(Delivery, null=True, blank=True, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True) note = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.company_name others models class Address(models.Model): address = models.CharField(max_length=256, null=True, blank=True) number = models.PositiveIntegerField(null=True, blank=True) district = models.CharField(max_length=32, null=True, blank=True) city = models.CharField(max_length=32, null=True, blank=True) country = models.CharField(choices=COUNTRY_CHOICES, max_length=64, null=True, blank=True) def __str__(self): return self.address class Contact(models.Model): name = models.CharField(max_length=256, blank=False, null=True) sector = models.CharField(max_length=64, blank=True, null=True) email = models.EmailField(max_length=256, blank=True, null=True) phone = PhoneField(blank=True, null=True) cellphone = PhoneField(blank=True, null=True) role = … -
Create model instance from dict containing different keys compared to model attributes in Django
I am trying to create model/s from an api response. The response received has different keys as compared to the model attributes in our system. I would like to know the best way to create a model from that response. class MyModel(BaseModel): external_id = models.IntegerField(blank=True, null=True) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) def save_to_db_from_external_data(response_data): map_dict = { 'externalId': 'external_id', 'startDate': 'start_date', 'endDate': 'end_date' } if type(response_data) == 'dict': new_model_data_dict = {} for key in map_dict: if key in response_data: new_model_data_dict[map_dict[key]] = response_data[key] MyModel.objects.create(**new_model_data_dict) elif type(response_data) == 'list': new_model_data_list = [] for data_dict in response_data: new_data_dict = {} for key in map_dict: if key in data_dict: new_data_dict[map_dict[key]] = data_dict[key] new_model_data_list.append(new_data_dict) MyModel.objects.create(**(model_data_dict) for model_data_dict in new_model_data_list) The above is the code that I have written. Is this the correct way to do the required task? Or is there any better way in django to achieve the same? -
Debug hover in VSCode is not showing variable values in Python
In a Django view context, I am trying to see the variable values at debug time in the hover, and they are not showing up. Version: 1.53.2 (user setup) Commit: 622cb03f7e070a9670c94bae1a45d78d7181fbd4 Date: 2021-02-11T11:48:04.245Z Electron: 11.2.1 Chrome: 87.0.4280.141 Node.js: 12.18.3 V8: 8.7.220.31-electron.0 OS: Windows_NT x64 10.0.18363 What I expect to see: What I actually see: Python Extension v2021.1.502429796 Language Server: Pylance -
Django + OWASP ZAP Cross Site Scripting (Reflected) - Is the value attribute of an HTML input tag a risk?
In my Django project, I have a search input in the navbar across most pages on my site. I'm a beginner to OWASP ZAP. After running the scan, one of the high priority alerts (red flag icon) raised was "Cross Site Scripting (Reflected)". In my case, this is my website search form: <form method="GET" id="searchForm"> <input type="text" name="q" id="searchQuery" placeholder="Search..." autocomplete="off" maxlength="100" required=""> </form> if someone searches for javascript:alert(1); in the search box, the value= attribute contains the same. <form method="GET" id="searchForm"> <input type="text" name="q" value="javascript:alert(1);" id="searchQuery" placeholder="Search..." autocomplete="off" maxlength="100" required=""> </form> Is this is a potentially vulnerability or is the input is being sanitized by Django? This form is created using a Django forms.ModelForm: class SiteSearchForm(forms.ModelForm): class Meta: model = Search fields = ('q',) -
How to prepopulate tabularInline fields with different values per-row
I have a ModelAdmin class with an inline of type TabularInline. What I would like is for each row of the TabularInline. What I need to do is to pre-select the select boxes with the available languages so each of them will have one of the languages as a selected value (e.g. row1: English, row2:Arabic, row3: Français, row4: Espanol). Please note that the number of rows is generated based on the count of the available languages. Any suggestions would be appreciated. My code is shown below: admin.py class SectorTranslationInline(admin.TabularInline): model = SectorTranslation form = SectorTranslationForm def get_extra(self, request, obj=None, **kwargs): lang_count = Language.objects.count() return lang_count def get_max_num(self, request, obj=None, **kwargs): lang_count = Language.objects.count() return lang_count class SectorAdmin(admin.ModelAdmin): inlines = [ SectorTranslationInline ] models.py class Sector(models.Model): _name = models.CharField(max_length=255, null=False, default='') class Language(models.Model): name = models.CharField(max_length=255, null=True) name_prefix = models.CharField(max_length=255, null=True) class SectorTranslation(models.Model): lang = models.ForeignKey(Language, related_name='lang_sector_translation', on_delete=models.CASCADE) sector = models.ForeignKey(Sector, related_name='sector_translation', on_delete=models.CASCADE) name = models.CharField(max_length=255, null=False, default='') -
How to make a django field read only for a non staff user in django rest framework
Here is my django model; class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="books") quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.book.title}" Here is the serializer; class OrderItemSerializer(serializers.ModelSerializer): book = BookSerializer(read_only=True) class Meta: model = OrderItem exclude = ["user"] How do I prevent non staff users from changing the ordered field or making the field read-only for non staff users -
Django Two Factor Auth with custom login
I am trying to add two factor login using the @otp_required decorator from Django Two-Factor Authentication into my custom login. From other posts, it seems like the correct way to do this is create a new view that is extended from two factors Login View so I have views.py from two_factor.views import LoginView from two_factor.forms import AuthenticationTokenForm, BackupTokenForm class testLogin(LoginView): template_name='customLogin.html' form_list = ( ('auth', TestLoginForm), ('token', AuthenticationTokenForm), ('backup', BackupTokenForm), ) urls.py path('test/', views.testLogin.as_view(), name='test') I have also extended my login form to be forms.py from django.contrib.auth.forms import AuthenticationForm class TestLoginForm(AuthenticationForm): username = forms.CharField(max_length=20) password = forms.CharField(max_length=20, widget=forms.PasswordInput) How would I pass the form into a html page and then get that data back through a post command so I can work with the data in another view such as my customView. views.py def customView(request): form = TestLoginForm(request) if (request.method == "POST"): if (form.is_valid()): -
Recover old jupyter notebooks
I had to uninstall everything on my laptop and reinstall including python and jupyter. Now I dnt see any of my jupyter notebooks when I launch jupyter. I am having almost a heart attack! How I can recover my codes in jupuyter? some additional info: This was part of our company transition from legacy company to new company. We basically lost all installed programs as the results of this transition. I know, very stupid but I was not involved in making decisions! -
Django Admin login not working after model change
I changed the username field to email, following this guide. Everything works so far, except for Django Admin Website, which worked before like a charm. No matter what I enter it always displays "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.". This is odd, as I am still able -from my separate frontend- to add and login users. Just the ones created via createsuperuser don't work properly. I went to the shell and it stated the following: >>> from user.models import User >>> User.objects.get(id=1) <User: Firstname Lastname> >>> me = User.objects.get(id=1) >>> me.password 'pbkdf2_sha256$216000$XTRS1jTuNQWA$rvRCMxeYAJVaL1SftNjXBYCxlMiRnHs9uopq4OMh6gM=' >>> me.email 'me@test.test' >>> me.username >>> me.is_staff True >>> me.is_superuser True >>> me.is_active True So this seems to work. But when I do the authenticate method for those credentials, nothing happens. My model looks basically like this and worked before the change: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() I tried deleting the database and reading the user, I tried different passwords and usernames (mail addresses). -
trouble with django on git bash. command not found
I've been trying to to start a django project but have been having issues following the usual steps recommend to start a django project, some have been working some have not. For instance: pip django doens't work, throwing the error - bash: pip: command not found, while py -m pip django works. Similary when I try to check if django is installed django --version gives the error bash: django: command not, while this py -m django --version has no issues. So I figured just adding py -m would make all comands work, however when I try py -m django-admin startproject x to try and create my first django file but it gives the error "C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe: No module named django-admin" What can I do to make django-adming work and be able to create a project :( -
Django createsuperuser command not working after switching from username to email
So I changed the Django username field to 'email', which is documented as completely legal here, but after this, the createsuperuser method doesn't work. Of cause I have added the Auth model to my settings and it worked before. This is basically my model currently: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] After migrating the change createsuperuser throws this after every input is entered: XXX\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' I tried moving around this with a custom manager, but it threw new problems plus I would really would like to avoid this. Furthermore, I looked at the source code of the method, but couldn't figure out where this could go wrong. I also reset and deleted the database without luck. -
Django secret key on elastic beanstalk
Is there any reason why this isn't working anymore? I'm getting key must not be empty even though I have env variable set in EB console. https://stackoverflow.com/questions/47372082/django-secret-key-environmental-variable-not-working-in-elastic-beanstalk -
localhost vs. 127.0.0.1 in regards to CSS
So I've seen a few posts about the differences between localhost and 127.0.0.1 but nothing specifically regarding my question. I am currently creating a Django application which, when run, starts the application on 127.0.0.1:8000. My problem involves updating my CSS files and not always seeing changes when I refresh. Sometimes the changes will display on one of the two but not the other and was curious as to why this may be? I do currently have multiple CSS files as well as bootstrap files which I have downloaded the libraries for. Any general feedback on why these changes occur on one of the two but not the other would be appreciated! -
Django objects.filter vs objects.all
I have a question regarding the filter() and all() methods of django objects. It is not a question which one of the two is preferred, I just noticed an odd (to me) behavior. Because, as it is laid out in Django ORM - objects.filter() vs. objects.all().filter() - which one is preferred? in Django src, both ways should return the same (they both reference the chain() method): See: https://github.com/django/django/blob/0963f184abd96800b76b19a6a181e1b544c7fafe/django/db/models/query.py#L928 And: https://github.com/django/django/blob/0963f184abd96800b76b19a6a181e1b544c7fafe/django/db/models/query.py#L951 So the filter() and all() method should return the same objects. But I recently discovered the following behavior: MyModel.objects.all()[0].update(name="Test") # --> $: AttributeError: type object 'MyModel' has no attribute 'update' # And to check if it indeed has no update method: MyModel.objects.all[0].__dir__() # --> no update() method in returned dictionary but a save method So while above code raises Error, line below would work: MyModel.objects.all()[0].name = "Test" MyModel.objects.all()[0].save() However, if the same object is retrieved by the filter() method, it has the update() method. Why do I get the same object both times but with seemingly different methods added to it? -
How Can I Make The User Vote Only Once
so I'm trying to build a poll app with Django but I have a problem, I can't preventing a user from voting twice or more This is My Models.py class NewPoll(models.Model): Question = models.CharField(max_length=255,default=False) option1 = models.CharField(max_length=255) option2 = models.CharField(max_length=255) option3 = models.CharField(max_length=255) option1count = models.IntegerField(default=0) option2count = models.IntegerField(default=0) option3count = models.IntegerField(default=0) created_by= models.ForeignKey(User,related_name='newpoll',on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Question What I have in my vote view in views.py #some codes @login_required(login_url='signin') def vote(request,poll_id): newpoll = get_object_or_404(NewPoll,pk=poll_id) if request.method == "POST": selected_option = (request.POST['poll']) if selected_option == 'option1': newpoll.option1count +=1 elif selected_option == 'option2': newpoll.option2count +=1 elif selected_option == 'option3': newpoll.option3count +=1 else: return HttpResponse("Wrong Form!") newpoll.save() return redirect('result',poll_id=newpoll.pk) return render(request,'vote.html',{'newpoll':newpoll}) -
How to pass variable (list) to JavaScript in Django?
I am trying to create a chart Using Chartjs and Django, i have a problem when i am trying to pass the data from views.py to js code. so,this is my code in views.py.. def home(request): labels = ["A", "B", "C", "D"] data = [1,2,3,4] return render(request, 'home.html',{'labels': labels ,'data': data,}) and this is my part of code in home.html .. <script> var labels = {{labels}}; var data = {{data}}; var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: labels, datasets: [{ label:"chartLabel", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data:data, }] }, // Configuration options go here options: {} }); </script> put when i use these tow lines in js .. var labels = ["A", "B", "C", "D"]; var data = [1,2,3,4]; instead of this tow my code works fine. var labels = {{labels}}; var data = {{data}};