Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing argument to view function from template without exposing it in URL
How should arguments be passed from template to view function without appearing in URL? I am familiar with the usual way to pass arguments to view function through template: Template <a href="{% url 'redirection' pk %}">Perform</a> URL: url(r'^redirect/(?P<pk>\d+)/$', views.redirection, name='redirection'), View Function: def redirection(request, pk): # code of function This method exposes the pk variable in URL. Is there any other way to perform this without exposing this variable in URL? Can this be used to perform the above task? If yes, then how should the code in template be changed to perform this? -
Delete User information automatically from backend, if user did not confirm the email id
I have a webapp made in Django. Here is my views.py that I use to confirm email id of user, class SignupView(View): form_class = SignupForm template_name = 'mechinpy/user_signup.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form':form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('mechinpy/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('mechinpy:account_activation_sent') else: messages.error(request, 'Invalid Input') return render(request, self.template_name, {'form':form}) def account_activation_sent(request): return render(request, 'mechinpy/account_activation_sent.html') def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return redirect('mechinpy:home') else: return render(request, 'mechinpy/account_activation_invalid.html') This works fine if the user goes back to click on the email link. My question is, if the user does not click on the confirm email link and the account is not activated within a period of time, let's say 24 hours, how can I delete all that information from the user automatically. What is the right approach. -
Why do only files of static-folder get loaded in Django?
I am working on a Django App on Heroku and need the possibility to temporarily store something on my dyno there. As far as I understood, this is possible by using a workaround with the /tmp/-folder in the root-directory of the dyno. However, I am trying to reference to a JSON stored there in JS and it seems like Django does not load, once something is outside of the static folder. How can I force Django to accept other folders as well? Or am I missing something very simple? This is the error message I get from my server: "GET /tmp/honoradar/mediumsname_temporary.json?v=1539425460111 HTTP/1.1" 404 2731 This is my jquery code with static as a reference: var options = { url: "static/honoradar/mediumsname.json?v=" + versionUpdate, getValue: function(element) { return element.name; }, This is my jquery code with tmp as a reference: var options = { url: "tmp/honoradar/mediumsname.json?v=" + versionUpdate, getValue: function(element) { return element.name; }, For making sure that the file structure is the exact same, I duplicated the static folder and renamed it "tmp". -
is there any bulk_update django2.0?
I want to save a thousand records at a time and some of them I need to insert and if the already primary key is there means it should update. how can I achieve in Django 2.0? thank you in advance. -
I cannot get radio button value
I cannot get radio button value.I wrote in html {% with form as f %} <form action="{% url 'app:test' %}" method="POST"> {% csrf_token %} <div> {{ f.test1 }} <label class="js--goTo" for="test1" dataGoTo="2">TEST1</label> </div> <button type="submit"">SEND</button> </form> {% endwith %} in forms.py # -*- coding: utf-8 -*- from django import forms RESPONSE_CHOICES = ( ('1', 'test1'), ('2', 'test2'), ) class InputForm(forms.Form): test1 = forms.ChoiceField(required=False,choices=RESPONSE_CHOICES, widget=forms.RadioSelect()) in views.py def test(request): if request.method == "POST": form = InputForm(data=request.POST) if form.is_valid(): test1 = request.POST.get("test1") print(test1) When I select test1's radio button and put SEND button,print(test1) shows None.In this case,I put test1,so I really cannot understand why test1's 1 is not printed out in print(test1).What is wrong in my codes?How should I fix this? -
Value Error Tensorflow While Loading the Machine Learning project in Django
While loading our machine learning project into django server we got following error: Traceback (most recent call last): File "/home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/akhil/tocoblo/msg/views.py", line 6, in index a=fuctioncall.show() File "/home/akhil/tocoblo/msg/fuctioncall.py", line 6, in show a=Loadmodel.predict_string() File "/home/akhil/tocoblo/msg/Loadmodel.py", line 69, in predict_string b=loaded_model.predict(y) File "/home/akhil/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1164, in predict self._make_predict_function() File "/home/akhil/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 554, in _make_predict_function **kwargs) File "/home/akhil/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 2744, in function return Function(inputs, outputs, updates=updates, **kwargs) File "/home/akhil/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 2546, in init with tf.control_dependencies(self.outputs): File "/home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 5002, in control_dependencies return get_default_graph().control_dependencies(control_inputs) File "/home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 4541, in control_dependencies c = self.as_graph_element(c) File "/home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3488, in as_graph_element return self._as_graph_element_locked(obj, allow_tensor, allow_operation) File "/home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3567, in _as_graph_element_locked raise ValueError("Tensor %s is not an element of this graph." % obj) ValueError: Tensor Tensor("dense_4/Sigmoid:0", shape=(?, 6), dtype=float32) is not an element of this graph. The Loaded code is Loadmodel.py import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import sys import gzip import keras import sys import pickle from sklearn.model_selection import train_test_split from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import … -
Django facebook login
I had facebook login setup using python-social-auth a while ago, but it stopped working. Now I updated social auth library and set it up again. I went trough a few errors from incorrect secret, incorrect facebook setup up till "Authentication process canceled". Now it seems like whole process went successfully, however once I am redirected back, I am still not logged in. I think, I have same problem with google auth, which worked alright even before I updated library, so I guess some configuration changed. I upgraded from python-social-auth==0.2.21 to python-social-auth==0.3.6. I checked newest documentation and changed a few bits, that were different with no help. I got standard pipeline, social AUTHENTICATION_BACKENDS first, updated context processors (prefix social.apps.django_app -> social_django), but still no help. I already went trough quite a few files of the library and related ones to fix those errors. Now I kinda don't know where should I look for problem and dig a bit. Any hints would be greatly appreciated! -
django rest framework update method in serializer, instance is not saved immediately
The instance to be updated has instance.email=abc@mail.com. email to be updated or changed to xyz@mail.com UserUpdateSerializer's update method. def update(self, instance, validated_data): email_updated=False email = self.validated_data["email"] print(instance.email) #abc@email.com if email!=instance.email: if User.objects.filter(email=email).exists(): raise serializers.ValidationError("email is not available") else: email_updated=True instance.__dict__.update(**validated_data) instance.save() # instance is saved. print(instance.email) #xyz@email.com if email_updated: task_send_activation_mail.delay(instance.id)#this one here print(instance.email) #xyz@email.com return instance I am using celery to send an email to the user when given a user_id to the method as: from `celery` import shared_task @shared_task def send_activation_mail(user_id): from doclet.models import User user = User.objects.get(pk=user_id) subject = 'Activate Your '+DOMAIN_SHORT_NAME+' Account' message = get_template('registration/account_activation_email.html').render({ 'domain_url': DOMAIN_URL, 'domain': DOMAIN, 'domain_short_name': DOMAIN_SHORT_NAME, 'domain_full_name': DOMAIN_FULL_NAME, 'domain_email': DOMAIN_EMAIL, 'domain_support_email': DOMAIN_SUPPORT_EMAIL, 'domain_support_url': DOMAIN_SUPPORT_URL, 'mobile_support': MOBILE_SUPPORT, 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) user.email_user(subject, DOMAIN_FULL_NAME +' ', html_message=message) return user.email #"abc@email.com" is printed as celery output. The instance is saved with instance.save(), where email is updated from abc@mail.com to xyz@mail.comand then the instance's id is passed as a parameter to a shared_task method to send a mail. But thought the email appears updated finally. The User instance obtained from the user_id inside the send_activation_mail(user_id): appears to have not updated and the mail is sent to the previous email. -
Order by nested JSON field in Django admin
I've got model User with meta field, which stores JSON data: { "info": { "f_name": "John". "l_name": "Doe", "nick": "foo", ... }, ... } How can I specify ordering in Django admin by meta['info']['l_name']? I've tried: ordering = ( 'meta__info__l_name' ) ordering = ( 'meta -> info ->> l_name' ) ordering ( RawSQL("main_user.meta -> 'info' ->> 'l_name'", [], ), ) Also, user.id DESC sorting is applied by default, which also breaks the desired behaviour. Thank you in advance. -
Lazy loading with Angular 6.1, error with ng build
I have a Angular 6.1 application which is served by django. When I try to ng build this and open it, following error is occuring: Uncaught SyntaxError: Unexpected token < ERROR Error: Uncaught (in promise): Error: Loading chunk recordmanagement-records-module-ngfactory failed. There is no import of the records-module or its component in the app-module. If I ng serve this, it works just fine. I also tried --aot and a custom webpack build with angular-router-loader, which didn't work. This is the app-routing: const appRoutes: Routes = [ { path: "records", loadChildren: './recordmanagement/records.module#RecordsModule'}, { path: "", pathMatch: "full" , component: DashboardComponent, canActivate: [AuthGuardService]}, ]; @NgModule({ imports: [RouterModule.forRoot(appRoutes)], exports: [RouterModule] }) export class AppRoutingModule {} And the records-routing: const recordsRoutes: Routes = [{ path: "", component: RecordsComponent, canActivate: [AuthGuardService] }]; @NgModule({ imports: [RouterModule.forChild(recordsRoutes)], exports: [RouterModule], providers: [AuthGuardService] }) export class RecordsRoutingModule {} The basic angular depencies are used + ngrx for state management. Everything gets built perfectly: chunk {main} main.js, main.js.map (main) 233 kB [initial] [rendered] chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 228 kB [initial] [rendered] chunk {recordmanagement-records-module-ngfactory} recordmanagement-records-module-ngfactory.js, recordmanagement-records-module-ngfactory.js.map (recordmanagement-records-module-ngfactory) 208 kB [rendered] chunk {runtime} runtime.js, runtime.js.map (runtime) 9.09 kB [entry] [rendered] chunk {styles} styles.js, styles.js.map (styles) 78.6 kB [initial] [rendered] chunk {vendor} vendor.js, … -
Django Save extended usermodel to database not working
I'm creating an extended user model with a OneToOne relation. Now whenever I try to register it saves the data to the user table instead of my created table. Can anyone help me? Here are my files: models.py class User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=31, unique=True, default=None) first_name = models.CharField(max_length=31, unique=True, default=None) last_name = models.CharField(max_length=31, unique=True, default=None) password = models.CharField(max_length=1023, default=None) email = models.CharField(max_length=255, unique=True, primary_key=True, default=None) typeOfPerson = models.CharField(max_length=15, default=None) birth_date = models.DateField(default=None) registration_date = models.DateField(auto_now=True) ip_address = models.CharField(max_length=31, blank=True, null=True) classNumber = models.CharField(max_length=2, blank=True, null=True) shortName = models.CharField(max_length=3, blank=True, null=True) rank = models.CharField(max_length=15, default="Normal") class Meta: ordering = ["email"] #db_table = 'register_user' #fields = ['username', 'first_name', 'last_name', 'password', 'email', 'typeOfPerson', 'birth_date', 'ip_address', 'classNumber', 'shortName'] def __str__(self): return self.first_name forms.py class SignUpForm(forms.ModelForm): typeOfPerson = forms.ChoiceField(label="Was bist du?", required=True, choices=( ("S", "Schüler"), ("L", "Lehrer"), ("E", "Elternteil"), ("G", "Gast"), ), widget=forms.Select(attrs={ "id": "select", })) username = forms.CharField(max_length=31, min_length=3, required=True) first_name = forms.CharField(max_length=31, min_length=3, required=True) last_name = forms.CharField(max_length=31, min_length=2, required=True) email = forms.EmailField(max_length=255, min_length=6, required=True) birth_date = forms.DateField(label="Geburtsdatum", required=True) classNumber = forms.IntegerField(max_value=13, min_value=5) shortName = forms.CharField(min_length=2, max_length=2, required=False) password1 = forms.CharField(min_length=8, max_length=1023, required=True) password2 = forms.CharField(min_length=8, max_length=1023, required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', … -
Django : Cannot assign must be a instance
I want to fetch the non-str objects of one model into another model... This is my models: class Selectdatefield(models.Model): User = models.OneToOneField(settings.AUTH_USER_MODEL,related_name="Users",on_delete=models.CASCADE,null=True,blank=True) Start_Date = models.DateField(blank=True, null=True) End_Date = models.DateField(blank=True, null=True) class Journal(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname') start_date = models.ForeignKey(Selectdatefield,on_delete=models.CASCADE,null=True,blank=True,related_name='startdate') end_date = models.ForeignKey(Selectdatefield,on_delete=models.CASCADE,null=True,blank=True,related_name='enddate') Date = models.DateField() By = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) I have tried this in my journal create view: class journalCreateView(LoginRequiredMixin,CreateView): model = journal form_class = journalForm def form_valid(self, form): form.instance.User = self.request.user c = company.objects.get(pk=self.kwargs['pk']) form.instance.Company = c s = selectdatefield.objects.get(pk=self.kwargs['pk3']) form.instance.start_date = s form.instance.end_date = s.End_Date return super(journalCreateView, self).form_valid(form) I want to fetch the end date of selectdate automatically in my journal model when the journal form is submitted... But getting this error : ValueError: Cannot assign "datetime.date(2018, 10, 6)": "journal.end_date" must be a "selectdatefield" instance. The error is in this line of code: form.instance.end_date = s.End_Date Can someone plz tell me what wrong am I doing in my code??? -
What does it mean when '=' is used inside a function's paranthesis (with the arguments) in python?
I came across a python code in Django in which '=' was used in an unusual way. Can anybody please explain what it means. This is the line of code: return reverse('model-detail-view', args=[str(self.id)]) Here reverse is a function and it's value is being returned. The first argument is understandable but the second argument uses a '=' symbol. How is this working? What does it do? -
ManyToManyField is being filtered excluded when passed through DRF view and serializer
When attempting to persist a new record to the database via POSTing through a Django Rest Framework route, my ManyToManyField named shared_users on the object is filtered out. It is weird as the new object is still created, however, the shared_users attribute appears as an empty list. When I inspect via Python Debugger, everything is originally available on the request object. (Pdb) request.data <QueryDict: {u'shared_users[]': [u'4', u'5', u'1'], u'model_name': [u'A name'], u'description': [u'A description']}> But when I inspect the field with request.data.get('shared_users[]', []) (not sure why fieldname appears with [] in the name), I get a result of u'1' (already missing two user id's). And when I evaluate serializer.data it returns everything with expected values but the shared_users field, as below. {'last_modified_by': 3, 'description': u'A description', 'user': 3, 'shared_users': [], 'model_name': u'A name'} I have provided my views and serializers files for reference. views.py class MyCreateView(generics.GenericAPIView): pass serializer_class = MyCreateAndUpdateSerializer def get_queryset(self): return User.objects.filter(pk=self.kwargs.get('user')) def post(self, request, format=None, **kwargs): # This dictionary is used to ensure that the last_modified_by field is always updated on post to be the current user request_data = { 'user': request.user.id, 'model_name': request.data['model_name'], 'description': request.data['description'], 'last_modified_by': request.user.id, 'shared_users': request.data.get('shared_users', []) } serializer = MyCreateAndUpdateSerializer(data=request_data) if serializer.is_valid(): … -
How to store dictionary into database like key and value pairs have seperate fields in diango
In python file I have dictionary dict1 the key of dict1 is item and value is frequency I want to store this database in django I have already created model named display for this! Can you please help me to solve this and how to store dictionary in database using MySQL -
Django aggregate Count with Filter does not work
The model is simple, like: class Student(models.Model): name = models.CharField(max_length=100) gender = models.SmallIntegerField() And there are 5 records in the table, like: >>> for s in Student.objects.all(): ... print s.id, s.gender ... (0.000) SELECT "student"."id", "student"."name", "student"."gender" FROM "student"; args=() 1 0 2 1 3 0 4 1 5 1 Note that I enabled the DEBUG log for django.db.backends, that is why the "SELECT ..." statement was printed. The odd thing is: >>> Student.objects.aggregate(number=Count("gender", filter=Q(gender=0))) (0.000) SELECT COUNT("student"."gender") AS "number" FROM "student"; args=() {'number': 5} As you can see, the result, which is supposed to be 2, is 5. And from the sql, the filter does not work at all. So what's wrong with it? In addition, following query works well: >>> Student.objects.filter(gender=0).count() (0.000) SELECT COUNT(*) AS "__count" FROM "student" WHERE "student"."gender" = 0; args=(0,) 2 Thanks in advance. -
Django: Add extra attributes to form fields generated by UpdateView
Am using a custom user that is a subclass of Django AbstractUser, what am trying to archive is to allow user update their data everything works but the form look ugly. Below is my code the class attribute is not added to the form. forms.py(simplified) class AccountEditForm(forms.ModelForm): class Meta: model = CustomUser fields = ('first_name', 'last_name', 'phone_number', 'date_of_birth', 'country') widget = { 'first_name':forms.TextInput( attrs={ 'class': 'input-bordered', } ) } views.py class UserAccountDetails(LoginRequiredMixin, UpdateView): template_name = 'dashboard/account_edit.html' context_object_name = 'form' form_class = AccountEditForm model = CustomUser def get_object(self, queryset=None): """ Return the object the view is displaying. """ if queryset is None: queryset = self.get_queryset() #Get logged in user from request data queryset = queryset.filter(pk=self.request.user.id) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj -
Prevent Resetting of Countdown Timer On Page Refresh - Django & JS
I am working on Django, I wanted to create a countdown timer and once the timer reaches 0 minutes a "Done" button is enabled. On clicking "Done" I get points, now I should make sure that I get points only once. I was thinking of preventing countdown timer on refreshing the page so that I can avoid users from getting points twice. I don't know how to implement it on the current code. HTML <div class="row"> <span class="col-3" id="countdown"> <button id="startClock">Start Timer</button> </span> <span class="col-1"></span> <button class="col-2" id="done">Done!</button> </div> <script> $('#done').hide(); jQuery(function($){ $('#startClock').on('click', doCount); }); function doCount(){ var timer2 = "10:01"; var interval = setInterval(function() { var timer = timer2.split(':'); //by parsing integer, I avoid all extra string processing var minutes = parseInt(timer[0], 10); var seconds = parseInt(timer[1], 10); --seconds; minutes = (seconds < 0) ? --minutes : minutes; seconds = (seconds < 0) ? 59 : seconds; seconds = (seconds < 10) ? '0' + seconds : seconds; $('#countdown').html(minutes + ':' + seconds); if (minutes < 0) clearInterval(interval); //check if both minutes and seconds are 0 if ((seconds <= 0) && (minutes <= 0)){ clearInterval(interval); $('#done').show(); } timer2 = minutes + ':' + seconds; }, 1000); } </script> -
Initializing MultipleChoiceField form with an initial values
I've developed a model (BaseServicesOffered) that contains a field called 'servicelist' that set to a list of IDs of model instances that a user has selected. For example, If I have the following options displayed in a form: Buff (ID = 1) Wax (ID = 2) Wash (ID = 3) and the user selects Buff and Wash in the multiplechoicefield form, the following will be stored to the 'servicelist' field within BaseServicesOffered: [1, 3]. I'd like to know how I can initialize the form with the values that the user previously chose (i.e. when the form loads, the checkboxes that the user previously selected are checked off). Models.py class Service(models.Model): service = models.CharField(max_length=100, null=True, blank=True) industrycode = models.IntegerField() def __str__(self): return self.service class BaseServicesOffered(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) servicelist = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.user.username Forms.py class BaseServicesOfferedForm(forms.ModelForm): service = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): user = kwargs.pop('user') selectedservices = kwargs.pop('selectedservices') super(BaseServicesOfferedForm, self).__init__(*args, **kwargs) self.fields['servicelist'].choices = [(t.id, t.service) for t in Service.objects.filter(industrycode=user.userprofile.industry)] class Meta: exclude = ('user',) model = BaseServicesOffered Views.py @login_required(login_url="/accounts/login/") def baseservicesoffered(request): try: base_services_offered = BaseServicesOffered.objects.create(user=request.user) except: pass user = request.user services = user.baseservicesoffered.servicelist instance = get_object_or_404(BaseServicesOffered, user=user) form = BaseServicesOfferedForm(request.POST or None, user=request.user, selectedservices=services, … -
AttributeError: 'decimal.Decimal' object has no attribute 'decode'
I am having a hard time figuring out why I am getting this error. I have a model called Driver and this is the code: class Driver(models.Model): userId = models.IntegerField(unique=True) status = models.IntegerField(default=-1) currentLatitude = models.DecimalField(max_digits=11, decimal_places=8, default=0) currentLongitude = models.DecimalField(max_digits=11, decimal_places=8, default=0) I am trying to test this model in my tests.py file and I have a Driver instance created like this in my setUpTestData(cls) method. Driver.objects.create(userId=3, status=0, currentLatitude=37.717, currentLongitude=100) I just put fake dummy values for the lat/long and I want to test if this instance actually has 37.717 for the currentLatitude and 100 for the currentLongitude. Here are one of my tests: def testDriverLatitude(self): driver = Driver.objects.get(id=3) expected_latitude = driver.currentLatitude self.assertEquals(expected_latitude, 37.717) When I run the tests I get an error on the driver = Driver.objects.get(id=1) and this is the error I get AttributeError: 'decimal.Decimal' object has no attribute 'decode' I have tried looking for answers online but can't seem to find a solution. Any help/tips will be appreciated. Thanks! -
Django middleware recommendation payments processing
So i'm developing an application and I was wondering how I should go about processing payments. I'm trying to find documentation online but seem out of luck so I'm trying my luck here. I wondering how to integrate a payment processor in django, where if the user_merchant charges 30$ to the user_client, i would charge an extra processing fee as the application is the intermediary for the service. I was wondering if someone can refer me to a payment gateway and if i can integrate it with the django code. I'm sorry if the the question might be repeated but I used the search forum and I can't seem to find my answer. Thank you! -
NoReverseMatch at /security/login/
i Need of help , please. cual seria la configuracion correcta en el urls.py my Views.py class UserProfileData(LoginRequiredMixin, View): template_name = "form_create_perfil.html" def get(self, request): return render(request, self.template_name) my urls.py from .views import ActiveInactiveUser, ChangePassword, UserChangePassword from .views import TenantRegisterView app_name = 'security' urlpatterns = [ url(r'^login/$', Login.as_view(), name="login"), url(r'^logout/$', Logout.as_view(), name="logout"), url(r'^userprofile/$', UserProfileData.as_view(), name="userprofile"), url(r'^user-change-password/$', UserChangePassword.as_view(), name="user-changepassword"), ] html. <a href="{% url 'security:user-changepassword' %}" style="color:#337ab7">Change Password</a> -
jQuery - Fail to load Response for preflight is invalid (redirect) status 307
I'm currently trying to set an asynchronous function to load a small JSON into the page. It's just a test since I'm quite inexperienced with jQuery and XHR. I had been getting stuck on the 'Access-Control-Allow-Origin' Origin null until I set my server to support CORS. The problem now is that I can't fix this problem. I already inspected the client and server-side and from what I can see everything should be working. I'm using Django Framework here too. This is a small test button on the page. The JSON goes inside the testeJSON div <button type="button" id="btnTest">Teste JSON</button> <div id="testeJSON"></div> Here's the JavaScript for it $("#btnTest").click( function() { let jfilho = $.ajax({ method: 'GET', url: 'http://www.pythonanywhere.com/user/zzzaik/files/home/zzzaik/OPE_Draco/core/backend/dataJson.py', headers:{ 'Access-Control-Allow-Origin':'http://zzzaik.pythonanywhere.com/', 'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'} }); $("#testeJSON").text(jfilho); }); So the script should access this function here inside dataJson.py def getClassificacoes(request): data = { 'estilos':['1','2','3'], 'cores':['a','b','c'], 'regiao':['um','dois','tres'], 'tamanho':['s','m','l'] } if request.method == 'GET': return HttpResponse(json.dumps(data), content_type="application/json") return HttpResponse("This is not a GET request", content_type="text/plain") And I'm sure CORS is enabled on the server. The origin is set to accept all because I'm currently testing. Once I get this working I'm setting the right domains. INSTALLED_APPS = [ '...', 'core', 'jquery', 'corsheaders', ] MIDDLEWARE = [ '...', … -
Django: TemplateDoesNotExist at /accounts/login/
I'm following this tutorial from Mozilla.org, Setting up your authentication views And I'm having problems in this part: The next step is to create a registration directory on the search path and then add the login.html file. Because I've created that directory and the template but it appears that is not been recognize by my app. Structure: Note: Your folder structure should now look like the below: locallibrary (Django project folder) |_catalog |_locallibrary |_templates (new) |_registration My Structure: And then for this part: make these directories visible to the template loader I've: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #'DIRS': [os.path.join(BASE_DIR, 'templates')], 'DIRS': ['./templates',], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Project url.pý: from django.contrib import admin from django.urls import path, include from main_app import views urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('', include('main_app.urls')), ] For my login.html template I've: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../../../favicon.ico"> <title>Jumbotron Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="../../dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="jumbotron.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"> … -
How can I access real file by using variable?
How can I access real file by using variable? In this directory,test.jpg is exsited. I wrote codes, def test1(): test2("test.jpg") def test2(file): #write something on test.jpg But in this case,test2 method gets test.jpg's letter,so not test.jpg.I want to pass test.jpg to test2 method,so how should I fix this?