Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django manytomany through with constraint
I tried to use ManytoManyfield with through into my models to help user to associate their Basket with mulitples % of items. Each items have a value and each user have a budget. So i am not able to limit items association even i used a field percentage. Do you have any idea how to add this constraint ? meaning user cannot add more than 100% of the items to one or more Basket below my models so far : class Basket(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) items = models.ManyToManyField(items,through='Percentage') details = models.CharField(max_length=200) date = models.DateField(blank=True, null=True) budget = models.IntegerField(default=0) class Percentage(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) basket = models.ForeignKey(Basket, on_delete=models.SET_NULL, blank=True) item = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True) percentage = models.IntegerField(default=0) class Item(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=20) description = models.CharField(max_length=250) value = models.CharField(max_length=20) -
Please enter the correct Email and password for a staff account. Note that both fields may be case-sensitive
I complete makemigrations and migrate then create a superuser. After this http://127.0.0.1:8000/admin i try to log in then show this error Please enter the correct Email and password for a staff account. Note that both fields may be case-sensitive seetings.py AUTH_USER_MODEL = 'user.CustomUser' **models.py** from django.db import models from django.contrib.auth.models import AbstractUser,BaseUserManager class CustomUserManager(BaseUserManager): """ Creates and saves a User with the given email, date of birth and password. """ def create_user(self, email, password=None): if not email: raise ValueError('User must have an email id') user=self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): user=self.create_user( email, password=password ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractUser): #only add email field for login email = models.EmailField( verbose_name='Email', max_length=50, unique=True ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email ***admin.py*** from django.contrib import admin from django.contrib.auth import get_user_model user=get_user_model() admin.site.register(user) -
how to deploy and upload python app to CPanel?
Dears, I'm trying to deploy a python web application on Cpanel hosting provider but I cannot determine the: Application startup file. Application Entry point. Check attached screenshots (Cpanel required fields + app files), please need help and advice Cpanel required fields Applications files -
Unique values of field per user
I have a model where users can have duplicate values but each user can only have unique values. for example - User A can have value1, value2, value3, all unique values. User B can have value1, value3, value4, again all unique values. So both users can have value1 but neither User A or User B can have multiple value1(duplicate values) So I cant do something like this in the model (setting unique = true) class ABC(models.Model): field1 = models.EmailField(unique=True) What is the best way to validate such a case? For now, I'm checking values in the database against the value which I pass during the create method of my views.py. And looking for any better approach to use in build Validators from the rest framework. class abc_viewset(viewsets.ModelViewSet): queryset = abc.objects.all() serializer_class = abc_serializer def create(self, request, format=None): data = request.data serializer = self.get_serializer(data=request.data) self.field1=data['field1'] self.prevValues=abc.objects.filter(field1=self.field1,user=request.user) .values_list('field1',flat=True) if self.prevValues: return Response({"Failure":"Dublicate value"}) if serializer.is_valid(): serializer.save() -
Getting a word document from a django generated view
I have a class based django view that presents some tables and text to the user dependent on their inputs. I would like to have a button on this page that allows the user to download this data as a word document. What would be the best way to accomplish this? urls.py app_name = "patient" urlpatterns = [ path('add/', views.PatientAddView.as_view(), name="patient_add"), path( route='<patient_id>/', view=views.TreatmentTemplateView.as_view(), name='treatment_detail'), ] views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context hmtl {% extends "base.html" %} <!-- {% block title %}Patient: {{ patient.name }}{% endblock %} --> {% block content %} <h3>Patient Summary</h3> <p> {{pt_letter|linebreaks}} </p> <br> <br> <h3>Current Medication</h3> <p> {{current_med_letter|safe}} </p> <br> <br> <h3>Past Medication</h3> <p> {{past_med_letter|safe}} </p> <br> <br> <h3>Plan </h3> <br> <h5>Treatment Recommendation</h5> <p> {{newmed_letter|safe}} {{existingmed_letter|safe}} </p> <br> <h5>Physical Health Monitoring</h5> <p> {{monitor_letter|safe}} </p> <br> <h5>Potential Drug Interactions</h5> <p> {{interaction_letter|safe}} </p> {% endblock content %} -
Viewing a Word doc in Django
Fairly new to Django and I have an app that records certain details from the user, it then adds these details to certain fields in a template to create a brand new 'report'. This all works fine, however I am finding it difficult to now upload that report to a page so that the user may view it.\ views.py form.save(commit=False) new_record = form.save(commit=False) new_record.save() tpl = DocxTemplate('record/retail_report_temp.docx') context = { 'date_time': form['date_time'].value(), 'name': form['name'].value(), 'd_o_b': form['d_o_b'].value(), 'department': form['department'].value(), } tpl.render(context) tpl.save(f"{form['name'].value()}_retail_report.docx") return render(request, 'home.html',) HTML {% if record.retail_pack %} <a class="nav-link" href="{{ record.retail_pack }}">Report</a> {% endif %} I can view the report from the file and that part works, but I would like the user to have a link or something so they could view/print the report. Thank you in advance for your time, it is much appreciated. -
How do I display image in my view page django
I have created a page when the staff click on the view button, it should redirect them to the view page and display it out accordingly, like when the user click on the view button for id 1 it should display the id 1 image out, but it is not displaying. This is how it my viewreception page looks like. when the staff click on the view button, the url did manage to get the id but image not displaying out. models.py class Photo(models.Model): class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' datetime = models.DateTimeField() image = models.ImageField(null=False, blank=False) descriptionbox = models.TextField() serialno = models.TextField() partno = models.TextField() reception = models.TextField() customername = models.TextField() nonc = models.TextField() # nonc stand for non conformity TypeOfNonConformity = models.TextField() def __str__(self): return self.descriptionbox urls.py urlpatterns = [ path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('changepassword/', views.changepassword, name='changepassword'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('updatestaff', views.updatestaff, name='updatestaff'), path('delete/<int:id>/', views.delete, name='delete'), path('deletephoto/<int:id>/', views.deletephoto, name='deletephoto'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), path('edit_profile/', views.edit_profile, name='edit_profile'), path('ReceptionUnserviceable/', views.ReceptionUnserviceable, name='ReceptionUnserviceable'), … -
While proceeding for payment, a pop-up box pops up saying, Invalid amount
When i try to proceed for payment, after clicking the button, a pop-up shows saying Oops! Something went wrong. Invalid amount (should be passed in integer paise. Minimum value is 100 paise, i.e. ₹ 1) The order_amount is being correctly fetched, then why is the amount is not been processed? views.py: #Payment Integration - Razorpay @login_required def payment(request): add = Address.objects.filter(default=True) order = Order.objects.filter(user=request.user).first() print(order) client = razorpay.Client(auth=("XXX", "YYY")) if order.razorpay_order_id is None: order_id = order.order_id print(order_id) x = order.get_total() print(x) order_amount = int(x) * 100 print(order_amount) order_currency = 'INR' order_receipt = 'Rcpt' #data = {"amount": order_amount, "currency": order_currency, "receipt": order_receipt, "payment_capture": '1'} razorpay_order = client.order.create(dict(amount=order_amount, currency=order_currency, receipt=order_receipt, payment_capture=1)) # Razorpay order inserted into database order order.razorpay_order_id = razorpay_order["id"] order.save() else: razorpay_order = client.order.fetch(order.razorpay_order_id) return render(request, 'payment.html', {'razorpay_order': razorpay_order, 'add': add}) -
Is it possible to let Postgres automatically retry transactions?
I'm developing a Django application in which I want to have strong guarantees about the correctness of the data. For this reason, I have SERIALIZABLE as the transaction isolation level. However, during load testing I see some related error messages: could not serialize access due to read/write dependencies among transactions DETAIL: Reason code: Canceled on identification as a pivot, during write. HINT: The transaction might succeed if retried. and could not serialize access due to read/write dependencies among transactions DETAIL: Reason code: Canceled on conflict out to pivot 23933812, during read. HINT: The transaction might succeed if retried. and current transaction is aborted, commands ignored until end of transaction block I do automatically retry the transaction via Django, but I'm uncertain if this solution is actually good. I wondered: Is it possible to let Postgres automatically retry transactions that failed for those reasons? Is there maybe something directly in Django allowing me to configure that? (It would not have to be for all transactions; I know the candidates that are failing more often / that are more important) -
Unable to understand self-referencing many-to-many and filter in django?
I am trying to learn Self-referencing many-to-many and stuck on code segment Let assume two models,Person and relation ship,as below:- class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') status = models.IntegerField(choices=RELATIONSHIP_STATUSES) and person model contains following methods:- def get_relationships(self, status): return self.relationships.filter( to_people__status=status, to_people__from_person=self) def get_related_to(self, status): return self.related_to.filter( from_people__status=status, from_people__to_person=self) I am unable to understand how these two methods are working and what they are returning. I am unable to understand how filter and reverse-lookup are working together. Please anyone help me to understand real intuition behind this. Thanks in advance. Hope to here from you soon. -
how to get python screen sharing seperate application window to show on django web server?
Im fairly new to python and django and im trying to share the desktop video of a windows virtual machine to show onto a linux django web server. When i run the python scripts the screen sharing would show as a seperate application window. How do i get the python seperate window to show onto the django web server instead? receiver.py (running on linux machine) from vidstream import StreamingServer import threading receiver = StreamingServer('ipaddr', 8080) t = threading.Thread(target=receiver.start_server) t.start() while input("") != 'STOP': continue receiver.stop_server() sender.py (running on windows virtual machine) from vidstream import ScreenShareClient import threading sender = ScreenShareClient('ipaddr', 8080) t = threading.Thread(target=sender.start_stream) t.start() while input("") != 'STOP': continue sender.stop_stream() -
ImportError: cannot import name 'DEFAULT_CURRENCY' from 'moneyed' on Ubuntu
I've been using Django for just over a year for the development of an automation software and am currently just running the project locally on my windows machine. I hadn't run into any issues with it, until I tried running cron tasks, which ofc windows doesn't support. Scheduled tasks don't work the same way imo, so I installed a Ubuntu VM to work with the project. Set everything up correctly(I think?), installed Django and all. Currently installing all the libraries the project uses, one of which is django-money. I have installed it, as well as py-moneyed, yet on trying to make migrations, or run the server, I run into this error enter image description here Can't find anything about this online. The project still works perfectly with the windows command prompt, as well as PowerShell but having this issue on the ubuntu VM. Installed apps on my settings.py look like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap5', 'sass_processor', 'djmoney', 'background_task', 'django_crontab', 'companies', 'google_cal', 'dashboard', ] Any help on this, or good alternative for corn tasks-need some to run every 2 hours and update the db and others to run once a day at a specific time. Celery … -
Need a solution to user Django Authentication associated with some specific models and way to create user
I need you help to know what is the best way in Django to use authentication but with some specific way to create user (except superuser) and after to associated this user with only one specific role. It's for using with elementaries students. #1 I want to create a user but the user has to type his firstname, lastname and his password ... that's all ! Code should slugify firstname and lastname separate with a "." (it will be the username) and add "@mail.com" (it will be the mail). Of course it's allready exist it will add "-1" after. For this point actually I only succeeded to overload User models in Django and user email instead username ... But it's typing manually (username and email) ... #2 IN the same Register form I want to add the way to choose which classroom he belong to. This list will be a models name Role with only name into ... SO in the register form html I need to have firstname (text) / lastname (text) / classroom (list) / password (password) ... all mandatory :) For this last point, I tried to create Model RoleUser with User in OneToOneField and Role in … -
Django throws TemplateDoesNotExist for a template located it in the 'my_app/templates/my_app' subfolder
I am studying Django and got stuck right at the first project. I've got TemplateDoesNotExist exception when accessing index page of my application. I saw a lot of same looking questions here, but answers seem to be referring to slightly different cases or older Django versions. Template-loader postmortem shows that Django looked for the index page (index.html) in the 'movies/templates' directory, while file is placed inside 'movies/templates/movies' as it is suggested by manuals. Project info Project structure 'movies' is added to the INSTALLED_APPS list in the settings.py And movies/views.py refers to the index.html in following way: def all_films(request): return render(request, 'index.html', {'movies': my_movies, 'director': settings.DIRECTOR}) What worked Adding 'os.path.join(BASE_DIR, 'movies', 'templates', 'movies'),' to the TEMPLATES['DIRS'] values in the settings.py makes it work, but after reading manuals and answers to same questions I assume it shouldn't be required. Also, if I change movies/views.py so that it refers to 'movies/index.html' instead of 'index.html' everything works. But is it a good practice to use app name in links like this? I mean, it could be hard to maintain in future etc. Question Basically, question is what am I doing/getting wrong. Could you please suggest, what else should I check to make it work … -
Why do I have to reload twice before my HTML gets updated in Django?
i'm working on a videogames webstore on Django, currently on the cart. This are the basic components of the system: A Videogame model, containing basic info of a Videogame (name, image, price, stock, etc.) A Item in Cart model, containing an Integer Field (amount) and a One to One Field of Videogames. The idea of this is to have a model with the amount of times a videogame is added to cart by a particular client A Visiting Client model, containing the visitor's IP as ID and a Many to Many field of a Item in Cart model Models: class Videogame(models.Model): name = models.CharField(max_length=50, blank=False, unique=True) image = models.ImageField(upload_to='products_images/', blank=False) category = models.ManyToManyField(Category) description = models.TextField(blank=True) stock = models.DecimalField(blank=True, null=True, max_digits=3, decimal_places=0, default=0) price = models.DecimalField(blank=False, max_digits=6, decimal_places=2, default=0.00) visible = models.BooleanField(blank=False, default=True) class Meta: verbose_name_plural = 'Videogames' def __str__(self): return self.name class ItemInCart(models.Model): amount = models.PositiveIntegerField(default=1) product = models.OneToOneField(to=Videogame, on_delete=CASCADE) id = models.TextField(primary_key=True) class Meta: verbose_name_plural = 'Items In Cart' def __str__(self): return self.id class VisitingClient(models.Model): id = models.GenericIPAddressField(primary_key=True) amount_of_visits = models.IntegerField(default=1) first_visit = models.DateTimeField(auto_now_add=True) last_visit = models.DateTimeField(auto_now=True) items_in_cart = models.ManyToManyField(ItemInCart) def __init__(self,*args,**kwargs): super(VisitingClient, self).__init__(*args, **kwargs) if self.amount_of_visits is None: self.amount_of_visits = self.amount_of_visits def __str__(self): return self.id Now, in … -
Can I save richtext data in Django TextField() model?
Since, I want to make my app as lightweight as possible and thus using quill editor for my richtext editor can I use Django TextField() model to save my data? And what are its limitations -
Django Paginator shows post titles Not Page numbers, why?
i'm trying to use Django Paginator using ListView, but the paginator shows post title instead of page number: Page number replaced with post title how can i fix that? this is my code: in views.py: from django.shortcuts import render from django.core.paginator import Paginator from django.views.generic import ListView, DetailView from .models import Post # Create your views here. # PostObject_list by using ListView class PostList(ListView): model=Post paginate_by=20 context_object_name='all_posts' ordering=['-created_at'] # allpost by using ListView '''class AllPost(ListView): model=Post context_object_name='allpost' paginate_by=None ''' # Post_singl_object using DetailView class PostDetail(DetailView): model=Post in template post_list.html : </div> <nav aria-label="Page navigation example"> <ul class="pagination d-flex justify-content-center mt-1"> {% if all_posts.has_previous %} <li class="page-item "><a class="page-link" href="?page={{ all_posts.previous_page_number }}">Previous</a></li> {% endif %} {% for page in all_posts %} <li class="page-item "> <a class="page-link" href="?page={{ page }}"><span>{{page}}</span></a> </li> {% endfor %} {% if all_posts.has_next %} <li class="page-item"><a class="page-link" href="?page={{all_posts.previous_page_number }}">Next</a></li> {% endif %} </ul> </nav> </div> <!-- Pagination--> thank you! -
'Photo' object is not iterable error in django
I have created a page when the staff click on the view button, it should redirect them to the view page, but I am getting this error 'Photo' object is not iterable as shown in the picture below. How do I solve this error? This is how my page looks like with the view button 'Photo' object is not iterable error views.py def view(request, pk): alldescription = Photo.objects.get(id=pk) return render(request, 'view.html', {'alldescription': alldescription}) urls.py urlpatterns = [ path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('changepassword/', views.changepassword, name='changepassword'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('updatestaff', views.updatestaff, name='updatestaff'), path('delete/<int:id>/', views.delete, name='delete'), path('deletephoto/<int:id>/', views.deletephoto, name='deletephoto'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), path('edit_profile/', views.edit_profile, name='edit_profile'), path('ReceptionUnserviceable/', views.ReceptionUnserviceable, name='ReceptionUnserviceable'), path('success', views.success, name='success'), path('logisticprofile', views.logisticprofile, name='logisticprofile'), path('viewreception/', views.viewreception, name='viewreception'), path('view/<str:pk>/', views.view, name='view'), path('outgoingLRU/', views.outgoingLRU, name='outgoingLRU'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) viewreception.html {% extends "logisticbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, … -
Fetching data from API in django
I have access to an outside API which have some data something like the following: { "Successful":true, "Message":"[{\"Id\":1,\"GroupId\":0,\"QuestionTitle\":\"What is your first name?\",\"GroupName\":null,\"QuestionType\":\"TEXT\",\"IsMappingAvailable\":null,\"BodyRegion\":0,\"EnableCalculation\":false,\"Responses\":[]},{\"Id\":2,\"GroupId\":0,\"QuestionTitle\":\"And your last name?\",\"GroupName\":null,\"QuestionType\":\"TEXT\",\"IsMappingAvailable\":null,\"BodyRegion\":0,\"EnableCalculation\":false,\"Responses\":[]}]" } Now I want to show all these Id and QuestionTitle in my template. my views.py: def GetQuestion(request): headers = {'Content-Type': 'application/json', 'Authorization': 'Basic XXXXXXXXXX='} body = { "Tenant" : "devED" } GetQuestion_response = requests.post('https://url_name.com/api/GetQuestions', headers=headers, json=body).json() GetQuestion_dict={ 'GetQuestion_response' : GetQuestion_response, } return render(request, 'app\GetQuestion.html', GetQuestion_dict) in my template: {% for i in GetQuestion_response.Message %} <h2>ID: {{ i.Id }}</h2> <h2>QuestionTitle: {{ i.QuestionTitle }}</h2> {% endfor %} But unfortunately, it shows no results. Maybe it's because the value of the Message key in the API is inside the double quote (like a string). Please suggest how can I fix this? -
Database design and normalization in django
I have a web form where a student can enter their info and grades e.g. Name Age Math Grade Spanish Grade Chemistry Grade This would transform to a POST request like below: POST /grades { "name": "Bob", "age": 17, "math_grade": "A", "spanish_grade": "B", "chemistry_grade": "C", } Finally, this would be stored in a SQL table grades like below by django ORM: Name Age Subject Grade Bob 17 Math A Bob 17 Spanish B Bob 17 Chemistry C All good till here. As I read about the different normal forms (1NF, 2NF, 3NF), it seems like the above table should really be two tables (student and grades) or maybe even three (student, subject DIMENSION table, grades FACT table). Q1. If the grades table should really be split, should I do it at the application level where django ORM executes SQL query against multiple tables at once or am I pre-optimizing here? Should I do the normalization as part of my data warehousing strategy and leave the application table as-is? Q2. If I want to return the grades for Bob in a nested format like below, how would I do that in django. GET /grades/Bob { "name": "Bob", "age": 17, "grades": { … -
In Razorpay Payment Gateway, the order_amount is not been fetched. How can I get the amount?
While I am using Razorpay Payment Gateway for my Payment Integration, the order_amount is not been fetched from the model. As seen in the models.py , there are two methods to get the total amount of the order, but trying any one of them , the order_amount is not sending any correct value, and hence I am being stuck here for days now. Please help. Thank You Below is the traceback of the error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\blink\myblink\onlineshopping\views.py", line 243, in payment order_amount = order.get_total * 100 Exception Type: TypeError at /shoppe/payment/ Exception Value: unsupported operand type(s) for *: 'method' and 'int' Views.py: #Payment Integration - Razorpay @login_required def payment(request): add = Address.objects.filter(default=True) order = Order.objects.filter(user=request.user).first() print(order) #order=admin client = razorpay.Client(auth=("rzp_test_0kYEl3pVDjgz2A", "1yZe58wefzjlWYbqjekVUeKS")) if order.razorpay_order_id is None: order_id = order.order_id print(order_id) #order_id=1 order_amount = order.get_total * 100 print(order_amount) order_currency = 'INR' order_receipt = 'Rcpt' data = {"id": order_id, "amount": order_amount, "currency": order_currency, "receipt": order_receipt, "payment_capture": '1'} razorpay_order = client.order.create(data=data) # Razorpay order inserted into database order order.razorpay_order_id = … -
Django Q filters and & operator
How to query different values of the same column using Django models that must include all entries? I tried this way but always return empty result, even if the object filtered contains all entries? query = Q() for _id in includedFeaturesList: query = query & Q(feature_id=_id) familyFeatFilterIds = phenodbsearch.models.FamilyMemberFeature.objects.filter(submission_id=submission, family_member_id=familyMember).filter(query).values('family_member_feature_id') logger.debug('all features : %s', familyFeatFilterIds) -
django forms for filtering
I am trying to make a form for filtering a table by its columns , condition and text given by users.(text is not required) for example, the user selects a column, greater,less, equals etc. forms class FilterForm(forms.Form): COLUMN_FILTER_CHOICES = ( ('title', 'Title'), ('quantity', 'Quantity'), ('distance', 'Distance'), ) CONDITION_FILTER_CHOICES = ( ('equals', 'Equals'), ('contains', 'Contains'), ('greater', 'Greater'), ('lower', 'Lower'), ) search = forms.CharField(required=False) column_filter_field = forms.ChoiceField(choices=COLUMN_FILTER_CHOICES) condition_filter_field = forms.ChoiceField(choices=CONDITION_FILTER_CHOICES) views class TableView(ListView): model = Table template_name = 'spa/index.html' context_object_name = 'table' paginate_by = 5 def get_queryset(self): query = self.request.GET.get('search') column_filter_field = self.request.GET.get('column_filter_field') condition_filter_field = self.request.GET.get('condition_filter_field') return Table.objects.all() def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['tables'] = Table.objects.all() context['form'] = FilterForm(initial={ 'search': self.request.GET.get('search', ''), 'column_filter_field': self.request.GET.get('column_filter_field', ''), 'condition_filter_field': self.request.GET.get('condition_filter_field', ''), }) return context template <form action="" method="get" class="inline"> {% csrf_token %} {{ form.column_filter_field }} {{ form.condition_filter_field }} {{ form.search }} <input type="submit" class="btn btn-default" value="Search"> </form> the form is now working now, there is no response from the form. and i need to refresh my table in real time without updating page, i cant find any information to filter in real time , is it possible to do with django? -
I am having a page not found (404) error django
I have created a page where there is a view button and when the staff click on the view, it should redirect them to the view page but I am getting a page not found(404) error, instead of having the image pop out in the view page. I can't figure out what is wrong with my code, the view in the url seems like match to me page not found error(404) views.py @login_required() def view(request, id): alldescription = get_object_or_404(Photo, id=id) context = {'alldescription': alldescription} if request.method == "POST": return HttpResponseRedirect("/view") return render(request, 'viewreception.html', context) urls.py urlpatterns = [ path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('changepassword/', views.changepassword, name='changepassword'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('updatestaff', views.updatestaff, name='updatestaff'), path('delete/<int:id>/', views.delete, name='delete'), path('deletephoto/<int:id>/', views.deletephoto, name='deletephoto'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), path('edit_profile/', views.edit_profile, name='edit_profile'), path('ReceptionUnserviceable/', views.ReceptionUnserviceable, name='ReceptionUnserviceable'), path('success', views.success, name='success'), path('logisticprofile', views.logisticprofile, name='logisticprofile'), path('viewreception/', views.viewreception, name='viewreception'), path('view/<int:id>/', views.view, name='view'), path('outgoingLRU/', views.outgoingLRU, name='outgoingLRU'), ] viewreception.html {% extends "logisticbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, … -
Many-to-many relationship with self table Django
I am having a table with a self-referencing column with many-to-many relations class PanelUser(core_models.TimestampedModel): assigned = models.ManyToManyField("self", related_name="panelusers", blank=True) def __str__(self): return self.user.username Problem I have three records A, B, C and if I and assigning A = B then is automatically assigned B = A I don't understand why this is happing, how I fix it.