Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why when i try to create a user in django the form doesn't react?
I tried to make a Customer: models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=20, null=True) phone = models.CharField(max_length=10, null=True) email = models.CharField(max_length=40, null=True) with the use of this form forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.TextInput(attrs={'placeholder': 'username'}), 'email': forms.TextInput(attrs={'placeholder': 'email'}), 'password1': forms.TextInput(attrs={'placeholder': 'password'}), 'password2': forms.TextInput(attrs={'placeholder': 'repeat password'}), } html <form method="post"> {% csrf_token %} <ul class="list-group list-group-flush"> <li class="list-group-item"><p>{{ form.username }}</p></li> <li class="list-group-item"><p>{{ form.email }}</p></li> <li class="list-group-item"><p>{{ form.password1 }}</p></li> <li class="list-group-item" style="border-bottom: 1px solid #e4e5e6;"><p>{{ form.password2 }}</p></li> </ul> <input class="btn btn-primary" type="submit" type="button" style="width: 27%;margin-left: 63%;margin-top: 4%;"> </form> views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name='customer') user.groups.add(group) user.objects.create( user=user, name=user.username, ) return redirect('/') return render(request, 'register_page.html', { 'form': form, }) but when I click submit nothing happens and it doesn't create a record. Please help :( dasdsadasdasdasdfasewgaggiuhihqworeghoashgiiasigjioasigjiaipgjiaiasoopijpgjiaspjgpisapigaspj -
how to differentiate two forms in a django template?
I'm creating forms directly in a django html template. In this template I have 2 forms. {% extends 'base.html' %} {% block title %} <title>Add Groups</title> {% endblock %} {% block content %} <h1>Add Groups</h1> <form method="post"> {% csrf_token %} <label>User</label> <input type="text" name="user_name"/> <label>Password</label> <input type="text" name="password"/> <input type="submit" value="Submit"> </form> {% if groups %} <form method="post"> {% csrf_token %} {% for group in groups %} <div class="div_group"> <h3> <input type="checkbox" name="{{group.id}}" value="{{group.name}}"> {{group.name}}</h3> <div> <span>Id:</span> {{group.id}} <br> <a href="{{group.link}}">{{group.link}}</a> <br> <span>Role:</span> {{group.role}} <br> <span>Tags:</span> {{group.tags}} </div> </div> {% endfor %} <input type="submit" value="Add Grupos"> </form> {% endif %} <br> {% endblock %} In the views.py im trying to differentiate from the forms. I've made it asking for fields that only appear in the first form def admin_add_group(request): if request.user.is_staff and request.user.is_staff: context = {} if request.method == 'POST': if 'user_name' in request.POST: user_name= request.POST['user_name'] mendeley_password = request.POST['password'] try: # login mendeley md.authenticate(mendeley_user, mendeley_password) groups = md.get_groups() context['groups'] = groups except Exception as exc: context['errors'] = [str(exc)] else: c = request.POST print(c) # redirect to groups view. return render(request, 'admin_add_group.html', context) else: context = {} return render(request, 'admin_add_group.html', context) Is there another way to know what form is makin … -
How to create multiple first in first out queues in celery?
I have a Django webservice running on one machine that submits jobs to a celery worker running on another machine. Here is what my models.py looks like: class Department(models.Model): name = models.CharField(max_length=200) class Employee(models.Model): name = models.CharField(max_length=200) department = models.ForeignKey(Department) This is what my celery systemd service file looks like this: [Unit] Description=celery daemon After=network.target [Service] Type=forking User=<user> Group=<group> WorkingDirectory=<path_to_working_directory> ExecStart=celery multi start worker -A project --pidfile=<process_id_path> \ --concurrency=1 --logfile=<path_to_logfile> --loglevel=debug ExecStop=celery multi stopwait worker -A project --pidfile=<process_id_path> \ --concurrency=1 --logfile=<path_to_logfile> --loglevel=debug ExecReload=celery multi refresh worker -A project --pidfile=<process_id_path> \ --concurrency=1 --logfile=<path_to_logfile> --loglevel=debug [Install] WantedBy=multi-user.target Currently, I use a Django signal that creates a new queue every time a new department is added. However if I set the concurrency to 1 in my systemd file then the worker runs only one job at the time. And if i don't mention concurrency then it sometimes runs multiple jobs from the same queue parallelly. I want it to run multiple jobs parallelly, but at a given time only one from each queue should be running. For example. Lets say there are 3 departments A,B,C. This creates 3 queues, one for each department, queueA, queueB, queueC. I want the worker to be concurrently … -
Generating Django HTML template with JavaScript
I used this function to download the PDF version of HTML template, but it didn't work, here is the function: <script> function getPDF() { var HTML_Width = $(".canvas_div_pdf").width(); var HTML_Height = $(".canvas_div_pdf").height(); var top_left_margin = 15; var PDF_Width = HTML_Width + (top_left_margin * 2); var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2); var canvas_image_width = HTML_Width; var canvas_image_height = HTML_Height; var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1; html2canvas($(".canvas_div_pdf")[0], { allowTaint: true }).then(function(canvas) { canvas.getContext('2d'); console.log(canvas.height + " " + canvas.width); var imgData = canvas.toDataURL("image/jpeg", 1.0); var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]); pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height); for (var i = 1; i <= totalPDFPages; i++) { pdf.addPage(PDF_Width, PDF_Height); pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height); } pdf.save("HTML-Document.pdf"); }); }; </script> It works only when the HTML snippet doesn't contain Django tags or variables, here is an example where it worked: <button onclick="getPDF()" id="downloadbtn" style="display: inline-block;"><b>Click to Download HTML as PDF</b></button> <div class="canvas_div_pdf" style="margin-left:100px;"> <h1>title</h1> <p> Content.</p> </div> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script> <script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script> And here is where it didn't work: <button onclick="getPDF()" id="downloadbtn" style="display: inline-block;"><b>Click to Download HTML as PDF</b></button> <div class="canvas_div_pdf" style="margin-left:100px;"> <h1>{{qr.title}}</h1> <p> {{qr.content}}</p> </div> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> … -
Django Project - Update made inadvertently now failing
I am working on a Django Project 3.0.7 using Python 3.8. Something was updated inadvertently [like the title says] and I can't seem to figure out what it is. Any assistance is appreciated, full traceback below: File "C:\Program Files (x86)\Python383-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Python383-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python383-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File … -
I can't find which algorithm should i use to solve this problem
I'm working on a project that will track the attendance and leaving of employees in a company. Each employee has a mobile application connected to the web server, once he reached his working area (each employee has a specific working area) he can log in using the mobile application (he can't log in outside his working area, we depend on Google APIs). For some restriction reasons from HR (i will not deep dive into details of that), Each 10mins the employee will automatically logout from the application and he needs to sign in again in the same working area. I will not mention a lot of details about the application to save your time but we can grasp from previous statements that each user will have multiple sign in time and sign out time at the same day, here is the DB model that will handle this: class SignInOutLogs(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) signin_time = models.DateTimeField(verbose_name="Sign in Time") signout_time = models.DateTimeField(blank=True, null=True, verbose_name="Sign Out Time") Our company has 1500 employees, we want to ensure that each one of them has attended 8 hours at work, after a lot of talking with HR, he told me … -
How to display the field "label" in django's builtin password validation errors?
I am using Django's builtin authentication class views and need to customize the error message displayed when password validation fails. For example, in the builtin PasswordResetView, if I try to change my password to test, the following errors will display in my template: new_password2 This password is too short. It must contain at least 8 characters. This password is too common. I would like to change new_password2 to New Password. Here is the relevant part of my template for the PasswordResetView: {% extends 'registration/base.html' %} {% block card_body %} <div class="form-group"> <label for="old_password"> Old Password: {{ form.old_password }} </label> </div> <div class="form-group"> <label for="new_password1"> New Password: {{ form.new_password1 }} </label> </div> <div class="form-group"> <label for="new_password2"> Confirm Password: {{ form.new_password2 }} </label> </div> <div class="form-group"> <input type="submit" value="Change" class="btn float-right login_btn"> </div> {% endblock card_body %} {% block card_footer %} {% if form.errors %} <p class="d-flex justify-content-center links"> {{ form.errors }} </p> {% endif %} {% endblock card_footer %} -
Add styling to django Password reset forms
I want to add styling to django's default password reset form such as classes and placeholders I have the following in my urls.py from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ # Password reset paths path('password_reset/', auth_views.PasswordResetView.as_view(template_name="main/password_reset.html"),name="reset_password"), path('password_reset_sent/', auth_views.PasswordResetDoneView.as_view(template_name="main/password_reset_sent.html"),name="password_reset_done"), path('reset_password/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="main/reset_password.html"),name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="main/reset_password_complete.html"),name="password_reset_complete"), ] in the templates <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="Send email" class="btn btn-primary" > </form> -
I need a way to pass unique object id in my django function based list view
I have been stucked on this for a couple of days, all help would be really cherished. I have a list and detail view which are function based views, my detail view works perfectly because i am able to pass the "/str:pk/" at the end of the url and also with the request as(def po_detail(request, pk)) which in turn i am able to pass into my view functions and they all successfully return the unique id i desire. I have a custom queryset i have written to help me get the sum total amount of some payments and return it in both the list and detail view. The issues now is that i am not able to get each unique items in my list view page because i am not able to pass the pk into the url and the request function as the object i used it for in detail function has access to the pk. I would love if any one can provide an hint, suggestion, or solution. Thanks, Oyero H.O Below is my model class PurchaseOrder(models.Model): created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) po_type = models.ForeignKey(PurchaseOrderType, on_delete=models.SET_NULL, null=True) status = models.CharField(choices=STATUS, max_length=15) supplier_ID = models.ForeignKey(Supplier, on_delete=models.SET_NULL, null=True) order_date … -
Django 'No file chosen' in FileInput
I have a project here. I am able to add photos through the /admin panel. I tried to create a form so that I can add a photo not by going thro' the admin panel. I get an error of file chosen. I can't tell where my problem is. My model class Photos(models.Model): Photo = models.ImageField(upload_to='background',blank=True,null=True) class Meta: ordering = ('-pk','Photo') def __str__(self): return('Photos') My forms.py class AddPhotosForm(forms.ModelForm): class Meta: model = Photos fields = ("Photo",) widgets = { "Photo":forms.FileInput(),} My views.py class AddPhotosView(CreateView): model = Contact form_class = AddPhotosForm template_name = "add_photo.html" success_url = reverse_lazy('photos') urls.py path('add_photo',AddPhotosView.as_view(), name='add_photo'), My add_photo.html {% extends "base.html" %} {% block title %} Add Photo {% endblock %} {% block content %} <hr> <article class="container" > <div class="btn-primary" style="padding:10px;border-radius:10px">Add Photo</div> <hr> <div> <div class="form-group"> <form method="POST"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button class="btn btn-outline-primary">Add</button><br><hr> </div> </div> </article> {% endblock %} -
Pass a queryset as the argument to __in in django?
I have a list of object ID's that I am getting from a query in an model's method, then I'm using that list to delete objects from a different model: item_ids = {item.id for item in self.items.all()} other_object = OtherObject.objects.get_or_create(some_param=some_param) other_object.items.filter(item_id__in=item_ids).delete() What I don't like is that this takes 2 queries (well, technically 3 for the get_or_create() but in the real code it's actually .filter(some_param=some_param).first() instead of the .get(), so I don't think there's any easy way around that). How do I pass in an unevaluated queryset as the argument to an __in lookup? I would like to do something like: other_object.items.filter(item_id__in=self.items.all().values("id")).delete() -
Filtering a reverse lookup in Django template
I have a model that looks like this class Invoice(models.Model): inv_number = models.CharField(max_length=10, primary_key=True) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) inv_date = models.DateField() class Txn(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.PROTECT) transaction_date = models.DateField() reference = models.CharField(max_length=12) amt = models.IntegerField() I would like to display a report in my template that lists filtered invoices each with a sub-list of filtered transactions. In my view I have done the following: invoice_list = Invoice.objects.filter(customer=customer) Which I pass into my template. In the template, I do something like the following: {% for invoice in invoice_list %} {{ invoice.inv_number }}, {{ invoice.customer}}, {{ invoice.inv_date }} {% for txn in invoice.txn_set.all %} {{ txn.transaction_date }}, {{ txn.reference }}, {{ txn.amt }} {% endfor %} {% endfor %} This works great to show the entire transaction list per filtered invoice. The question is, how does one also filter the list of transactions per invoice in the template - what if I wanted just the transactions within a certain date range or that match a specific reference? Is there maybe a way to pass a filter to the txn_set queryset per invoice in the view before putting the main queryset in the context and without converting them to lists? Thank you … -
Django queryset get names of model fields
I want to get field names of Django model through queryset. Models.py: class User1(models.Model): types1 = ( ('a', 'a'), ('b', 'b'), ('c', 'c'), ) types2 = ( ('a', 'a'), ('b', 'b'), ('c', 'c'), ) q1 = models.CharField ( 'Today1', max_length=200, choices=types1, blank=True, null=True, default='---------' ) q2 = models.CharField ( 'Today2', max_length=200, choices=types2, blank=True, null=False, default='---------', ) After queryset, I want to get [q1,q2] or something similar to this but containing only field names. -
Code runs in Google Collab but not on local machine python
I'm running a TensorFlow model and when I try to run it on google collab it runs fine but if I run the same code on my local machine it gives me the following error: C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks.py:1472: RuntimeWarning: invalid value encountered in less if self.monitor_op(current - self.min_delta, self.best): Traceback (most recent call last): File "lstm_var_1.py", line 363, in <module> callbacks=[es], steps_per_epoch= len(generator_train_var)) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\kerashypetune\kerashypetune.py", line 460, in search **all_fitargs) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in _method_wrapper return method(self, *args, **kwargs) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 876, in fit callbacks.on_epoch_end(epoch, epoch_logs) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks.py", line 365, in on_epoch_end callback.on_epoch_end(epoch, logs) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks.py", line 1485, in on_epoch_end self.model.set_weights(self.best_weights) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 1519, in set_weights if expected_num_weights != len(weights): TypeError: object of type 'NoneType' has no len() If anyone can help me it would be really great. https://colab.research.google.com/drive/1kQ2KeiSXEbLRJ3tooJ8A6-tg0oqmNBRR?usp=sharing Thanks in advance. -
Duplicate column name when sclaing django application using Swarm/k8s
my Django app uses a entry-point script in order to start the application using docker as the hypervisor platform of choice. As soon as the container starts, several checks getting executed to determine the service lvl., Database availability, migration status and much much more (please see shortened snipped below): ... if [ "$SERVICE_TYPE" = "app" ] then echo "Check for open migrations" python manage.py makemigrations $App1 $App2 $App3 etc... python manage.py migrate echo "Checking if System User is setup" python manage.py shell <<-EOF from django.contrib.auth import get_user_model User = get_user_model() # get the currently active user model User.objects.filter(user='$SYS_USER').exists() or User.objects.create_superuser('$SYS_USER', '$SYS_USER') EOF as soon as "python manage.py makemigrations $App1 $App2 $App3" gets executed the following error appears: django.db.utils.OperationalError: (1060, "Duplicate column name 'voter_id'") In practice this only happens if I scale the application container using Docker swarm or K8S. The initial start-up procedure of the very first container works fine, always! Please correct me If I'm wrong but shouldn't it be like that if "python manage.py makemigrations" as no open migrations that are waiting to get applied to the database it never should come to such an error? Actually I would always expect that Django prints: "No changes detected in … -
Django group : only add specific user among other
I got a question what the best way to add only specific user to a group. Assume I got a userprofile, and some of user make is_ready true. When creator create a new group to one user. I'd like to only have inside of seller user (is_ready=true) user/models.py class UserProfile(models.Model): ... is_ready = models.BooleanField('Become one', default=False) exemple/models.py class Exemple(models.Model): creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="exemple_creator") seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="exemple_seller") # only user that is_ready=True ... exemple/views.py class Createexemple(CreateView): model = Exemple form_class = CreateExempleForm template_name = 'exemple_new.html' def form_valid(self, form): form.instance.creator = self.request.user form.save() return super(Createexemple, self).form_valid(form) def get_success_url(self): return reverse_lazy('exemple:exemple_home') -
Django Celery Error Message Cannot Serialize
I keep getting this error message when I run my script on my Djano App. (Object of type WSGIRequest is not JSON serializable) when I have my serializer set to JSON. If i change it to Pickle, I get this error message. (cannot serialize '_io.BufferedReader' object). I have spent days on this trying to figure out how to fix this. I appreciate any help. Thanks Here is my script im sending to celery. def ImportSchools(request): print("Getting school data from SIS") url = "" payload = {} token = APIInformation.objects.get(api_name="PowerSchool") key = token.key headers = {'Authorization': 'Bearer {}'.format(key)} response = requests.request("GET", url, headers=headers, data = payload) encode_xml = response.text.encode('utf8') pretty_xml = xml.dom.minidom.parseString(encode_xml) pretty_xml_str = pretty_xml.toprettyxml() xml_string = ET.fromstring(encode_xml) schools = xml_string.findall("school") for school in schools: psid = school.find("id").text name = school.find("name").text school_number = school.find("school_number").text low_grade = school.find("low_grade").text high_grade = school.find("high_grade").text if not School.objects.filter(schoolpsid=psid): print("Record doesn't exist in DB, creating record.") x = School.objects.create(schoolpsid=psid, school_name=name, school_number=school_number, low_grade=low_grade, high_grade=high_grade) x.save() elif School.objects.filter(schoolpsid=psid).exists(): print("Record exists in DB, updating record.") School.objects.filter(schoolpsid=psid).update(school_name=name, school_number=school_number, low_grade=low_grade, high_grade=high_grade) print("School Data Pull Complete") return("Done") -
Parse ISO string to date
I am trying to parse 2020-09-18T16:11:03.4411565+00:00 Code from dateutil import parser parser.isoparse('2020-09-18T16:11:03.4411565+00:00') I am getting ValueError: Unused components in ISO string Also i am using 3.6.9 so i can't use datetime.fromisoformat(date_string) What can I do? -
Is it possible to integrate Django Paypal IPN without using paypal_dict form?
I am trying to use the javascript button code provided by paypal instead of the paypal_dict form passed from the view to the template. I want to use the paypal code because of its modern design and simplicity. I have the paypal code working well on sandbox. Specifically I am using subscriptions payment method. I have integrated paypal IPN in settings.py: INSTALLED_APPS = [ ... 'paypal.standard.ipn', ... urls.py: urlpatterns += [ ... path('', include(apps.get_app_config('oscar').urls[0])), ... I have added the following to apps.py from django.apps import AppConfig class MypaypalConfig(AppConfig): name = 'myPaypal' def ready(self): import myPaypal.signals.handlers and here is my handlers.py file: from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received from django.utils import timezone from Store.colors import * def show_me_the_money(sender, **kwargs): ipn_obj = sender print(sender) if ipn_obj.payment_status == ST_PP_COMPLETED: print("ST_PP_COMPLETED") valid_ipn_received.connect(show_me_the_money) and in my template I have the code provided by paypal: <div id="paypal-button-container"></div> <script src="https://www.paypal.com/sdk/js?client-id= ***" data-sdk-integration-source="button-factory"></script> <script> paypal.Buttons({ style: { shape: 'pill', color: 'gold', layout: 'vertical', label: 'subscribe' }, createSubscription: function(data, actions) { return actions.subscription.create({ 'plan_id': '***' }); }, onApprove: function(data, actions) { // $("#confirm_form").submit() console.log(data) console.log(actions) } }).render('#paypal-button-container'); </script> After I successfully process the payment(sandbox) I don't receive any IPN. Is there a possible way to integrate paypal … -
Login is not working in custom User modal in Django
I have created custom user model consist of username and password and I use logged in through the username and password but when i try to login the login is not working register_app/model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class Register(models.Model): class Meta: db_table = "register" id = models.AutoField(primary_key = True) first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) email=models.EmailField() class HandleloginManager(BaseUserManager): def create_user(self, username, password=None): if not username: raise ValueError("username is required") user = self.model( username = self.username, ) user.set_password(password) user.save(using=self._db) return user class Handlelogin(AbstractBaseUser): class Meta: db_table = "login" username = models.CharField(max_length=150, unique = True) password = models.CharField(max_length = 50) register = models.OneToOneField(Register, on_delete=models.CASCADE) USERNAME_FIELD="username" REQUIRES_FIELD=['password'] objects = HandleloginManager() register_app/views.py from django.shortcuts import redirect, render, HttpResponse from .models import Register, Handlelogin from django.contrib.auth import authenticate, login # Create your views here. def home(request): return render(request, 'home.html') def register(request): if request.method == 'POST': if request.POST.get('firstname') and request.POST.get('lastname') and request.POST.get('username')and request.POST.get('email') and request.POST.get('password'): add = Register() add.first_name= request.POST['firstname'] add.last_name= request.POST['lastname'] add.email= request.POST['email'] add.save() d = Handlelogin() d.username= request.POST['username'] d.password= request.POST['password'] d.register = add d.save() return redirect('/') else: return render(request,'register.html') def users(request): reg = Register.objects.all() return render(request, 'users.html', {'reg':reg}) def login_handle(request): if request.POST: username = request.POST['user'] password = request.POST['pass'] … -
Can't migrate due to FieldDoesNotExist Error
The migration stopped working when switching from ForeignKey between Shop and user to a ManyToManyField. I wanted shops to be able to be owned by different users at the same time: class Shop(models.Model): name = models.CharField('name', max_length=120) #user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ManyToManyField(User, related_name="shopusers", blank=True) class Meta: constraints = [models.UniqueConstraint(fields=['user', 'name'], name='user cant have the same shop twice!')] @property def get_users_for_shop(self): return ", ".join([u.username for u in self.user.all()]) class Warehouse(models.Model): address = models.CharField('address', max_length=120) user = models.ManyToManyField(User, related_name="User", blank=True) django.core.exceptions.FieldDoesNotExist: NewShop has no field named 'shopusers' I thought by choosing a related name I can use multiple relations to the User model? I already tried completely deleting my database and migrate from start, but tht did not help :( -
Django change permission management logic
I'm trying to change the permission management logic to grant the following behaviour: if a permission belongs both to user group and user or neither, the user can't perform the action tied to permission if a permission belongs to one of user group and user, the user can perform the action. Following the documentation, I thought to do this by writing my custom authorization backend: from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission UserModel = get_user_model() class CustomBackend(ModelBackend): def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_group_permissions(self, user_obj): user_groups_field = get_user_model()._meta.get_field('groups') user_groups_query = 'group__%s' % user_groups_field.related_query_name() return Permission.objects.filter(**{user_groups_query: user_obj}) def get_user_permissions(self, user_obj, obj=None): group_permissions = self.get_group_permissions(user_obj) assigned_permissions = user_obj.user_permissions.exclude(permission__in=group_permissions).all() print(assigned_permissions) return assigned_permissions I don't understand why it doesn't work. I'm also trying to find other solutions. -
I wanted to get data from my django mobels but it's shown error context must be a dict rather than QuerySet
I tried to pull the data from my models but It's return "{'data': <QuerySet [<WareHousePlan: Part ID : 1 Part No : 71398-KK010-00 PartName : HOLDER RR Depart Time : 2020-09-18 22:27:00 Status : True>]>}" which cause TypeError What should I do ? This is my views.py from django.shortcuts import render from django.http import HttpResponse def Home(request): return render(request,'Warehouse/HomePage.html') from .models import WareHousePlan def ShowSchedule(request): data = WareHousePlan.objects.all() context = {"data": data} return render(request,'Warehouse/Showschedule.html',data) -
I get an error when I try to change my upload image function name Django
Here it is my models.py that works. from __future__ import unicode_literals from django.db import models from django.urls import reverse from django.db.models.signals import pre_save from services.utils import unique_slug_generator from PIL import Image def upload_location(instance, filename): return "%s/%s" %('image/service', filename) # Create your models here. class Services(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=250, null=True, blank=True) content = models.TextField(null=True, blank=True) icon = models.ImageField(upload_to=upload_location, blank=True, null=True) category = models.CharField(max_length=255, default='all') def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 320 or img.width > 560: output_size = (320, 560) img.thumbnail(output_size) img.save(self.image.path) def __unicode__(self): return self.title def __str__(self): return self.title def slug_generator(sender, instance, *args, **kargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Services) The problem is when I want to change def upload_location 's name. I tried to use def upload_location_icon as name and I changed the upload_to to icon = models.ImageField(upload_to=upload_location_icon, blank=True, null=True) This is the terminal error How can I change def upload_location name without errors? -
Decorate an inherited method without changing the method
I have this class, which inherits from another class (in this case django-rest-frameworks mixing.RetrieveModelMixin) and I want to use all of the functionality of the given retrieve() function. However I have to decorate it in order to work with swagger. class TestAPI(mixins.RetrieveModelMixin, viewsets.Viewset): model = TestModel serializer_class = TestSerializerClass @swagger_auto_schema(operation_description="TESTTEST") def retrieve(self, request, *args, **kwargs): pass This states that Expected a 'Response', 'HttpResponse' or 'HttpStreamingResponse' to be returned from the view, but received a '<class 'NoneType'>'. This leads me to believe that the "workflow" is stopped at the pass and not passed on to the parent method, which I need. I tried using the super() method with super(TestAPI, self).__init__() instead of pass but this didn't work either. I don't want to change the behaviour of the retrieve method, I just want to decorate it. When I delete the whole reference to it, it works fine.