Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compute average value
I have set up a table where players can input three income values in three different cells. I would like to set up a fourth cell where the average value is computed. Any idea? <table class="table-bordered" style="width:100%"> <tr style="background-color:#ffb380"> <th scope="col" colspan="1" style="text-align:center"> Anno </th> <th scope="col" colspan="1" style="text-align:center"> 2018 - 2019 </th> <th scope="col" colspan="1" style="text-align:center"> 2019 - 2020 </th> <th scope="col" colspan="1" style="text-align:center"> 2020 - 2021 </th> <th scope="col" colspan="1" style="text-align:center"> Reddito MEDIO</th> </tr> <tr style="background-color:#ffe0cc"> <td scope="col" colspan="1" style="text-align:center"> Reddito/ettaro </td> <td scope="col" colspan="1" style="text-align:center"> {% formfield 'income1'%} €/ha </td> <td scope="col" colspan="1" style="text-align:center"> {% formfield 'income2'%} €/ha </td> <td scope="col" colspan="1" style="text-align:center"> {% formfield 'income3'%} €/ha </td> <td scope="col" colspan="1" style="text-align:center"> 'inc_avg' €/ha </td> </tr> </table> {%formfield 'income1' %} and so on are integer.Field where the players inputs the values. ps I am using otree -
how to generate qr code with python and when scanned make it open a url defined?
Hi how are you? how do I generate a qr code which when scanned opens a url? is it possible to use a library like qrcode or pyqrcode to accomplish this? something like this : pyq = QRCode() pyq.generate(url="http://google.com/") thanks in advance! -
Django template var in Javascript
Let's take a dictonary: mydict = { 'color': "blue", 'brand': "Ford", 'year': 1969 } We pass this dict to our template, then, in the template, we have a select list with options according to our dictionary keys (color, brand, year). Now, I want to change some text in my rendered template regarding the selected option. So we have some Jquery that is getting the value of the selected option, like this: $('#myselect').change(function() { var selected = $( "#myselect option:selected" ).text(); }); Now that we have the selected text, I would like to use it as a key to display a value from our dictionary. Something like this $('#myselect').change(function() { var selected = $( "#myselect option:selected" ).text(); $('#mytext').text('{{ mydict.selected }}'); }); But I guess mixing Django var and JS var like this, is not going to work... Any idea how I can do this ? -
How to add new class argument while keeping the original (inherent ones)?
My problem The graphql_social_auth.SocialAuthMutation in the following Claas class SocialAuth(graphql_social_auth.SocialAuthMutation): class Arguments: id = graphene.Int(required=False) user = graphene.List(schema.Users) is passing few arguments and functionalities. But when I added class Arguments: id = graphene.Int(required=False) To it, I lost the original arguments. My goal I want to pass the new arguments while keeping the arguments and the functionalities of graphql_social_auth.SocialAuthMutation If you can't understand GraphQL Generally, in python and in Django you can pass a functionality in a class like models.Model which have hidden functionalities and argument that help you create a model without explicitly adding all the code. # models.py class Post(models.Model): # in this example if I tryied to use `class Arguments:` the arguemnts that came from models.Model will not be passed . But what I want is to keep the `models.Model` and add class`class Arguments:` ass well description = models.CharField(max_length=9999999) title = models.CharField(max_length=200) -
django-queryable-properties confusion
I ran into a problem with django-queryable-properties package. I have this model: class MyModel(Model): f1 = CharField() f2 = AnnotationProperty( annotation=RegexpMatches(source='f1', regexp=MY_REGEXP, group=1) ) objects = QueryablePropertiesManager() And the problem is: postgres throw an error when i try to filter on field f2 because postgress do not allow functions on where clause. After some researches i found that field f2 do not figure in select clause of generated sql. In other words: when i try MyModel.objects.filter(f2='a').first() the folowing sql is generated: SELECT "myapp_mymodel"."f1" FROM "myapp_mymodel" WHERE (regexp_matches("myapp_mymodel"."f1", (^m.+)_.+))[1] = 'a' And my question is: How can i add f2 into select clause to make it possible to lookup on this field using django-queryable-properties package. -
Django _set behaving just like .objects?
I have been trying to override objects behavior using a custom manager. class AbstractBase(models.Model): # ... objects = CustomManager() My objects will automatically filter out the instances that have their field is_deleted as True I was wondering... if I were to grab the same model's instances using _set.all(), would this behave just like that custom objects? Otherwise, do I have no choice but to find every _set.all() and refactor it to _set.filter(is_deleted=False)? -
is there any function or method to auto-update the attribute in record of django admin,when the record is saved
Present I am working on commerce website when the seller updates the order status to delivered condition , delivered time attribute must be auto-updated -
Simple CreateView returns 405 Method Not Allowed
Very simple CreateView is not working, and I do not know why: view: class CreateProduct(CreateView): template_name = "app/product_create2.html" form_class = ProductForm success_url = reverse_lazy("index") form: class ProductForm(ModelForm): class Meta: model = Product fields = ("description", "name", "price") def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.field_class = 'mb-2' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) urls: path("create/", views.CreateProduct.as_view(), name = 'create'), template: <div class="modal-body"> {% csrf_token %} {% crispy form %} </div> When I input Data in the form I get: Method Not Allowed (POST): / and I can seet the 405 error in the console. -
how to check if new entry is added to postgres DB?
In my Django project, I am getting new values every other second with an MQTT client and save them in Postgresql. In the front end, I try to get new values and plot them with ajax calls. Consider a situation when, for any reason, the connection gets lost and no new data comes to the DB. I want such functionality: if no new data is added to DB, then null values should be sent via AJAX. I tried checking the id of the latest object of the previous query, but I couldn't implement it for a situation when the DB is empty. -
OS Time in Python 3.8.5
I've got the following dictionary in my code: "morning": now.hour > 0, "afternoon": now.hour > 12, "evening": now.hour > 18, "bit_late": now.hour > 21, It's part of a Django project (v3.1), and whenever I run the server it throws up no errors, but it is using UTC time instead of my local system's time (+ 5 1/2 UTC). Hence, when I viewed the page at 3 PM, it wished me "Good morning" (which it's programmed to do). I've included the datetime library, but I don't know how to use it or any other library to try and get the program to run using system time. Am I missing any particular library? What method should I use to get the system time, and where do I put it? now = datetime.datetime.now() This is the code I used for "now", just for reference! Thanks in advance! -
How to pass data to the model field when saving the form? django form models save
get the form and process it in post. It is necessary to save the unique uuid of the record to the model, I do it like this: formOne.save(related_uuid=related_uuid) but doesn't work, the error is - save() got an unexpected keyword argument 'related_uuid' models class Orders(models.Model): device = models.CharField(max_length=150) uuid = models.CharField(max_length=22, blank=True) views class OrderAddView(TemplateView): template_name = 'orders/order_add.html' def get(self, request, *args, **kwargs): context = super().get_context_data(**kwargs) ... some work code return self.render_to_response(context) def post(self, request, *args, **kwargs): formOne = SimpleOrderAddForm(self.request.POST, prefix='one_form') if formOne.is_valid(): related_uuid = shortuuid.uuid() formOne.save(related_uuid=related_uuid) return HttpResponseRedirect('orders_home') else: print('NotValid') return self.form_invalid(formOne, **kwargs) def form_invalid(self, formOne,, **kwargs): context = self.get_context_data() ... some work code return self.render_to_response(context) -
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) when migrating
I am building a Location based webapp and I am stuck on a Problem. What i am trying to do I am trying to load json file and saving into database. The Problem When i run python manage.py migrate in console then it keep showing me json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) migrations.py DATA_FILENAME = 'data.json' def load_data(apps,schema_editor): Shop = apps.get_model('mains','Shop') jsonfile = Path(__file__).parents[2] / DATA_FILENAME with open(jsonfile,'r',encoding='utf-8') as datafile: objects = json.load(datafile) for obj in objects['elements']: try: objType = obj['type'] if objType == 'node': tags = obj['tags'] name = tags.get('name','no-name') longitude = obj.get('lon',0) latitude = obj.get('lat',0) location = fromstr(f'POINT({longitude} {latitude})', srid=4326) Shop(name=name,location = location).save() except KeyError: pass class Migration(migrations.Migration): dependencies = [ ('mains', '0003_shop'), ] operations = [ migrations.RunPython(load_data) ] What have i tried I tried bz2 function to unzip json data but it was unhelpful for me. I tried replacing file name into full path but nothing worked for me. I don't know what to do. Any help would be appreciated. Thank You in Advance. -
Django - Referential integrity on OneToOneField
I am trying to import a product feed (Product) into Django. I need to maintain a set of selected products (SelectedProduct) which also hold overrides for the product descriptions. I thought the best way to represent this is as a OneToOneField linking SelectedProduct with Product. class Product(models.Model): sku = models.CharField(max_length=32, primary_key=True) title = models.CharField(max_length=200) description = models.TextField(max_length=2000, blank=True, null=True) class SelectedProduct(models.Model): product = models.OneToOneField(Product, db_column='product_sku', on_delete=models.DO_NOTHING) description = models.TextField(max_length=2000, blank=True, null=True) For simplicity, each time the product feed is read, I am intending to delete all the products and re-import the whole product feed (within a transaction, so I can rollback if required). However, I don't want to truncate the SelectedProduct at the same time, since this contains the descriptions which have been overridden. I was hoping that models.DO_NOTHING might help, but it doesn't. I suppose I either need to temporarily disable the referential integrity while I import the feed (and delete any entries from SelectedProduct which would break the integrity) or I need to represent the relationship differently. Any advice appreciated please :-) Note - the above is a simplified representation. I have variants hanging off products too and will have selected variants overriding variant prices. -
trying to install exchangelib package in dockerized django i receive following error
Building wheel for cryptography (PEP 517): started Building wheel for cryptography (PEP 517): finished with status 'error' ERROR: Command errored out with exit status 1: command: /usr/local/bin/python /usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmp_g7gpo_c cwd: /tmp/pip-install-2y_1vrjf/cryptography_c327dead1e3c4d5ead1c1745ab7281d2 Complete output (151 lines): running bdist_wheel running build running build_py -
Page not found (404) jquery django python
jquery does not load - Page not found (404) base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="{% static 'bootstrap-5.0.0/css/bootstrap.css' %}" rel="stylesheet"> <link href="{% static 'css/style.css' %}" rel="stylesheet"> <!-- jQuery --> <script src="{% static 'jquery/jquery.js' %}"></script> </head> setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ServiceCRM3/static'),] static folder created the script is in the path static / jquery / jquery.js bootstrap picks up ok in the same folder the server restarted what's wrong? -
Delete an user object automatically after some time in django models
I want automatically delete the user object or make default="" in my model after 2 min. Here is my model. What am I doing wrong!! from django.db import models from django.contrib.auth.models import User from datetime import datetime, timedelta from django.utils import timezone from datetime import date class Action(models.TextChoices): REQUESTED = 'Requested' ACCEPTED = 'Accepted' REJECTED = 'Rejected' class UserMembership(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, default='') student_id = models.CharField(max_length=10, default='') membership_type = models.CharField(max_length=50) membership_action = models.CharField(max_length=50, choices=Action.choices, default=Action.REQUESTED) start_date = models.DateTimeField(default=timezone.now,blank=True,) @property def delete_after_thirty_days(self): time = self.start_date + datetime.timedelta(minutes=2) if time < datetime.datetime.now(): e = UserMembership.objects.get(user=self.user) e.delete() return True else: return False def __str__(self): return self.name Basically, after 2 minutes the values of the UserMembership model related to the specific user should be deleted or change back to default values. currently, nothing happens and I don't get any errors as well. Thank you for your time. -
Can the query be shrinked into lesser statements and optimized?
business_user = User_Profile.objects.get(user = request.user) reqs = Business_Influencers_Requests.objects.filter(business_request=business_user).values_list('influencer_request') users = User_Profile.objects.exclude(user__in=reqs).filter(role='I',admin_verify=True)[page_start:page_end] The code above does the following on each line respectively. 1-get business_user object of id request.user from model 2-gets influencers_list,a list of type influencers that relate to the business_user 3-gets a list of users of role I and admin_verify=True excluding those which are found in influencers_list -
trouble installing mysqlclient on mac
Using cached mysqlclient-1.3.0.tar.gz (76 kB) ERROR: Command errored out with exit status 1: command: /Users/mr.sallam/.local/share/virtualenvs/Admission_System-h6ReVRNX/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/58/khmzr9l90hx237729cjz2ct00000gn/T/pip-install-cn6qvsqm/mysqlclient_c82e6a9eeefe4d66bf9960f11336d0db/setup.py'"'"'; __file__='"'"'/private/var/folders/58/khmzr9l90hx237729cjz2ct00000gn/T/pip-install-cn6qvsqm/mysqlclient_c82e6a9eeefe4d66bf9960f11336d0db/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/58/khmzr9l90hx237729cjz2ct00000gn/T/pip-pip-egg-info-186pdzul cwd: /private/var/folders/58/khmzr9l90hx237729cjz2ct00000gn/T/pip-install-cn6qvsqm/mysqlclient_c82e6a9eeefe4d66bf9960f11336d0db/ Complete output (10 lines): /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/58/khmzr9l90hx237729cjz2ct00000gn/T/pip-install-cn6qvsqm/mysqlclient_c82e6a9eeefe4d66bf9960f11336d0db/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/58/khmzr9l90hx237729cjz2ct00000gn/T/pip-install-cn6qvsqm/mysqlclient_c82e6a9eeefe4d66bf9960f11336d0db/setup_posix.py", line 47, in get_config libs = mysql_config("libs_r") File "/private/var/folders/58/khmzr9l90hx237729cjz2ct00000gn/T/pip-install-cn6qvsqm/mysqlclient_c82e6a9eeefe4d66bf9960f11336d0db/setup_posix.py", line 29, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/6a/91/bdfe808fb5dc99a5f65833b370818161b77ef6d1e19b488e4c146ab615aa/mysqlclient-1.3.0.tar.gz#sha256=06eb5664e3738b283ea2262ee60ed83192e898f019cc7ff251f4d05a564ab3b7 (from https://pypi.org/simple/mysqlclient/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ERROR: Could not find a version that satisfies the requirement mysqlclient ERROR: No matching distribution found for mysqlclient -
Exception Value: _getfullpathname: path should be string, bytes or os.PathLike, not list
I don't what's the problem, i tried everything but never understood, what should i do in this scenario, please take a look Setting.py When i am doing this like that: STATIC_URL = '/static/' STATICFILES_DIRS = os.path.join(BASE_DIR, 'static') MEDIA_URL ='/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') it is showing this error ERRORS: ?: (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or list. HINT: Perhaps you forgot a trailing comma? Setting.py When i am doing this like that: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL ='/images/' MEDIA_ROOT = [os.path.join(BASE_DIR, 'static/images'),] it is showing this error TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not list [17/Mar/2021 13:27:59] "POST /admin/admission/personal/add/ HTTP/1.1" 500 211689 anyone who could help?? -
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 121835: character maps to <undefined>
I am building a Location based Webapp and I am stuck on an Error. UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 121835: character maps to This error is keep showing when i migrate the DataBase. migrations.py DATA_FILENAME = 'data.json' def load_data(apps,schema_editor): shop = apps.get_model('mains','Shop') jsonfile = Path(__file__).parents[2] / DATA_FILENAME with open(str(jsonfile)) as datafile: objects = json.load(datafile) for obj in objects['elements']: try: objType == obj['type'] if objType == 'node': tags = obj['tags'] name = tags.get('name','no-name') longitide = obj.get('lon',0) latitude = obj.get('lat',0) location = fromstr(f'POINT({longitide} {latitude})', srid=4326) Shop(name=name,location = location).save() except KeyError: pass What have i tried I tried many answer like put encoding='cp437, it didn't worked for me. I also tried encoding="utf8", it didn't work too. When i add , encoding = 'cp850' with filename then it shows json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I don't what am i doing wrong. Any help would be appreciated. Thank You in Advance. -
Is there a way to determine the order in which a FilterSet (from django-filter) perform queries?
Im using django-filter for a project. I've had to declare methods for filters in order to merge the queries being made. However besides doing those merges I also need to apply other filters. My problem is that there seems to be no way to determine the order in which the filters perform the queries. Here's my code class Tramite(models.Model): .... class FechasEtapas(models.Model): tramite = models.ForeignKey(Tramite, on_delete=models.CASCADE, related_name='etapas') etapa = models.IntegerField(choices=ETAPA_CHOICES, default=1) The views: class TramiteFilter(filters.FilterSet): origen__contains = BaseCSVFilter(method='filter_origen') origen__not_contains = BaseCSVFilter(method='filter_not_origen') lead__fecha_creacion = DateFromToRangeFilter() fecha_etapa_1__after = CharFilter(method='filter_etapa_fecha_greater') fecha_etapa_2__after = CharFilter(method='filter_etapa_fecha_greater') fecha_etapa_3__after = CharFilter(method='filter_etapa_fecha_greater') .... def __init__(self, *args, **kwargs): self.len_tramite = Tramite.objects.all().count() super().__init__(*args, **kwargs) class Meta: model = Tramite fields = { 'lead__score': ['lte', 'gte'], .... } def filter_origen(self, qs, name, value): return qs.filter(reduce(operator.or_, (Q(origen__contains=x) for x in value))) def filter_not_origen(self, qs, name, value): return qs.exclude(reduce(operator.or_, (Q(origen__contains=x) for x in value))) def filter_etapa_fecha_greater(self, qs, name, value): if len(qs) != self.len_tramite: return (qs | Tramite.objects.filter(etapas__etapa=name[12], etapas__fecha_etapa__gte=value).distinct()).distinct() return qs.filter(etapas__etapa=name[12], etapas__fecha_etapa__gte=value) I need that the filters fecha_etapa_x__after are run first so the other queries are made over the already merged queries, however right know my code is doing the opposite. Is there a way to achieve this? Thanks in advance. -
Return value from another model Django
I try to get data from a ChoiceField and bind to textbox. I have model BookingUnit one to many with PaymentTerm and PaymentTerm one to many with UnitPrice. I want when bookingUnit, select the paymentTerm and it will return with unitPriceAmount from model UnitPrice. How to solve this? Best Regards, Capah Maga Here Model,Form, view and template that i use. Model.py class UnitBooking(models.Model): projectID = models.ForeignKey(Project,on_delete=models.CASCADE) bookingID = models.AutoField(primary_key=True) bookingNo = models.CharField(max_length=20) unitID = models.ForeignKey(Unit,on_delete=models.CASCADE) nupNo= models.CharField(max_length=20) paymentTermID = models.ForeignKey(PaymentTerm,on_delete=models.CASCADE) unitBasePriceAmount = models.DecimalField(max_digits=20,decimal_places=2) unitPriceAmount = models.DecimalField(max_digits=20,decimal_places=2) remarks = models.CharField(max_length=16) isActive = models.BooleanField(default=True) insertTime = models.DateTimeField(default=datetime.now,blank=True) insertUser = models.CharField(max_length=50) lastUpdated = models.DateTimeField(default=datetime.now,blank=True) lastUpdater = models.CharField(max_length=50) def __str__(self): return self.bookingNo class PaymentTerm(models.Model): projectID = models.ForeignKey(Project,on_delete=models.CASCADE) paymentTermID = models.AutoField(primary_key=True) paymentTermNo = models.CharField(max_length=20) paymentTermName = models.CharField(max_length=150) isActive = models.BooleanField(default=True) insertTime = models.DateTimeField(default=datetime.now,blank=True) insertUser = models.CharField(max_length=100) lastUpdated = models.DateTimeField(default=datetime.now,blank=True) lastUpdater = models.CharField(max_length=150) def __str__(self): return self.paymentTermID class UnitPrice(models.Model): projectID = models.ForeignKey(Project,on_delete=models.CASCADE) unitPriceID = models.AutoField(primary_key=True) unitID = models.ForeignKey(Unit,on_delete=models.CASCADE) paymentTermID = models.ForeignKey(PaymentTerm,on_delete=models.CASCADE) basepriceAmount = models.DecimalField(max_digits=20,decimal_places=2) taxAmount = models.DecimalField(max_digits=20,decimal_places=2) totalAmount = models.DecimalField(max_digits=20,decimal_places=2) isActive = models.BooleanField(default=True) insertTime = models.DateTimeField(default=datetime.now,blank=True) insertUser = models.CharField(max_length=150) lastUpdated = models.DateTimeField(default=datetime.now,blank=True) lastUpdater = models.CharField(max_length=150) def __str__(self): return self.unitPriceID ===================================================================== Form.py class UnitBookingForm(forms.ModelForm): projectID = forms.ModelMultipleChoiceField(queryset=Project.objects.all(),widget=forms.Select(attrs={'class' : 'form-control'}),label="Project ID") bookingID = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}),label="Booking ID") bookingNo … -
TypeError at /post 'User' object is not iterable
I am currently building a post page for my web application Tutor find. The post page is can be only accessed when a user logins. I need the post page to show all the posts done by the current user. Please help Here is my models.py code class Skill(models.Model): teacher_name = models.CharField(max_length=50) skill_type = models.CharField( max_length=30, choices=SKILL_CHOICES, ) name = models.CharField(max_length=65) duration = models.IntegerField() cost = models.IntegerField() location = models.CharField(max_length=65) def __str__(self): return str(self.skill_type + " " + self.name) My view for posting skills in the home page : @login_required def postskill(request): if request.method == 'POST': print(request.user.id) print(request.user.username) form = PostRecord(request.POST) if form.is_valid(): data = form.cleaned_data s = Skill( # author = request.user.id, teacher_name = request.user.username, skill_type = data.get('skill_type'), name = data.get('name'), duration = data.get('duration'), cost = data.get('cost'), location = data.get('location'), ) s.save() allskills = Skill.objects.all().order_by('name') return render(request, 'home.html', {'skills': allskills}) else: form = PostRecord() return render(request, 'postskill.html', {'form': form}) View for post page: def post(request): logged_in_user_posts = Skill.objects.filter(request.user) return render(request, 'post.html', {'posts': logged_in_user_posts}) urls: urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), path('post', views.post, name='post'), ] template for postskill {% extends "base_generic.html" %} {% block content %} <h2>Post Skill</h2><br> … -
Mongodb query to check if a particular field is not null ( aggregation)
I have queries like { "title": "sjncx", "desciption": "cknxk jckd", "price": "29.99", "stock": "3", ... } I need to filter data if the title is not empty.( title exists and not null). And also is empty like ~ title: "" ~ ( so title exists but empty) I tried for is not empty: {'title': {'$ne': 'null'}} for is empty: I tried {'title': {'$type': 10}} That doesn't work. What would be the reason? -
Attribute error : 'str' object has no attribute 'post'
I am new to Django and trying to integrate razorpay with my website but getting error AttributeError: 'str' object has no attribute 'post' views.py def order(request, id): product = Product.objects.get(prod_ID=id) if request.method == 'POST': customer_id = request.user product = Product.objects.get(prod_ID=id) product_id = product try: quantity = request.POST['quantity'] quantity = int(quantity) order_price = quantity * product.prod_Price print(order_price) except MultiValueDictKeyError: pass try: size = request.POST['size'] value.update(size=size) except MultiValueDictKeyError: pass try: Colour = request.POST['Color'] value.update(Colour=Colour) except MultiValueDictKeyError: pass attribute_value = json.dumps(value) order_store = Order(user_id=customer_id, prod_id=product_id, quantity=quantity, attribute_value=attribute_value, order_price=order_price) if order_store: order_store.save() o_id = Order.objects.get(order_id=order_store.order_id) payment_store = Payment(order_id=o_id) payment_store.save() client = razorpay.Client('rzp_test_Cut6mUJgrjfQU', 'LSNlrKrH0NoUq8Y9rEUbg27') print(client) data = { 'amount': order_price * 100, 'currency': "INR", 'receipt': 'Order for ' + str(o_id.order_id), 'notes': { 'name': o_id.user_id.first_name + o_id.user_id.last_name, 'Payment_for': o_id.prod_id.prod_Name } } print(data) order_detail = client.order.create(data=data) print(order_detail) return render(request, 'user/payment.html', {'order_store': order_store}) context = {'products': products } return render(request, 'user/order.html', context) Here I am trying to integrate payment with my website but after creating order and payment status I am trying to do payment but I don't know what I am doing wrong.