Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to update a record rather than raise error on duplicate id
I guess what I need to do it overwrite my model's save method but do correct me if I'm wrong/have better suggestion. This is what my model looks like: class MergingModel(models.Model): some_field = models.TextField() And this is the unit test that I want to pass: class MergingModelTests(TestCase): def test_duplicates_are_overwriten(self): MergingModel.create(id=1) MergingModel.create(id=1, some_field="abc") self.assertEquals(MergingModel.objects.count(),1) self.assetEquals(MergingModel.objects.get(id=1).some_field,"abc") I tried overwriting save method to check if record with id=x exists but that raised recursion errors, my code for save method looked like: def save(self, *args, **kwargs): if MergingModel.objects.filter(id__exact=self.id): original = MergingModel.objects.get(id=self.id) original.some_field = self.some_field original.save() else: super().save( *args, **kwargs) Then I tried overwriting create but I get error: Key (id)=(ID1) already exists So I'm not really sure what to do anymore. -
pywin32 shutdown django runserver
when I use pywin32 as editing excel sheet django runserver is died when for loop is executing django is died here's my code for i in range(14,36): data = {} cell_number = 'A'+str(i) cell_date = 'B'+str(i) cell_content = 'C'+str(i) cell_completed = 'G'+str(i) cell_memo = 'H'+str(i) data = {'number' : worksheet.Range(cell_number).Value} data = {'date' : worksheet.Range(cell_date).Value} data = {'content' : worksheet.Range(cell_content).Value} data = {'completed' : worksheet.Range(cell_completed).Value} data = {'memo' : worksheet.Range(cell_memo).Value} data = {'cells' : cell_number+'/'+cell_date+'/'+cell_content+'/'+cell_completed+'/'+cell_memo} data = {'sheetName' : sheetName} # data = {'filepath' : filepath} excelData.append(data) -
how receive http post in django
send http post import requests payload = [{'name': 'pippo', 'age':'7'}, {'name':'luca', 'age':'12'}] r = requests.post("http://127.0.0.1:8000", data=payload) print(r.url) Receive Http post in django from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from home.models import Post @csrf_exempt def home(request): all_post = Post.objects.all() context = {'request_method': request.method} if request.method == 'POST': context['request_payload'] = request.POST.dict() post_data = dict(request.POST) print(post_data) if request.method == 'GET': context['request_payload'] = request.GET.dict() return render(request, 'main/index.html', context, {'all_post':all_post}) in print(post_data) i not see [{'name': 'pippo', 'age':'7'}, {'name':'luca', 'age':'12'}] why? where is my error? -
Filter drop-down options in a django form based on logged-in user
I have a django form to create a new instance (record) of a class called Ticket. The users can be from different clients so I need to limit the options displayed in the drop-downs to the logged-in user's client basically. client is an attribute of a class that I have defined in admin.py, which defines the client name of the user. I know that I am on the right path, but I have a difficult making this work since I need to extract the client of the logged-in User and then use it to filter the fields (for example business) when initializing the form, any help would be appreciated? Please consider that I have multiple fields that should be filtered so if there is a way to do this once for all of the fields it would be great: models.py class Business(models.Model): client=models.ForeignKey('Client',on_delete=models.CASCADE, limit_choices_to={'is_active':True},) name=models.CharField(max_length=30,blank=False, unique=True,) description = models.CharField(max_length=50, blank=True, ) is_active=models.BooleanField(default=True,) class Ticket(MMRequestAttributes): no=models.CharField('Ticket Number',max_length=50,default=uuid.uuid4,null=False, blank=False, editable=False, unique=True) client=models.ForeignKey('Client',on_delete=models.CASCADE, limit_choices_to={'is_active':True},) subject=models.CharField('Subject',max_length=100,null=False, blank=False) business=models.ForeignKey('Business', on_delete=models.CASCADE,limit_choices_to={'is_active':True},) admin.py class UserExtend(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False,null=False,) client=models.ForeignKey('Client', on_delete=models.CASCADE,limit_choices_to={'is_active': True},) class Meta: verbose_name_plural='User Extends' forms.py from django import forms from .models import Ticket from .admin import UserExtend class NewTicket(forms.ModelForm): def __init__(self,user): self.business.queryset=business.objects.filter(client.id=userextend.client_id) class Meta: … -
Creating Django form questionnaire with radio buttons
I'm attempting to implement a survey within my django application. Currently I have it implemented by manually drawing out the HTML for the form structure like so: <!-- Question 1--> <form method="post" action="{% url 'piuserform' %}"> {% csrf_token %} <div class="mx-auto"> <h3 class="mb-4">At the time of the accident, the injured party was: </h3> <label class="radcontainer">The driver of an automobile. <input type="radio" name="question1" value="The driver of an automobile"> <span class="checkmark"></span> </label> <label class="radcontainer">The passenger of an automobile. <input type="radio" name="question1" value="The passenger of an automobile"> <span class="checkmark"></span> </label> <label class="radcontainer">A pedestrian. <input type="radio" name="question1" value="A pedestrian"> <span class="checkmark"></span> </label> </div> <!-- /Question 1 --> <!-- question 3--> <div class="mx-auto pt-5"> <h3 class="mb-4">How many vehicles were involved in the accident?</h3> <label class="radcontainer">One <input type="radio" name="question3" value="One"> <span class="checkmark"></span> </label> <label class="radcontainer">Two <input type="radio" name="question3" value="Two"> <span class="checkmark"></span> </label> <label class="radcontainer">Three <input type="radio" name="question3" value="Three"> <span class="checkmark"></span> </label> <label class="radcontainer">Four or more <input type="radio" name="question3" value="Four or more"> <span class="checkmark"></span> </label> </div> <!-- /Question 3 --> Now I tried to implement something to this effect using Django forms api but it would only render the last question. The questionnaire is all radio buttons with the answer fields varying greatly. Is there a way … -
Django doesn't commit changes to MySQL database
My web-app is deployed on two different VPS on different subnets, one for Django and the other for database. the problem is that whenever i send a request to server it takes about 10 second to get response (waiting time)! i have no idea how to fix it , i set the 'CONN_MAX_AGE' parameter to None and now the response time is OK! but Django doesn't commit any change that i make on database and as you restart the app server all the changes rolls back! does anyone has an idea about? thanks -
Context variables set in a for loop are reset each time
I'm running Django 1.11 on Python 3.6. I have written a custom template tag next_i so that each time I call it it will add 1 to the output. @register.simple_tag(takes_context=True) def next_i(context): if 'i' not in context: context['i'] = 0 context['i'] += 1 return context['i'] What I expect it to do is outputting 1, 2, 3 in sequence, e.g. <p>{% next_i %}</p> <p>{% next_i %}</p> <p>{% next_i %}</p> <p>{% next_i %}</p> <p>{% next_i %}</p> Will become 1 2 3 4 5 This works fine until I started using for loops in the template, e.g. <p>{% next_i %}</p> {% for section, subsections in sections %} <p>{% next_i %}</p> {% endfor %} <p>{% next_i %}</p> where sections is a list of tuples. Each tuple has 2 elements to unpack and the list itself has a length of 3. What I expect it to do is to give me 1, 2, 3, 4, 5. However it gives me 1, 2, 2, 2, 2. More amazingly, if I don't unpack the tuples, i.e. {% for t in sections %}, it will give me 1, 2, 3, 4, 2. I really don't understand what's going on here. Am I not supposed to change context in … -
Websocket with Django channels doesn't work, connection failed
I created a chat room with django-channels. Every time I try to connect to my chat room via web socket in production, it fails. Locally it works correctly. I host on digitalocean pip freeze: channels==2.1.2 channels-redis==2.3.0 daphne==2.2.1 ''' I have installed the redis-server with sudo apt-get install redis-server Here's my settings. INSTALLED_APPS = [ # ''' 'channels', # ''' ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } ASGI_APPLICATION = "project_name.routing.application" Here's my asgi.py alongside wsgi.py import os import django from channels.routing import get_default_application from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings") django.setup() application = get_default_application() And here's my project_folder.rounting.py application = ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ # my urls ]) ) ) }) I keep getting this in firefox and something similar in other browsers: Firefox can’t establish a connection to the server at wss://www.domain_name.com/url-to/1/XBvZjr2pqdf6fhy/ However it works locally. I really need your helps, thanks in advance. Let me know if you want further information. -
Django ModelChoice Field Conditional ForeignKey
I've surfed most of the afternoon and have been at this particular quandry for a while. I am trying to figure out how to essentially present a foreign key as a dropdown choice if the user has driven that type of car. For example purposes and to keep this as easy as possible... Let's say I have cars and manufacturers and a userprofile model. I have a model for Cars as so... class Cars(models.Model): car_name = models.CharField(max_length=80) class = models.ForeignKey(Manufacturer,null=True,on_delete=models.DO_NOTHING,related_name='car_manufacturer') I have a model for Manufacturers as so... class Manufacturers(models.Model): manu_name = models.CharField(max_length=80) Then I have a userprofile model.... class Userprofile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) user_name = models.CharField(max_length=80) car_owned = models.ForeignKey(Car,null=True,on_delete=models.DO_NOTHING,related_name='car_owned') All good so far... I have a view where I am listing all of the Manufacturers and this works fine as well. It shows all of the manufacturers that I would expect in the form view below. class ManufacturerForm(forms.Form): dropdown = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) def __init__(self, *args, **kwargs): super(ManufacturerForm, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices1' self.fields['dropdown'].empty_label = '' I'm using the FORMVIEW below to display the form... class ManufacturerView(LoginRequiredMixin,FormView): form_class = ManufacturerForm template_name = 'Directory/HTMLNAME.html' def get_form_kwargs(self): kwargs = super(ManufacturerView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): manufacturer = form.cleaned_data['dropdown'] return … -
Search and Display in same view
I am learning Django and I am wondering if there is a better way to do this. Basically I am trying to get movies from the IMDbPy API and display the movie information. As of now I am using one view that gets the information and also displays it (using two different templates). Is this the right way to do this? Or should I split this onto two different views? If so, how do I do this? Views def get_movie_name_view(request): form = GetMovieName(request.POST or None) if form.is_valid(): ia = IMDb() movies = ia.get_movie(form.cleaned_data['movie_title']) context = {'title': movies['title'], 'directors': movies['directors'], 'runtime': movies['runtime'], 'year': movies['year'], 'genre': movies['genres'], 'form': form } return render(request, 'show_movie_info.html',context) context = { 'form': form } return render(request, 'get_movie_name.html', context) Model class Movie(models.Model): title = models.CharField(max_length=250) directors = models.CharField(max_length=300) runtime = models.IntegerField() year = models.DateField() genre = models.CharField(max_length=100) forms class GetMovieName(forms.Form): movie_title = forms.CharField(label='Movie Title', max_length=100) Get Movie template {% extends 'base.html' %} {% block content %} <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit", value="Submit" /> </form> {% endblock %} Show movie template {% extends 'base.html' %} {% block content %} <p> Title: {{ title }} </p> <p> Duration: {{ runtime }} minutes </p> <p> Director: {{ directors … -
django program yields incorrect output
I'm writing a program in Django to compare two uploaded files, find the correct differences, mark those different respectively, and produce the output. The program is to find if anything that is "Added," "Changed," or "Deleted." Currently, "Deleted" doesnt work (function and mark wise). Also the program doesnt print the differences (mark wise) respectively, so it knows(functionality) "Added" and "Changed" it just always prints the results as "Changed". Here is views.py from django.shortcuts import render from django.http import HttpResponse import difflib import datetime import csv from django.http import HttpResponseRedirect from django.http import FileResponse from .forms import FileForm from .forms import UploadFileForm def handle_uploaded_file(file1,file2): # handle_uploaded_file is a function that takes 2 files uploaded by the users fileone = file1.readlines() # define fileone and read lines from 1st file filetwo = file2.readlines() # define filetwo and read lines from 2nd file fileone =[line.decode("utf-8").strip() for line in fileone] filetwo =[line.decode("utf-8").strip() for line in filetwo] header = fileone[0].strip().split(',') # print(header) csv_old = [x.strip().split(',') for x in fileone[1:]] # print(csv_old) old_keys = [x[0] for x in csv_old] old_rows = {} for row in csv_old: key = row[0] if key in old_rows: old_rows[key].append(row) else: old_rows[key] = [row] csv_new = [x.strip().split(',') for x in filetwo[1:]] new_rows … -
Advanced django queries
I have three models: a company, an asset, and a user. Each company has many assets (ForeignKey), and each asset has a single user (ForeignKey, since a user may own more than one asset). I want to run a query that returns a list of companies in which a given user owns assets, and the number of assets that they own in each company. I have tried doing this in python, like this: companies = Company.objects.filter(asset__owner=self.request.user) context['investments'] = [(x, Asset.objects.filter(company=x, owner=self.request.user).count()) for x in companies] Perhaps unsurprisingly, this is incredibly slow, since a company can have 100,000 assets. It seemed that this would be better done at the database level, which led me to look at annotation and aggregation, but I couldn't get anywhere. Could somebody point me in the right direction? -
django - dynamic query on form field
Lets say I have a form with some fields. I was wondering if it is possible to do dynamic query where I could do a string match while the user is typing into a field. Like when typing into google it returns a list of choices when you type into the search bar. Can someone give me an example on how and where to implement it? -
How to create a temp boolean field with Django orm
Image I have following models: class Product(models.Model): name = models.CharField(max_length=20) class Receipt(models.Model): product = models.ForeignKey(Product) user = models.ForeignKey(User) I have an input list of product ids and a user. I want to query for each product, whether it's been purchased by this user. Notice I need a queryset with all exist products based on given input because there are other fields I need for each product even not purchased by this user, so I cannot use Product.objects.filter(receipt__user=user). So can I create a temp Boolean field to present this property in one single query? I am using Django 1.8 and postgresql 9.3 -
Calling a task via celery beat which is inside a folder throws Error
I have the following celery beat schedule CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'frontend.tasks2.tasks.test_task', #this doesn't work throws following error 'schedule': 1.0 }, } and the following error comes when I start celery beat and worker [2018-08-20 19:26:31,606: ERROR/MainProcess] Received unregistered task of type 'frontend.tasks2.tasks.test_task'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? I have the following project structure frontend |-tasks2 | |-tasks.py | |-test_task() |-tasks.py |-test_task() But if I change the beat schedule to following it starts working, both test_task() functions are same. CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'frontend.tasks.test_task', # this does work properly 'schedule': 1.0 }, } Where have I gone wrong? -
Error while uploading image from my mobie devices?
This is my models.py file class Report_item(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity') item_type = models.CharField(default="", max_length=100, help_text='*Enter the item name you found e.g. Marksheet,key,wallet') location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item') city = models.CharField(max_length=60, help_text='*Enter the city name') date = models.DateTimeField(default=timezone.now) Description = models.TextField(blank=True,null=True,help_text='*Enter full description about item') publish = models.BooleanField(default=False) image = models.ImageField(default="add Item image", help_text='*Please uplocad a item image to identify by the owner') def __str__(self): return self.title + " " + str(self.publish) def get_absolute_url(self): return reverse('feed:detail', kwargs={'pk': self.pk}) class Meta: ordering = ["-date"] This is my upload views: class ReportCreate(generic.CreateView): model = Report_item fields = ['title', 'item_type', 'location', 'city', 'image', 'Description'] def form_valid(self, form): self.object = form.save(commit=False) self.object.owner = self.request.user self.object.save() return FormMixin.form_valid(self, form) This is my view.py file def IndexView(request): query_list = Report_item.objects.filter(publish=True) query = request.GET.get('q') if query: query_list = query_list.filter(Q(title__icontains=query) | Q(item_type__icontains=query) | Q(city__icontains=query) | Q(location__icontains=query) | Q(Description__icontains=query)).distinct() context = { "object_list": query_list } return render(request, "feed/index.html", context) This is my feed/index file {% for obj in object_list %} <div class="thumbnail" onclick="window.open('{% url 'feed:detail' obj.id %}','mywindow');" style="cursor: pointer;"> <div class="row"> <div class="col-md-9"> <table class="mytable table-responsive"> <tr><td class="my-td-item">Title</td><td>{{ obj.title }}</td></tr> <tr><td class="my-td-item">Item Type</td><td>{{ obj.item_type … -
How can I use model relationships to associate my preorder model with my customer model in the admin without creating new objects each time
How can I associate a customer with a preorder object from another model, while not creating a bunch of objects for that model? I have a Customer and Preorder model: class Preorder(models.Model): product = models.CharField(max_length=100, default='') price = models.DecimalField(max_digits=12, decimal_places=2, default=None) quantity = models.IntegerField(default=1, ) def __str__(self): return self.product class Customer(models.Model): preorders = models.ManyToManyField(Preorder, blank=True, default=None) name = models.CharField(max_length=100, default='') email = models.EmailField(max_length=200, default='') credit = models.DecimalField(max_digits=12, decimal_places=2, default=None, null=True, blank=True, verbose_name='Store Credit') def __str__(self): return self.name In my admin, I'd like to add available preoder items to the Preorder model, and in the Customer change page, select from a list of available preoders, and add the Customer to a list of of Customers that have preordered that specific product. I thought a many to many relationship would be the best field to relate these items, but I'm having a tough time figuring out how to change the settings etc. to produce the exact results I want. It seems that I can't just display a static list of unique preorder items in the Customer change page, instead I get a list of every object in the Preorder database, and if I want to link the customer with an existing preorder … -
django upload file with custom name and directory name
i want to setup my django models for upload file with custom path and filename, my curent models : def update_filename(instance, filename): path = "accounts/" format = instance.id + "/" + filename return os.path.join(path, format) class AccountsModel(models.Model): ChannelName = models.CharField(max_length=100, unique=False) AuthUri = models.CharField(max_length=250, unique=True) ClientSecret = models.CharField(max_length=250, unique=True) ClientID = models.CharField(max_length=250, unique=True) ClientSecrets = models.FileField(upload_to="accounts/", default='', null=True, blank=False) RequestToken = models.FileField(upload_to="accounts/", default='', null=True, blank=False) Note = models.CharField(max_length=250, unique=False) counter = models.IntegerField(default=0) author = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) when i try to upload file, i want to be like this : /accounts/22/clientsecret.json /accounts/22/token.json my curent configuration return this error : UNIQUE constraint failed: myupload_accountsmodel.ClientID how i can do this ? Where i wrong ? full project : https://github.com/scaltro/youtubeapp/blob/master/myupload/models.py -
Post to django view from another view
Facing some constraints in a website, I was obligated to try to post data to some view from another view (I suppose it does make sense), like: def view1(request): if request.method == 'POST': value = request.POST.get('h1') ''' ''' And in my view2, I would do something like: def view2(request): if constraint: python.post(/url/view1/,data={'h1':1}) # Doesn't exist # Just a demonstration Is there a way to do what I want? -
Dealing with Django's TimeField for durations in a legacy database
I am dealing with a legacy database, and am building a Django application on top of it. One of my models has a duration field that is stored as TIME in MySQL and has values greater than 24 hours. This causes issues with Django’s TimeField, which only accepts values up to 24 hours because it is represented by datetime.time. I do not want to use Django’s DurationField because that stores its data as an integer representing the number of milliseconds on the database level, and I don’t want to change the database. What would you recommend? Writing a custom field type? -
Django Form Validation for Boolean Values Not Working
I have a simple HTML form that I'm trying to validate with a Django Form. The problem is that Django's form validation will only recognize the value of is_kit if it is 'True'. (When it is 'False', it will give an error saying that the field is required. Here is the form: <form method="post"> {% csrf_token %} <input type="hidden" name="part_id" value="{{ part.id }}" /> <input type="hidden" name="is_kit" value="False" /> <input type="submit" class="btn btn-link" value="Add to Cart"/> </form> And here is the Django form: class AddItemToCartForm(forms.Form): part_id = forms.IntegerField() is_kit = forms.BooleanField() And here is the relevant part of my view: def post(self, request, id): print(request.POST) print(request.POST.get('is_kit')) form = AddItemToCartForm(request.POST) print(form.errors) The output my server gives is here: <QueryDict: {'is_kit': ['False'], 'part_id': ['1'], 'csrfmiddlewaretoken': ['X2vkpwG6GJmK79vypFPAveTzVkrxBauJWgfnRvAtJVcZ8NwBokjQhCnfGN9dFFYF']}> False <ul class="errorlist"><li>is_kit<ul class="errorlist"><li>This field is required.</li></ul></li></ul> I believe that my template should work because looking at the source code, forms.BooleanField should convert the string 'False' in the POST data to a python False value. As I mentioned above, the form validates perfectly if is_kit is set to 'True'. -
Django: ORM/SQL query speed significantly decreased after adding additional BooleanField or (SQL tinyint) to Django Filter
Using MySQL Latest Django: I have a vaguely complex Django query that works quite quickly--until I add an additional "AND" with a Boolean Field-- See Below: queriedForms = queryFormtype.form_set.filter(is_public=True) newQuery = queriedForms.filter(formrecordattributevalue__record_value__icontains=term['TVAL'], formrecordattributevalue__record_attribute_type__pk=rtypePK) newQuery = newQuery.filter(flagged_for_deletion=False) logger.info(newQuery.query) term['count'] = newQuery.count() If I either remove the initial "is_public=True" or the final "flagged_for_deletion=False)--it works incredibly fast. If I use both as filters, it increases the time for the count() function by something like 2000% The different QuerySet.query outputs are below: SELECT `maqluengine_form`.`id`, `maqluengine_form`.`form_name`, `maqluengine_form`.`form_number`, `maqluengine_form`.`form_geojson_string`, `maqluengine_form`.`hierarchy_parent_id`, `maqluengine_form`.`is_public`, `maqluengine_form`.`project_id`, `maqluengine_form`.`date_created`, `maqluengine_form`.`created_by_id`, `maqluengine_form`.`date_last_modified`, `maqluengine_form`.`modified_by_id`, `maqluengine_form`.`sort_index`, `maqluengine_form`.`form_type_id`, `maqluengine_form`.`flagged_for_deletion` FROM `maqluengine_form` WHERE (`maqluengine_form`.`form_type_id` = 319 AND `maqluengine_form`.`is_public` = True AND `maqluengine_form`.`flagged_for_deletion` = False) SELECT `maqluengine_form`.`id`, `maqluengine_form`.`form_name`, `maqluengine_form`.`form_number`, `maqluengine_form`.`form_geojson_string`, `maqluengine_form`.`hierarchy_parent_id`, `maqluengine_form`.`is_public`, `maqluengine_form`.`project_id`, `maqluengine_form`.`date_created`, `maqluengine_form`.`created_by_id`, `maqluengine_form`.`date_last_modified`, `maqluengine_form`.`modified_by_id`, `maqluengine_form`.`sort_index`, `maqluengine_form`.`form_type_id`, `maqluengine_form`.`flagged_for_deletion` FROM `maqluengine_form` WHERE (`maqluengine_form`.`form_type_id` = 319 AND `maqluengine_form`.`is_public` = True) The first takes about 20/30 seconds to perform the count(), while the second with only 1 of the two BooleanField's takes less than a second to perform the count() -
Django POST using AJAX not working
I have a django backend where I have added corsheader and the middlewares. I have an html page from which I am sending AJAX XMLHttpRequest POST to my localhost hosting django application but the post never goes through. It fires a GET transaction and the transaction never reaches the server. The code for the front end HTML page is as below:- <button type="submit" class="btn btn-success btn-lg" id="sub1" onClick=loadDoc() >Login </button> <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if( this.readyState == 4 && this.status == 200 ) { location.replace(Trial.html); } }; xhttp.open("POST", "http://localhost:XXXX/XXXX/XXXX/", true) xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send(); } </script> Can any one point out what is wrong? When I use form data the post works but it doesn't work when I use javascript. -
Django 1 Models - DateTimeField()
I am very new to Django and programming in general and I am facing a challenge I have not seen before. I a looking for a bit of help with DateTimeField(). As a learning project, I am setting up a simple travel app. I would like users to be able to add trips, descriptions, etc. So far, so good. I would like to add two DateTimeFields to my trips model. The start_date entered must be a date in the future (from the time they are using the app), while the end_date will have to be after the start_date (natch). How do I program this into my models? Here is my current code for my Trip class: class Trip(models.Model): destination = models.CharField(max_length=55) description = models.TextField() start_date = models.DateTimeField(??) end_date = models.DateTimeField(??) travellers = models.ManyToManyField(User, related_name="trips") planned_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="trips_added") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Thank you. -
Automatice login after sign up without admin permission on django
I have an Django app wherein user creates an account and I have to manually approve it on my admin page from them to go live. Is there any option where I could automate this? as in immediately after the user creates an account they should be able to login without waiting for any admin permissions.