Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i solve it please? [closed]
when i run python manage.py makemigrations , i face this Error : book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) ^ SyntaxError: invalid syntax how can i solve it ? from __future__ import unicode_literals from django.db import models import uuid # requierd for unique book instance from django.urls import reverse class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) def get_absolute_url(self): return '%s, %s' %(self.last_name, self.first_name) class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="unique ID for this particular book across" book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'No loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book avaiable') class Meta: ordering = ["due_back"] def __str__(self): return '%s, (%s)' %(self.id, self.book.title) class Genre(models.Model): name= models.CharField(max_length=200, help_text=' Enter a book genre') def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) Author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the Book') isbn = models.CharField('ISBN', max_length=13, help_text='13 character <a href='# ') genre =models.ManyToManyField(Genre, help_text='Select a genre for this book') def__str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) -
Page not found (404) - No availability found matching the query
I'm getting a Page not found (404) on calling the Update and Delete views in my template. My models are in such a way that multiple Staff can have multiple Availability entries. So I created a view to list the availability entries of each staff and I thought it would make sense to use a URL pattern that uses both the staff's pk and the availability entry's pk in order to delete or update the specific availability entries of a staff. Example: To edit Staff #2's availability entry #4: http://127.0.0.1:8000/staff/2/availability/4/edit Any clue why I'm getting this error? I did some research and I'm wondering if I have to override the get_object method in the AvailabilityUpdateView and AvailabilityDeleteView? urls.py path('staff/availability/new/', views.AvailabilityCreateView.as_view(), name='availability_new'), path('staff/<int:pk>/availability/', views.AvailabilityListView.as_view(), name='availability_list'), path('staff/<int:pk>/availability/<int:pk_alt>/edit/', views.AvailabilityUpdateView.as_view(), name='availability_edit'), path('staff/<int:pk>/availability/<int:pk_alt>/delete/', views.AvailabilityDeleteView.as_view(), name='availability_delete'), Template <a href="{% url 'availability_edit' pk_alt=availability.pk pk=availability.staff.pk %}">Edit</a> | <a href="{% url 'availability_delete' pk_alt=availability.pk pk=availability.staff.pk %}">Delete</a> Views class AvailabilityUpdateView(UpdateView): template_name = 'crm/availability_form.html' form_class = AvailabilityForm model = Availability class AvailabilityDeleteView(UpdateView): template_name = 'crm/availability_confirm_delete.html' model = Availability success_url = reverse_lazy('staff_list') -
Unable to use RadioSelect buttons in Django to get an output
So I'm trying to basically create a site which takes in user input in form of RadiSelect buttons, and based on that button, a query has to be run on the database and results to be displayed. I am posting all the file sceenshots below: Models file Views file forms.py urls.py html file: html file Final output webpage being displayed if the person selects radio button of vendor 1, the output should be the money owed to vendor 1 by that user. I am unable to get where I am going wrong. Request you all to kindly help me out. -
Django - S3 - SQS Delivery Instead of Retrieving
I'm currently using Django with S3. When a new object is created a notification is sent through SQS.AWS documentation I'm receiving the notification by using boto3. Boto3 documentation.I can receive messages using the receive_message function, but I have to run the function every minute to see if new messages are available. Is there a way of getting the messages delivered automatically to my django app instead of having to retrieve them by continuously running a function every minute to see if there are new messages? Delivered instead of retrieved. -
Can I create a Django User Group from a CSV file?
I am creating a Django app using LDAP among other things. I am creating an admin view that will be based on an AD group. What I have so far: 1) A script that can pull AD group users/info and stores it in a CSV 2) A conditional in my view that changes what the user sees depending on whether or not they are in said group What I need: 1) A way to transfer that CSV data into a Django group so that new users will be added as an admin of the app once they are added to the AD group. Does anyone have experience with something like this? I honestly just have no idea where to start with this and just wanted to know if the capability exists period. -
Error while setting up Django. class 'werken' has no objects
`from django.shortcuts import render, redirect, get_object_or_404 from .models import Werken Create your views here. def home(request): werken = Werken.objects return render(request, 'werken/werken.html', {'werken': werken}) def detail(request, werken_id): werk = get_object_or_404(Werken, pk=werken_id) return render(request, 'werken/detail.html', {'werk': werk})`the error i have is: { "resource": "/c:/Users/jarmo/OneDrive/Bureaublad/project-challenge/portfolio-project/werken/views.py", "owner": "python", "code": "no-member", "severity": 8, "message": "Class 'Werken' has no 'objects' member", "source": "pylint", "startLineNumber": 7, "startColumn": 14, "endLineNumber": 7, "endColumn": 14 } the error -
Django get PK dynamically from views.py
I have a view that renders a comment form along with a template: views.py def news(request): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = Article.objects.get(pk=2) print(comment.post) comment.author = request.user.username comment.save() return HttpResponseRedirect('') else: form = CommentForm() return render(request, '../templates/news.html', context={"form": form}) models.py class Comment(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments', blank=True) author = models.TextField() text = models.TextField() def __str__(self): return self.text forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ('text',) In views.py, where comment.post is getting assigned to Article objects, I want the pk to be applied dynamically. I tried doing it in the templates, where putting {{ article.pk }} in the templates output the right pk for the Article object but I wasn't sure how I'd go about applying it to my form. The templates look simple: Article object, below it a comment form. The problem is simple, I want the news(request) function to dynamically apply the pk of the current Article object in order to make the comment go to the right post. -
Django webapp for Neo4jdata-exploration
I'm building a webapp with python (django) I would like to integrate one page allowing the user to explore the data in a neo4j like environment. Likely I imagine it to be a tabular view of a fixed cypher query on the right, the linked-data visualisation with the bubbles on the right. On the top a search field that can allow some filtering options on the query in real time both in the tabular view and the bubble view, possibly clicking on a bubble it would highlight the corresponding value in the tabular view. Do you think this is possible? Are there any examples I can take inspiration from online? Any opinion on your side before jumping straight into the development (I saw different libraries for the integration of neo4j in django, but I'm not sure which one is the best for me, some really just seem data querying - upload to/download from neo4j using django. I'm sorry if this is not totally clear, hope you will find the time to give me some of your precious advices. -
Django How to update model object fields from external api data
I have a script which runs on a scheduler to get data from an api which I then intend to use this data to update the current database model information. My model ShowInfo within main/models.py: from django.contrib.auth.models import User class ShowInfo(models.Model): title = models.CharField(max_length=50) latest_ep_num = models.FloatField() ld = models.BooleanField() sd = models.BooleanField() hd = models.BooleanField() fhd = models.BooleanField() following = models.ManyToManyField(User, related_name = 'following', blank=True) I managed to isolate the issue to this section of the script: else: #test if api fails for t in real_title: if t in data_title: #testing if the titles in the database and from the api match a = ShowInfo.objects.get(title=t) id = a.id b = next(item for item in show_list if item["title"] == t) a1 = ShowInfo(id = id, title = b["title"], latest_ep_num=b["latest_ep_num"], ld=b["ld"], sd=b["sd"],hd=b["hd"],fhd=b["fhd"]) a1.save() Some additional info about the lists (where show_list is a list of dictionaries gotten from an api): database = ShowInfo.objects.values() real_title = [] data_title = [] for show in show_list: real_title.append(show["title"]) for data in database: data_title.append(data["title"]) When the script runs I notice from browsing my database with DB Browser for SQLite that the objects were being inserted and not updating as i intended. The script is supposed to … -
How to stop AJAX function from running if form validation error
Submitting an video upload form via AJAX but the function continues to run if the form validation fails. To be more concise; the data success == True, but the form validation fails. $(document).ready(function(){ $(function () { var pleaseWait = $('#pleaseWaitDialog'); showPleaseWait = function () { pleaseWait.modal('show'); }; hidePleaseWait = function () { pleaseWait.modal('hide'); }; }); var $myForm = $('.form') $myForm.on('submit', function(event){ event.preventDefault(); var form = $(event.target) var formData = new FormData(form[4]); $.ajax({ xhr: function() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { showPleaseWait(); // <--------------- This runs even when view returns error console.log('Percentage uploaded: ' + (e.loaded / e.total)) var percent = Math.round(e.loaded / e.total * 100); $('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%'); } }); return xhr; }, type: 'POST', url: form.attr('action'), enctype: 'multipart/form-data', processData: false, contentType: false, data: new FormData(this), success: function(data){ if (data.success) { window.location.href = data.url; } else if (data.error) { $("#top").html(data.error.title).addClass('form-field-error'); $("#div_id_title").removeClass('form-group'); } // <----------------- I want it to stop here }, error: function(xhr, status, error){ alert('err'); } }); }, ); }); How do I stop the function where the comment is? -
Extracting json dict from POST request
I want to make use of webhook provided by Townscript to update the is_paid field in my model. The format of the data is (a json dict):- link(Under server notification API column). A piece of useful information on the link was: We will send the data in following format using post parameter data. Here is the python code: def payment(request): if request.method == "POST": posts=request.POST["data"] result=json.dumps(posts) #converting incoming json dict to string paymentemail(result) # emailing myself the string (working fine) data = posts try: user = Profile.objects.filter(email=data['userEmailId']).first() user.is_paid = True user.save() except Exception as e: paymentemail(str(e)) # emailing myself the exception return redirect('/home') else: ....... The two emails correspoinding to the paymentemail() function in the above code were: "{\"customQuestion1\":\"+9175720*****\",\"customAnswer205634\":\"+917572******\", \"customQuestion2\":\"**** University\",\"customQuestion205636\":\"College Name\",\"ticketPrice\":**00.00, \"discountAmount\":0.00,\"uniqueOrderId\":\"***********\",\"userName\":\"********\", \"customQuestion205634\":\"Contact Number\",\"eventCode\":\"**********\",\"registrationTimestamp\":\"12-12-2019 22:22\", \"userEmailId\":\"***********@gmail.com\",etc....}" I understand that the backslashes are for escaping the quotation marks. Second email: (which is the exception) string indices must be integers Does that mean that data=request.POST['data'] gives me a string thus leading to an error when I use data['userEmailId']? How do I deal with this error? -
Django: How to change where staticfiles are stored?
I'm wanting to make it to where my staticfiles are stored in my project directory instead of my base directory when I run python manage.py collectstatic I want my base project directory to look like this: myproject/ app1 app2 app3 myproject/ staticfiles settings.py urls.py instead of this (normal version): myproject/ app1 app2 app3 myproject staticfiles I'm not totally sure how best to go about doing this. I've read the relevent docs and couldn't make sense of how to change where staticfiles are stored. Doc references: https://docs.djangoproject.com/en/3.0/howto/static-files/ https://docs.djangoproject.com/en/3.0/ref/settings/#static-files I've tried a couple of variations of my STATIC_ROOT setting: # version 1: STATIC_ROOT = os.path.join(BASE_DIR, "myproject/static") # version 2: STATIC_ROOT = os.path.join(BASE_DIR, "/myproject/static/") and neither of those worked to move where the staticfiles are stored. I would really appreciate some feedback on how to make this work. Thanks! -
Django sends TypeError: 'module' object is not iterable when adding Meta in Form
I've googled this error, but none of the answers I've seen seem to apply to my problem, which is this: I recently imported a Django project, and have been working on it, and it worked, until I was adding CRUD methods and views for a model. I added everything I needed, but when running the server, I got this error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\urls\resolvers.py", line 596, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'quiniela.urls' does not appear to have any … -
CSRF token missing or incorrect. Django + jQuery File Upload
I trying to implement jQuery File Upload on Django project. But every time I submit an image, an error has occurred: "CSRF verification failed. Request aborted." models.py class Photo(models.Model): title = models.CharField(max_length=255, blank=True) image = models.ImageField(upload_to='photos/') uploaded_at = models.DateTimeField(auto_now_add=True) main.js $(function () { /* 1. OPEN THE FILE EXPLORER WINDOW */ $(".js-upload-photos").click(function () { $("#image-upload").click(); }); /* 2. INITIALIZE THE FILE UPLOAD COMPONENT */ $("#image-upload").fileupload({ dataType: 'json', done: function (e, data) { /* 3. PROCESS THE RESPONSE FROM THE SERVER */ if (data.result.is_valid) { $("#gallery tbody").prepend( "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>" ) } } }); }); template.html {# 1. BUTTON TO TRIGGER THE ACTION #} <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos </button> {# 2. FILE INPUT TO BE USED BY THE PLUG-IN #} <input id="image-upload" type="file" name="file" multiple style="display: none;" data-url="{% url 'add_location_step_3_url' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"'> {# 3. DISPLAY THE UPLOADED PHOTOS #} {% for photo in photos %} <a href="{{ photo.file.url }}">{{ photo.file.name }} {% endfor %} -
I want to connect nginx and django on openshift
So I have an instance of nginx running on my openshift and another pod for a django app, the thing is I don't know how to connect both services. I'm able to access hte default url for nginx and the url for django. Both are working fine but I don't know how to connect both services. Is there a way to do it modifying the yaml of the services or the pods? I already try to build the container myself of nginx and is giving me permission issues, so I'm using a version of nginx thats comes preloaded in openshift. Any help would be greatly appreciated. thank you so much. -
Django create_superuser() missing 1 required positional argument: 'username'
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('user must have smartcard') if not username: raise ValueError('must have username') user = self.create_user( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin =True user.is_staff =True user.is_superuser=True user.save(using=self._db) return user class Account(AbstractBaseUser): username = models.CharField(max_length=100, unique=True) email = models.EmailField(verbose_name="email", max_length=30, unique=True) department = models.CharField(max_length=30, choices=DEPARTMENT) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['username',] objects=MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True I just can't get what is wrong. While creating a superuser the prompt doesnt ask me for entering username I modified the settings.py file as well. Tried several times with various databases. I have also added the username in REQUIRED_FIELDS section. -
Django Pass id to URL after .exist query
i have created a view set where it carry out a check if the User has created the object or not, in case the object is not created it will redirect him to a form to fill it and if is exist it will redirect him to the next step. my current challenge is how to pass the id to the next view and set the foreign key based on it. models.py: class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False ) class Startup_About ( models.Model ) : str_about = models.ForeignKey ( Startup , on_delete = models.CASCADE ) about = models.TextField ( 'About Startup' , max_length = 2000 , null = False , blank = False ) problem = models.TextField ( 'Problem/Opportunity' , max_length = 2000 , null = False , blank = False ) business_model = models.TextField ( 'Business Monitization Model' , max_length = 2000 , null = False ,blank = False ) offer = models.TextField ( 'Offer to Investors' , max_length = 2000 , null = False , blank = False ) def … -
AttributeError: /usr/lib/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64 While installing in Docker
Getting error while installing GeoDjango on docker with postgres db. I'm completely new to docker and i'm setting up my project on docker. I don't know, is this error is regarding django or postgres. Found this error AttributeError: /usr/lib/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64 While installing in Docker web/Dockerfile from python:3.6.2-slim RUN groupadd dev && useradd -m -g dev -s /bin/bash dev RUN echo "dev ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers RUN mkdir -p /home/dev/app/HomePage RUN chown -R dev:dev /home/dev/app RUN chmod -R +x+r+w /home/dev/app WORKDIR /home/dev/app/HomePage RUN apt-get update && apt-get -y upgrade COPY requirements.txt /home/dev/app/HomePage RUN apt-get install -y python3-dev python3-pip RUN apt-get install -y libpq-dev RUN apt-get install -y binutils libproj-dev gdal-bin RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY ./docker-entrypoint.sh / RUN chmod +x /docker-entrypoint.sh USER dev ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] web/docker-entrypoint.sh #!/bin/sh python manage.py makemigrations python manage.py migrate python manage.py runserver 0.0.0.0:8000 docker-compose ps : root@BlackCat:/home/dev/Project-EX/django-PR# docker-compose up Starting django-pr_postgres_1 ... done Starting django-pr_web_1 ... done Attaching to django-pr_postgres_1, django-pr_web_1 postgres_1 | 2019-12-12 16:34:43.907 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2019-12-12 16:34:43.908 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_1 | 2019-12-12 16:34:44.099 UTC … -
Sync all tables from sqlite to postgres
I have a django application and deployed it on DigitalOcean. But the only problem is, new models, admin models, tables are not showing in django admin dashboard which is on running on server. Although I pushed al changes to github, pulled them from, and made migrations, again nothing changes. How can migrate all tables from db.sqlite3 to postgresql ? -
DRF - How do I whitelist a site for endpoint requests
This is my scenario: Hosted Django application running DRF External site hosted elsewhere. Could be multiple sites. My question is: How do I whitelist any Javascript POST request from an external site? For example I want to add a Javascript post request on a forms confirmation page. How do I do this so my DRF application only accepts requests from this site only? I'm trying not to use server site code. Just Javascript so it easily applied. My concern is anyone that views the source will be able to view the API endpoint and would be able to submit POST requests. -
Django: request.META.get('HTTP_REFERER') returns None after Ajax call
I am using request.META.get('HTTP_REFERER') to get the referrer page from where current request is made. This function work fine when I am using HttpResponse to render UI. But, if there is an Ajax call which returns JsonResponse to the page, then request.META.get('HTTP_REFERER') return None. Please guide me to solve this problem. Thanks -
I am using a phonenumbers module for validating phone numbers. It works well,however I just need the National number as output
import phonenumbers ph_no = "918332 88 1992" print(phonenumbers.parse(ph_no, "IN")) Output: Country Code: 91 National Number: 8332881992 Desired Output: 8332881993 I just need the phonenumber to return. Please help! -
django form.is_valid returns false
When ever I submit my form and check the form is not getting submited and is redirected. The validation is always false. I entered all the fileds and it still shows the same. Why is this keep showing like this? is there something wrong? Below are the files i use views,template, and forms. views.py def signincheck(request): if request.method == "POST": formsignin = FormSignup(request.POST,request.FILES) if formsignin.is_valid(): return HttpResponse("Password not match 3") TbluserVar=Tbluser() TbluserVar.firstname=formsignin.cleaned_data['firstname'] TbluserVar.lastname=formsignin.cleaned_data['lastname'] TbluserVar.username=formsignin.cleaned_data['username'] Password=formsignin.cleaned_data['password'] ConfirmPassword=formsignin.cleaned_data['confirm_password'] TbluserVar.mobilenumber=formsignin.cleaned_data['mobilenumber'] Tbluser.dateofbirth=formsignin.cleaned_data['dob'] Tbluser.dateofjoining=datetime.datetime.today() Tbluser.userlevel=0 if Password != ConfirmPassword: messages.error(request,'Password and Confirm Password does not match') return redirect('/') else: try: user = Tbluser.objects.get(username=formsignin.cleaned_data['username']) messages.error(request,'Username not available. Try another one.') return redirect('/') except: PasswordEnc=hashlib.md5(Password.encode()) RealPassword=PasswordEnc.hexdigest() TbluserVar.passwordenc=RealPassword TbluserVar.save() request.session['username']=TbluserVar.username request.session['getFirstandLastName']=TbluserVar.firstname + " " + TbluserVar.lastname FullName=request.session['getFirstandLastName'] return redirect('/index') else: return redirect('/') else: return HttpResponse("NOT CORRECT") forms.py class FormSignup(forms.Form): firstname=forms.CharField( max_length=30, widget=forms.TextInput(attrs={'placeholder': 'First Name...','class':'loginform'})) lastname=forms.CharField( max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Last Name...','class':'loginform'})) username=forms.CharField(max_length=30,widget=forms.TextInput(attrs={'placeholder': 'User Name...','class':'loginform'})) password=forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder': 'Password...','class':'loginform'})) confirm_password=forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password...','class':'loginform'})) mobilenumber=forms.CharField(max_length=30,widget=forms.TextInput(attrs={'placeholder': 'Mobile Number...','class':'loginform'})) dob=date = forms.DateTimeField( input_formats=['%d/%m/%Y'], widget=forms.TextInput(attrs= { 'class':'datepicker', 'placeholder': 'Date of Birth...' })) template.html <div class="modal fade" id="modalSignUpForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Sign in</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form id="idlognform" method="POST" action="{% url … -
Javascript-ajax not working in django template
I'm trying to use javascript-ajax to load pages without refreshing, it works fine on the home page. on the home page i have a sidebar containing adverts and other list items, when i click on advert, it shows me a page that has two views (forms), listview and create view. i hid view B so that when i click on the button in view B, it hides the form and shows view A. now the problems are, 1. the onclick function is not working on the home page, but if i run adverts as a page on its own it works very well 2. if i unhide view A such that both forms A and B show when i click on adverts from the home page, and i fill the form in view A it doesn't save to the database, but if i run the adverts.html on its own it saves and shows the form B here are my codes: home.html {% load staticfiles %} {% block content %} <head> <meta charset="UTF-8"> ... <title> {% block title %}News Central Scheduler App{% endblock %} </title> <link rel="stylesheet" href="{% static 'style.css' %} "/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"/> </head> <div class="clearfix"> </div> … -
Python/Django - Adding choices to a choice field through model submission
I'm building an API for communication from one application (the master database program) to a separate reporting application. Within my reporting application models, I have several fields with choices. These choices live within a separate choices.py file. However, when the master application creates a new instance within my reporting app, I want to ensure that if the value is not found in the choices list, that the choice is added to the list and then selected. What is the best practice or way to make this possible? Thanks!