Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django two foreign key to same model's different columns
I just started learning Django A couple of weeks ago. I want to be able to refer two foreign keys from payments model to Tenant's Model's Tenant_ID and tenant_Name. Pardon me for the formatting didnt know how to post here Tenants Model: from django.db import models from applications.houses.models import HousesTable # Create your models here. class TenantsTable(models.Model): STATUS_CHOICES = (('M','Married'),('S','Single'),('D','Divorced')) GENDER_CHOICES = (('F','Female'),('M','Male')) House_ID = models.ForeignKey(HousesTable, to_field='House_ID', on_delete=models.DO_NOTHING) Tenant_ID = models.CharField(max_length = 10, primary_key=True, unique = True) Name = models.CharField(max_length = 30, unique = True) Telephone = models.CharField(max_length = 15) Date_Admitted = models.DateField() Status = models.CharField(max_length=1,choices=STATUS_CHOICES) Sex = models.CharField(max_length=1,choices=GENDER_CHOICES) Date_of_Birth = model`enter code here`s.DateField() def __str__(self): return self.Tenant_ID Payments model: from django.db import models from applications.tenants.models import TenantsTable from applications.administrators.models import AdministratorsTable # Create your models here. class PaymentsTable(models.Model): PID = models.AutoField(primary_key=True) Tenant_ID = models.ForeignKey(TenantsTable, to_field = 'Tenant_ID', related_name="Tenants_ID", db_column='Tenant_ID', on_delete=models.DO_NOTHING) Name = models.ForeignKey(TenantsTable, to_field = 'Name', related_name="Tenant_Name", db_column='Name', on_delete=models.DO_NOTHING) Date_Admitted = models.DateField(null=True) Date_Paid = models.DateField() Start_Date = models.DateField() Expiry_Date = models.DateField() Duration = models.IntegerField() Status = models.CharField(max_length=15) Received_By = models.ForeignKey(AdministratorsTable, to_field='Name', on_delete=models.DO_NOTHING) def __str__(self): return self.Name -
Date format in queryset lookups
I'm trying to retrieve information by weekday using querysets in Django, but if I use the week_day look up I get this error: Exception Type: NotImplementedError Exception Value: subclasses of BaseDatabaseOperations may require a date_extract_sql() method I tried different ways of getting the week day: sun_data = week.annotate(weekday=ExtractWeekDay('date_in'))\ .values('weekday')\ .annotate(c=Sum('data'))\ .values('weekday', 'c') and mon_data = week.filter(date_in__week_day=2) But I haven't had luck with any solution I have wrote. Hope you can help me! :) -
Logout from windows authentication in Django
Using JavaScript code i.e. ClearAuthenticationCache, i am able to logout user from IE but didn't find anything to deal with it in Chrome. Please suggest... Thanks in advance -
Create a custom Django field which is actually is a formset
I have to a little bit complicated thing, which could be described like this: I need to create a form with multiple forms (and formsets), but this form should behave like a usual form and I need to save all these forms with one "save" button. Something like this were already implemented in django-superform library here. Because of restrinctions I can't just take some library and use it but I have to implement it by myself. I tried this approach and it works, but it is really dirty from the semantics side: I have to pass to inlineformset_factory some objects as a parent objects but they are actually not a parent of that objects. I just have to give users the way to work with a different entities related to the some other entity. So I think about more general approach. My idea is simple: I create a form with fields, and that fields are actually forms, each of these forms has two fields: one is default Django ModelForm and another is default Django Formset. So I have 3 nested levels: MainForm(forms.Form): system_1 = SystemOneFormField(prefix='system1') system_2 = SystemTwoFormField(prefix='system2') system_3 = SystemThreeFormField(prefix='system3') SystemOneFormField(forms.Form): general_fields = GeneralFormField(prefix='general') multiple_fields = MultiFields(prefix='multi') # one-to-many … -
Django Database Locked After Modifying Migrations
I accidentally set a default value in OneToOneField as a string and this caused an error when doing python manage.py migrate. So I modified the file storing the bad migration and now its displaying: django.db.utils.OperationalError: database is locked This is the code that caused this: from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blog', '0008_remove_post_cover_image'), ] operations = [ migrations.AddField( model_name='post', #default=exit name='author', field=models.OneToOneField (default='extra',on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ] How do I unlock the database again? -
Django Reset PW emails not sending on AWS
Difficult to phrase this question and what I've done as I don't know where the error is occuring. I'm using Django hosted on AWS Elastic Beanstalk and SES to send emails. (Only for password reset) However the password reset emails don't seem to be sending. When I try to send an email as below however it works. send_mail('Test', 'Email content', 'email@email.com',['email@email.com',]) Also locally the password reset email sends (its put in spam but that's a different issue) My email settings are: EMAIL_HOST = 'smtp.gmail.com' # mail service smtp EMAIL_HOST_USER = 'email@email.com' # email id EMAIL_HOST_PASSWORD = '****' #password EMAIL_PORT = 587 # EMAIL_USE_TLS = True EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'ACCESSKEY' AWS_SECRET_ACCESS_KEY = 'SECRETKEY' AWS_SES_REGION_NAME = 'eu-west-1' AWS_SES_REGION_ENDPOINT = 'email.eu-west-1.amazonaws.com' DEFAULT_FROM_EMAIL= 'email@email.com' If it's relevant, anywhere I've written email@email.com is actually the same email. Any help would be much appreciated. Thanks -
Custom-formatted Django form errors appearing twice
I am building a very simple form in Django, and want to display form errors in a Bootstrap alert tag. I know how to do this (e.g. Django docs or Django Forms: if not valid, show form with error message or How to render Django form errors not in a UL? ). However, when I do, I am seeing the errors appear twice. It seems like Django's {{ form }} element in the template is displaying the errors in a ul tag by default, in addition to my custom-formatted errors. What is the best way to avoid this duplication? In template.html: <!--Load the file search form from the view--> <form action="" method="post" id="homepage_filesearch"> <!--Show any errors from a previous form submission--> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% endif %} {{ csrf_input }} {{ form }} <button class="btn btn-primary" type="submit">Search</span></button> </form> In views.py: from .forms import FileSearchForm def view(request): # Create a form instance and populate it with data from the request form = FileSearchForm(request.POST or None) # If this is a POST request, we need to … -
Django: command management call from model, from view or from where?
I am new on Python3 and DJango. I am writing an app where the user can register a Company using Company Name and AWS Access Key and Secret Key. I will use the Access and Secret key to make a inventory "Discovery" of the AWS Account. Well, I want what every time an user register a company (click to create) django executes a management command called infra_discovery.py inside my app_folder/management/commands (that is working fine when I call via python manage.py infra_discovery). I have the following model: from django.db import models from django.urls import reverse from django.contrib.auth.models import User from empresa.models import Empresa class InfraDiscovery(models.Model): # user will fill this three fiels: infra_empresa = models.ForeignKey('empresa.Empresa', on_delete=models.CASCADE, blank=True, null=True ) infra_aws_key = models.CharField(max_length=100, null=True, blank=True) infra_aws_secret = models.CharField(max_length=255, null=True, blank=True) # my script called infra_discovery have to fill this fields: infra_vpc = models.TextField(blank=True, null=True ) infra_ec2 = models.TextField(blank=True, null=True ) infra_ebs = models.TextField(blank=True, null=True ) infra_rds = models.TextField(blank=True, null=True ) infra_vpn = models.TextField(blank=True, null=True ) infra_bill = models.TextField(blank=True, null=True ) def __str__(self): return self.id def get_absolute_url(self): return reverse('infrastructure_discovery_edit', kwargs={'pk': self.pk}) I really don't know how to make django fulfill this fields using my script at every time user clicks in "create" button; … -
Django SubForm not getting kwargs in Django subview
I am trying to make subform work in subview but can't make it work. It mainly is problem with inheritance and I tried the standard Python way but still I got stuck at this problem. Error is at bottom. Link for BasketLineForm I am trying to inherit from. My Form I am inheriting in: from oscar.apps.basket.forms import BasketLineForm as CoreBasketLineForm class AddBattery(CoreBasketLineForm): class Meta(CoreBasketForm.Meta): model=Battery fields = ('battery_manufacturer', 'battery_capacity', 'battery_warranty') Link for BasketView I am inheriting from: My View I am inheriting in: from oscar.apps.basket.views import BasketView as CoreBasketView class BasketView(CoreBasketView): def get_formset_kwargs(self): kwargs = super(BasketView, self).get_formset_kwargs() kwargs['strategy'] = self.request.strategy kwargs['battery']=self.request.modify return kwargs def get_queryset(self): return self.request.basket.all_lines() def get_battery_form(self): return AddBattery() def get_battery_objects(self): return Battery.objects.all() def get_context_data(self, **kwargs): context = super(BasketView, self).get_context_data(**kwargs) context['battery_form'] = AddBattery(self.request.POST) context['battery_data'] = self.get_battery_objects() return context def get_success_url(self): return safe_referrer(self.request, 'basket:summary') ERROR: Request Method: | GET -- | -- http://localhost:8000/en/shop/basket/ 1.11.15 TypeError __init__() missing 1 required positional argument: 'strategy' /home/shazia/oscar/getyoursolar/apps/oscar/basket/views.py in get_context_data, line 69 /home/shazia/oscar/bin/python 3.6.7 ['/home/shazia/oscar/getyoursolar', '/home/shazia/oscar/lib/python36.zip', '/home/shazia/oscar/lib/python3.6', '/home/shazia/oscar/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/shazia/oscar/lib/python3.6/site-packages'] On my line 69: def get_context_data(self, **kwargs): context = super(BasketView, self).get_context_data(**kwargs) context['battery_form'] = AddBattery() #this is line 69 context['battery_data'] = self.get_battery_objects() print(context) return context -
how to dispaly multiple inline form an django admin
I have multiple models and i want to display them all on one page in django admin. Some of these have no relationship(fk,onetoone,mm). how i can achieve that? class Category(models.Model): name = models.CharField(max_length=100) class Industry(models.Model): name = models.CharField(max_length=100) class SampleImages(models.Model): image = models.ImageField(upload_to='images/tile_images') category = models.ManyToManyField(Category) industry = models.ManyToManyField(Industry) class SampleColor(models.Model): image = models.ImageField(upload_to='images/tile_color') name = models.CharField(max_length=25) class OrderDetail(models.Model): name_in_logo = models.CharField( max_length=150) slogan = models.CharField(max_length=20) describe_website_and_audience = models.TextField() -
How to reduce verbosity of gunicorn access logging
I upgraded to Gunicorn 19.9 from 19.4 and it about doubled the amount of logging output into Heroku. I believe this is all due to access logs, which are for some reason now on. I want to turn this off. This is what these detailed messages look like: Dec 10 10:34:46 ballprice app/web.5: (IP address) - - [10/Dec/2018:16:34:46 +0000] "GET /us/c/reptiles/pythons/ball-pythons/home HTTP/1.1" 200 11271 "-" "Mozilla/5.0 (Linux; Android 8.0.0; SM-N950U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.83 Mobile Safari/537.36" Heroku claims to be getting the logging via stdout/stderr, but it seems like the default option is for accesslog to be None: http://docs.gunicorn.org/en/latest/settings.html#logging I also tried http://docs.gunicorn.org/en/latest/settings.html#disable-redirect-access-to-syslog thinking maybe the logging was getting sent to syslog but this did not remove it either. I am starting gunicorn in this manner: web: bin/start-pgbouncer-stunnel newrelic-admin run-program gunicorn mysite.wsgi --pythonpath mysite --timeout 30 --max-requests 10000 --disable-redirect-access-to-syslog Thanks! -
getting error while loading static file(*.css) file in django
Problem:- Getting Error GET /static/enquiry/homepage.css HTTP/1.1" 404 1765 Question:- I have made entries and created static directory {% load static %} but unable to resolve the problem. -
Integrate drag and drop with django forms.Form
I am currently using a django.forms.Form to upload user files to my project. I now need to add drag and drop functionality on files. I can't find a way to directly attach a drag and dropped file to a form. My code this far is: **javascript** var dropzone = document.getElementById('file-upload-wrapper'); dropzone.ondrop = function(e) { var form = document.getElementById('file-upload-form') var length = e.dataTransfer.files.length; if(length > 1){ alert('one at a time please') return; }; for (var i = 0; i < length; i++) { var file = e.dataTransfer.files[i]; console.log('Do something here...') console.log(form) } }; **template** <form method="post" enctype= multipart/form-data display="none" id="file-upload-form"> {% csrf_token %} {{ form }} <button type="submit" id="submit-file">submit</button> </form> **form** class UploadFileForm(forms.Form): data_import = forms.FileField() class Meta: model = Recipe fields = ('data_import',) Is this possible to add a file to a form without the use of dropzonejs or another similar package? -
Which database for python mysql or postgresql ?
postgresql or mysql I want to create a good web application with python and Django framework but I'm not sure which database i should use? I search on Google and i find postgresql is better but that Posts is for 2 years ago but now in 2018 which database is good ? I need a database that will not need to be changed later with another database Thanks -
Using reflection with Django models to determine module containing the choices?
Let's say I take the following code from the Django documentatation: class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) But instead I want to do: from student_app import choices class Student(models.Model): year_in_school = models.CharField( max_length=2, choices=choices.YEAR_IN_SCHOOL_CHOICES, default=choices.FRESHMAN, ) Is there anyway using reflection to determine which module the choices are imported from? For example: field = Student._meta.fields.get_field_by_name('year_in_school') choices_source = some_clever_function(field) print("Choices imported from '%s'" % choices_source) I want the output to be: Choices imported from 'student_app'. Obviously the clever function does not exist but hopefully clarifies what I'm trying to do. Thanks -
get any instance (if exist) or create new for any child of abstract model
I found myself repeatedly finding record matching some criteria and if none exists, then creating new one with those criteria matched. Basically that does get_or_create() method, but it fails, if more than one such record exists. I am doing this so often, that I do not want write the same similar code all over and instead use some simple function for that All my models are derived from one abstract BaseModel, so it would seem logical, to implement method get_first_or_create there, which would then return object of actual model fullfilling given criteria. In case of more such objects, it would return any one of them. It would also take care about all Exception checking and some other common stuff too in one place. I do not know, how to make it in the BaseModel. Something like class BaseModel(models.model): active = models.BooleanField(default=True) ... class Meta: abstract = True def get_first_or_create(*args,**kwargs): retval=ChildModel.objects.filter(*args,**kwargs).first() # ChildModel is ofcourse wrong, but what to use? if retval: return retval else: retval = ChildModel(*args,**kwargs) retval.save() return retval # actually make more Exceptions/sanity/whatever checks here # but this is core of the idea class Car(BaseModel): name = models.TextField(blank=True) color = models.TextField(blank=True) ... class Animal(BaseModel): cute=models.BooleanField(default=True) ... and then … -
How to save a file generated in view to the model?
I have a model.py: class SomeModel(models.Model): name = models.CharField(max_length = 30) file_field = models.FileField(upload_to=os.path.join(settings.MEDIA_ROOT,'strategies/')) and view.py def test(request): csv = get_csv(args) My function get_csv() returns string of csv. And I need to save this in my Model. I don't want to create a file and put existing url into my model, because I'll always need TO generate a new file name, but I know, it can be done automatically. Could you please advice me any way to solve this problem? -
How to configure Django with Webpack/React using create-react-app on Ubuntu server
I'm following this tutorial: http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/ The tutorial describes how to set up a Django/React app using webpack. Everything works fine on my development machine but I have problems with the static files on a remote server (Ubuntu 16.04.4). These are my questions: 1) Why is my development version looking for the static files in localhost? 2) If I use Nginx/Passenger to serve the production version, the static files are not loaded in the browser even though the links look correct. Why is this? 3) Do I need to configure STATIC_ROOT for production and run collectstatic? Many thanks for any help! Here is more information and code: In order to make sure I've not made any typos, I've cloned the source code, switched to the branch 'part-1' and followed all the instructions in the README. I added 'xx.xx.xx.xx' to settings.py ALLOWED_HOSTS where xx.xx.xx.xx is my server's IP address. I added "proxy": "http://localhost:8000" to frontend/package.json. 1) Development version I'm running the development server with: ./manage.py runserver xx.xx.xx.xx:8000 I have also run 'npm run build' before starting the webpack server with 'npm run start' in the frontend folder. The problem: when I navigate in a browser to xx.xx.xx.xx:8000, I see a blank page. … -
Django & Javascript : Display picture in popup
I would like to get your help in order to handle pictures in HTML template. I'm using Django 1.11.16. I display pictures like this in my HTML template : <a href="{{ element.publication.cover.url }}"> <img class="popup_image" id="img_{{ element.publication.id }}" src="{{ element.publication.cover.url }}"> </a> So when I click on picture, it displays this one inside a full window because it goes to media url. I have to make click on browser previous button to come back in the template. My question is : How I can display the picture inside a popup ? So when I click on the thumbnail, it displays a popup with the picture and close button ? Thank you so much -
How to integrate wordpress blog in django app?
I want to render wordpress blog from http://my-wordpress-app.com/ in my django project i have use this package https://django-wordpress-api.readthedocs.io/en/latest/integration.html but it is not working I followed all the steps mentioned in document. But it gives 404 page when i hit blog url -
Django using nested resultset in template
I am trying to implement a 2 (or 3-tiered) collapsible navigation in a Django system (that I am extremely unfamilair with) that would looks as follows: - Type 1 -- Sub_Type1 -- Sub_Type2 --- Sub_Sub_Type1 I have a model that (in a simplified form) looks as follows, where the Subactivity and Subsubactivity tables and values are newly added: class Activity(models.Model): activity_type = models.CharField(max_length=50) def __str__(self): return self.activity_type def __unicode__(self): return u"%s" % self.activity_type class Subactivity(models.Model): subactivity_type = models.CharField(max_length=50) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) def __str__(self): return self.subactivity_type def __unicode__(self): return u"%s" % self.subactivity_type class Subsubactivity(models.Model): subsubactivity_type = models.CharField(max_length=50) subactivity = models.ForeignKey(Subactivity, on_delete=models.CASCADE) def __str__(self): return self.subsubactivity_type def __unicode__(self): return u"%s" % self.subsubactivity_type class Foo(models.Model): barcode = models.CharField(max_length=200) name = models.CharField(max_length=200) activity = models.CharField(max_length=200, blank=True, null=True) activity_type = models.ForeignKey(Activity, on_delete=models.CASCADE) sub_activity_type = models.ForeignKey(Subactivity, blank=True, null=True) sub_sub_activity_type = models.ForeignKey(Subsubactivity, blank=True, null=True) confidential = models.BooleanField(default=True) The View that I have been trying (the original is commented away, which was a single tiered collapsible system). class IndexView(generic.ListView): template_name = 'gts/index.html' context_object_name = 'latest_foo_list' def get_queryset(self): # Tiered menu refactor try: resultList = [] for types in Foos.objects.values('Activity_type').distinct(): for sub_types in Foos.objects.values('Sub_activity_type').distinct(): if self.request.user.is_staff: resultList.append(Foos.objects.filter(Activity_type=types.values()[0], Sub_activity_type=sub_types.values()[0])) else: if Foos.objects.filter(Activity_type=types.values()[0], Sub_activity_type=sub_types.values()[0], confidential=0): resultList.append(Enzymes.objects.filter(enzyme_activity_type=types.values()[0], enzyme_sub_activity_type=sub_types.values()[0])) return resultList except: … -
django login using class based for custom user
here is my user model. class User (models.Model): username = models.CharField(max_length=50) # token = models.CharField(max_length=50) email_id = models.EmailField(max_length=50) password = models.CharField(max_length=50) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) and here is my views for creating user class UserView(APIView): def post(self,request): try: # RequestOverwrite().overWrite(request, {'token':'string'}) user_data = UserDetailSerializer(data=request.data) if not(user_data.is_valid()): return Response(user_data.errors) user_data.save() return Response("user created successfully",status=status.HTTP_201_CREATED) except Exception as err: print(err) return Response("Error while creating user") now what i want to do is to create a token when i post a user and that token is used later for login. also i want to validate user if it exist in database then make user authenticate. what should i do..?any suggestion below is my serializers.py class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username','email_id','password','is_deleted','created_at','updated_at') extra_kwargs = { 'password': { 'required':True, 'error_messages':{ 'required':"Please fill this field", } } } -
Django: Not fetching the same object
I have a form where i am entering four details 'Persona Name', 'Persona Key' ,'Persona Key Label' and 'Persona Key Value' and on entering these values i am pressing Submit button which generates a GET request on my server. Following are django views:- def PersonaSave(request): persona_name = request.GET.get('persona_name',) persona_key = request.GET.get('key_name',) persona_key_value = request.GET.get('key_value',) persona_key_label = request.GET.get('key_label',) persona_submit = request.GET.get('Save',) return( persona_name , persona_key , persona_key_label , persona_key_value , persona_submit ) def TestPageView(request): x=PersonaSave(request) persona_name = x[0] persona_key = x[1] persona_key_label=x[2] persona_key_value=x[3] persona_submit=x[4] if(persona_name is None and persona_key is None and persona_key_label is None and persona_key_value is None): return render(request, 'dashboard/test_page.html') # Update function starts from here---- elif TestPersonaName.objects.filter(name=persona_name).exists(): t= TestPersonaName.objects.get(pk=persona_name) testpersona = TestPersona.objects.get(name=t) if testpersona.key == persona_key: testpersona.label= persona_key_label testpersona.value = persona_key_value #-----This is where update function ends If persona name is different then complete new TestPersonaName object and TestPersona object will be formed. For this the function starts here---- t=TestPersonaName(name=persona_name) t.save() testpersona = TestPersona(name=t,key=persona_key,label=persona_key_label,value=persona_key_value) testpersona.save() # --and ends here. return render(request,'dashboard/test_page.html') Now the problem is for the same persona name and same persona key two different TestPersona objects are being formed. For e.g If I enter persona_name = Ankit, key = 'city' and value = 'New Delhi' and … -
Add Billing Address Validation in Stripe.js
I have a Django Saleor based website which is using stripe.js to manage the payments. During the checkout process, I am collecting the billing address as part of the checkout process but once I enter valid card details (even though billing address is incorrect) the payment is still successful. On the stripe dashboard I can see that the street and postcode check failed but the payment is successful. Anybody know how I can enable this. This is a copy of my stripe.js: document.addEventListener('DOMContentLoaded', function () { var stripeInput = document.getElementById('id_stripe_token'); var form = stripeInput.form; var publishableKey = stripeInput.attributes['data-publishable-key'].value; Stripe.setPublishableKey(publishableKey); form.addEventListener('submit', function (e) { var button = this.querySelector('[type=submit]'); button.disabled = true; Stripe.card.createToken({ name: this.elements.id_name.value, number: this.elements.id_number.value, cvc: this.elements.id_cvv2.value, exp_month: this.elements.id_expiration_0.value, exp_year: this.elements.id_expiration_1.value, address_line1: stripeInput.attributes['data-address-line1'].value, address_line2: stripeInput.attributes['data-address-line2'].value, address_city: stripeInput.attributes['data-address-city'].value, address_state: stripeInput.attributes['data-address-state'].value, address_zip: stripeInput.attributes['data-address-zip'].value, address_country: stripeInput.attributes['data-address-country'].value }, function (status, response) { if (400 <= status && status <= 500) { alert(response.error.message); button.disabled = false; } else { stripeInput.value = response.id; form.submit(); } }); e.preventDefault(); }, false); }, false); My end goal is to make sure where the billing address doesn't match, these transactions are declined. -
django URL doubled
when i clicked the anchor tag going to the detailed view of my product the url is doubled. http://127.0.0.1:8000/products/products/t-shirt/ i think it is supposed to be like this http://127.0.0.1:8000/products/t-shirt/ List.html {% for object in object_list %} <a href="{{ object.get_absolute_url }}">{{object.title}}</a> <br> {{object.description}} <br> {{object.price}} <br> <br> {% endfor %} models.py class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=19, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) featured = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # For url when you click a product def get_absolute_url(self): return "products/{slug}/".format(slug=self.slug) def __str__(self): return self.title urls.py from django.conf.urls import url from products.views import (product_view, product_detail_view, product_featured_view, ) urlpatterns = [ url(r'products/$', product_view), url(r'products/(?P<slug>[\w-]+)/$', product_detail_view), url(r'featured/$', product_featured_view), ] view.py from django.shortcuts import render, get_object_or_404, Http404 from .models import Product def product_view(request): queryset = Product.objects.all() context = { 'object_list': queryset, # 'featured': fqueryset } return render(request, 'products/list.html', context) def product_detail_view(request, slug=None, *args, **kwargs): try: instance = get_object_or_404(Product, slug=slug) except Product.DoesNotExist: raise Http404("Not Found..") except Product.MultipleObjectsReturned: queryset = Product.objects.filter(slug=slug) instance = queryset.first() context = { 'object': instance } return render(request, 'products/detail.html', context) def product_featured_view(request): queryset = Product.objects.filter(featured=True) context = { 'object_list': queryset } return render(request, 'products/featured-list.html', context)