Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form errors not displaying with Django Crispy Forms
I just started learning Django and Python some weeks back. Working on a project sign up page, everything works perfectly except that form errors are not displaying on the form itself but redirected to a debug error page with the below ValidationError at /register/ ['Username exists'] Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 3.2.5 Exception Type: ValidationError Exception Value: ['Username exists'] During a new user profile registration, i am checking if the username used to register already exists or not and if it exists, i want to display an error to user that Username already exists. Please see my code below: forms.py class RegistrationForm(forms.Form): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') username = forms.CharField(label='Username') password = forms.CharField( label='Password', widget=forms.PasswordInput(), min_length=8) password_confirm = forms.CharField( label='Confirm Password', widget=forms.PasswordInput()) email_address = forms.EmailField(label='Email') phone_number = PhoneNumberField(label='Phone Number') whatsapp_number = PhoneNumberField(label='WhatsApp Number', required=False) COUNTRY_CHOICES = [ ('', 'Choose...'), ] country = forms.ChoiceField(label='Country', choices=COUNTRY_CHOICES) referral_id = forms.CharField(label='Referral ID', required=False) license_agreement = forms.BooleanField( label='I agree to all the Terms and Conditions') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'create-account-form' self.helper.form_action = 'register' self.helper.form_show_errors = True self.helper.layout = Layout( Row( Column('first_name'), Column('last_name'), css_class='g-2' ), Row( Column( PrependedText('username', '@') ), Column('country'), css_class='g-2' ), … -
Python Django website for task Scheduling
I am creating a website for my College Project using Python Django Framework for Task Scheduling.Every user creates their own account.I am asked to add a functionality that when a user logs in with its credentials, the user must get suggestions from it's past experience for eg" you scheduled task for drinking water on sunday at 10:30 am, so would you like to add it to the schedule now?". So I want to know How I can achieve this ? and Feature is same for all users but each user gets suggestions based on it's own data.Please let me know about the same in Detail. -
How do I auto select group name in particular group post, i have done with authenticated user auto select
I am trying auto select group name based on in which group user want to post, if user in particular group details page. when he click post . the form will auto select group name... this is my post model: class Posts(models.Model): groups_name = models.ForeignKey(Groups, related_name='posts', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='my_posts', on_delete=models.CASCADE) post_body = models.TextField(blank=True,null=True) post_image = models.ImageField(upload_to='images/posts/', blank=True, null=True) post_created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) + ' |' + str(self.groups_name) def post_name(self): return self.post_body[:1000] def get_absolute_url(self): return reverse("groups:group_detail", kwargs={"slug": self.groups_name.slug}) class Meta: ordering = ["-post_created"] this is my view: class CreateGroupPost(LoginRequiredMixin, CreateView): model = Posts form_class = GroupPostCreateForm login_url = '/account/login/' template_name = 'groups/addpost_group.html' this is my urls.py: app_name = 'groups' urlpatterns = [ path('', GroupListView.as_view(), name='group_list'), path('create_group/', GroupCreateView.as_view(), name='create_group'), path('<str:groups_name>/create_grouppost/', CreateGroupPost.as_view(), name='create_grouppost'), path('group_detail/<slug>', GroupDetailView.as_view(), name='group_detail'), path('group_update/<slug>', GroupUpdateView.as_view(), name='group_update'), path('join/<slug>/', Joingroup.as_view(), name='join_group'), path('leave/<slug>/', LeaveGroup.as_view(), name='leave_group'), ] this is group_details.html i gave url link to add post: {% if user in groups.members.all %} <div class="d-grid gap-2 mt-3"> <a href="{% url 'groups:create_grouppost' groups.groups_name %}" class="btn btn-primary">Create Post</a> </div> {% else %} <div class="d-grid gap-2 mt-3"> <a class="btn btn-primary" href="{% url 'groups:join_group' groups.slug %}">Join Group</a> </div> {% endif %} this is my add_post.html page add post page -
image not updating in django from form post request
I am trying to edit an object through the form All fields are edited but the image field does not change What is the problem? model created with signals when user create account template <div> <form action="{% url 'user:profile' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="submit"> </form> </div> model class Profile(models.Model): CHOICES = ( ('RE', 'مشاور املاک'), ('S', 'فروشنده'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) real_estate = models.OneToOneField(Business , related_name='business' ,on_delete=models.CASCADE, blank=True , null=True) image = models.ImageField(blank=True) type_of_user = models.CharField(max_length=300, choices=CHOICES) phone_number = PhoneNumberField(unique = True, null = False, blank = False) form class ProfileForm(ModelForm): class Meta: model = Profile fields = ['type_of_user' , 'phone_number' , 'image'] views def profile(request): profile = Profile.objects.get(user=request.user) if request.method == 'POST': form = ProfileForm(request.POST , instance=profile) profile = form.save(commit=False) profile.user = request.user profile.save() redirect('busi:index') else: form = ProfileForm() context = { 'profile':profile, 'form':form } return render(request , 'user/profile.html' , context) -
is there anyway to accept dogecoin or TRX to website (django)
I am on project where I have to implement crypto Wallet to perform dogecoin or tron transactions but I have never worked with crypto wallets nor I have any idea , so can someone suggest me how to integrate it with some steps please. thank you -
django.core.exceptions.ValidationError: ['“Undergraduate” is not a valid UUID.']
I'm trying to add a way for a user to select if they are a undergrad or grad student in my models.py. Everything works except when I added this code below: undergrad_or_grad = models.OneToOneField( 'StudentStatus', default="Undergraduate", on_delete=models.CASCADE) Basically my thought process was, if the user doesn't select an option, they'll just be defaulted as an undergrad type student. Below is my full models.py file. from django.db import models from django.contrib.auth.models import User import uuid from django.db.models.signals import post_save, post_delete class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) profile_picture = models.ImageField( null=True, blank=True, upload_to='profiles/', default='profiles/defaultProfile.jpeg') username = models.CharField( max_length=200, null=True, blank=True, unique=True) name = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=1000, null=True, blank=True) undergrad_or_grad = models.OneToOneField( 'StudentStatus', default="Undergraduate", on_delete=models.CASCADE) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) class StudentStatus(models.Model): STUDENT_TYPES = ( ('undergrad', 'Undergraduate'), ('grad', 'Graduate'), ) title = models.CharField(max_length=200, null=True, blank=True, choices=STUDENT_TYPES) date_created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.title) Here's my full error after I run python manage.py makemigrations and then python manage.py migrate. I tried getting rid of default="Undergraduate" but the error still persists. (env) PS D:\Django Projects\StudentArchive> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, users Running … -
Raw Query to Django ORM Query
I have these two models: class Project(models.Model): name = models.CharField(max_length=200) class ProjectAdditionalInfo(models.Model): project = models.OneToOneField(Project) info = models.TextField() The Raw SQL is: select * from project_projectadditionalinfo A left join project_project B on A.project_id=B.id where B.id is null What will be the django query in response to the raw sql provided? Thanks in Advance. -
Deletion of an object in SQLite3 outputs a different error than Postgres
I have a Django and pytest-django project and I'm encountering a weird issue. My prod env has a Postgres DB and when running local tests I use SQLite3. Our DB schema look like this class A(BaseModel): # Some properties class B(BaseModel): a = models.ForeignKey(A, on_delete=DO_NOTHING, null=False) # Some other properties Assuming I have 2 objects (a which is an instance of A, and b which is an instance of B), deleting object a before deleting b will raise the following error on Postgres: django.db.utils.IntegrityError: update or delete on table \"db_a\" violates foreign key constraint \"db_a_id_32c056c8_fk\" on table \"db_b\" However, running the same code locally, using the (in-memory version of) SQLite, will raise: django.db.utils.IntegrityError: The row in table 'db_b' with primary key '453c667321254983915068259f6a999f' has an invalid foreign key: db_b.a_id contains a value 'b8fd641710be466ca8eab451faaed757' that does not have a corresponding value in db_a.id. So, in both cases, the deletion operation will output an error - but not the same one. I have no issues with the fact that an error is raised, but I would like my local unit tests to have the same error outputted as my remote one without changing the DB locally to PG. Any insights into this behaviour, … -
Image Gallery paginate through pure JavaScript
Django Here is my Django Template, to fetch images from database through {% for Nslide, Products, range in allProducts %}, now I want to pagination for each three Carousel using pure JavaScript no jQuery, how it's possible? I searched a lot but all the solution are based on Array, or tables not for Gallery. Thanks.. {% for Nslide, Products, range in allProducts %} <div id="carousel{{forloop.counter}}" class="carousel slide carousel-fade" data-bs-ride="carousel"> <ul class="carousel-indicators"> <button type="button" data-bs-target="#carousel{{forloop.counter}}" data-bs-slide-to="0" class="active"></button> <!-- Start of Range forloop --> {% for i in range %} <button type="button" data-bs-target="#carousel{{forloop.parentloop.counter}}" data-bs-slide-to="{{i}}"></button> {% endfor %} <!-- End of Rang forloop --> </ul> <!-- Start of Div => pricing --> <div class="pricingdiv" id="slider-wrapper"> <div class="carousel-inner "> <!-- Start of Carousel-item Active --> <div class="carousel-item active"> <!-- Start of (Product) forloop --> {% for i in Products %} <!-- Start of Div (Col) --> <div class="col-xs-3 col-sm-3 col-md-3 p-2 mt-3 reveal"> <!-- Start of Div (productHover) --> <div class="productHover gallery-items"> <div class="card card-body"> <img src='{{i.Product_Image}}' class="xzoom rounded-circle border card-img-top" /> <!-- start Div (card-body) --> <div class="card-body"> <h5> <strong> <a class="dark-grey-text">{{i.Product_name}}</a> </strong> </h5> <p class="card-text">{{i.Product_Description}}</p> <div class="row"> <div class="col-sm-12 "> <button id="pr{{i.id}}" class="btn btn-primary btn-sm shoppingCart" onclick="('productId = {{i.id}}')">Add to Cart</button> </div> … -
Why Django Channels test suites and consumers are using different databases?
Today, I ran into a problem with Django channels. I noticed that my test suites and and my consumers are using different databases. For example if I create a fake User object (for authentication) in my test suites, My consumer doesn't have access to that fake user. When I inspected the value of User.objects.all() inside my test suite, I got my fake user in the queryset but when I evaluated the same expersion inside my consumer's connect method, I got my real users in the original database which clearly shows that my consumer is not using the test database but it is using the original database. I wanted to know why my consumer is using the original database instead of the test database which is supposed to contain fake data for testing purposes? Here are all the packages I have installed: aioredis==1.3.1 asgiref==3.4.1 async-timeout==3.0.1 attrs==21.2.0 autobahn==21.3.1 Automat==20.2.0 autopep8==1.5.7 certifi==2021.5.30 cffi==1.14.6 channels==3.0.4 channels-redis==3.3.0 charset-normalizer==2.0.4 constantly==15.1.0 cryptography==3.4.7 daphne==3.0.2 Django==3.2 django-cors-headers==3.7.0 django-crum==0.7.9 django-extensions==3.1.3 django-filter==2.4.0 django-random-queryset==0.1.3 django-schema-graph==1.2.0 django-spaghetti-and-meatballs==0.4.2 djangorestframework==3.12.4 djangorestframework-recursive==0.1.2 djangorestframework-simplejwt==4.6.0 drf-spectacular==0.15.1 factory-boy==3.2.0 Faker==8.10.2 gunicorn==20.1.0 hiredis==2.0.0 hyperlink==21.0.0 idna==3.2 incremental==21.3.0 inflection==0.5.1 jsondiff==1.3.0 jsonschema==3.2.0 Markdown==3.3.4 msgpack==1.0.2 Pillow==8.2.0 psycopg2-binary==2.8.6 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.7.0 pycparser==2.20 PyJWT==2.1.0 pyOpenSSL==20.0.1 pyrsistent==0.18.0 python-dateutil==2.8.2 python-dotenv==0.15.0 pytz==2021.1 PyYAML==5.4.1 requests==2.26.0 service-identity==21.1.0 six==1.16.0 sqlparse==0.4.1 text-unidecode==1.3 toml==0.10.2 Twisted==21.7.0 … -
django custom tags that returns a boolean - using in a boolean expression in template results in "Unused 'foo' at end of if expression."
I am using Django 3.2 I am writing custom template tags for my project. This is some of my code: /path/to/myapp/templatetags/wanna_be_starting_something.py @register.simple_tag(name='can_dance_with', takes_context=True) def can_dance(context, danceable_object): request = context['request'] user = request.user if isinstance(danceable_object, Danceable): return danceable_object.can_dance(user) return False /path/to/myapp/templates/myapp/dancing.html {% load wanna_be_starting_something %} {% if can_dance_with nicegirl %} <div class="col">Nice!</div> {% else %} <div class="col">Oh Dear!</div> {% endif %} When I run the HTML above, I get the error message: Unused 'nicegirl' at end of if expression. If I remove the if conditional - it runs fine. How can I write a custom tag that returns a boolean that can be used in conditional expressions in the calling template? -
Overriding templates with Django 3.2.6
I am new to python and working through a Zero to Hero course by Mosh on YouTube. I am getting stuck on a problem, and even after going through all the Django documents (https://docs.djangoproject.com/en/3.2/howto/overriding-templates/) I just can't see where I am going wrong. I have tried pasting the file path for the base.html file directly, as well as other methods such as os.path.join(BASE_DIR, 'templates') to try find the right path. But I still get an error. Here is what I think all the code someone would need to understand the problem. Sorry if I have copied too much, but I am not sure what I actually need to show for someone to fully understand where I might have gone wrong. The overall project is call PyShop and I have a file called index.html which is located in PyShop\products\templates\index.html which is trying to call the base.html file by {% extends 'base.html' %}. The base.html file is located here PyShop\templates\base.html. When I run I get the below error. If I move the base.html file out from under the templates folder and just have it on it's own like this PyShop\base.html ie not in any subfolder then it works no problem. TemplateDoesNotExist at … -
Django importing CSV into model: matching query does not exist
I have the following Django project called Auditor, with 2 apps called main and backend. I am trying to upload csv content into a model, everything seems to be working fine until i try to upload the file, resulting in the following error: DoesNotExist at /upload/1 Csv_dv matching query does not exist. I created the model for CSV file, model for the CSV content and Form to contain the csv fields. Here is my Models.py: class Csv_dv(models.Model): file_name = models.FileField(upload_to='main') #The media folder will contain CSV file uploaded = models.DateTimeField(auto_now_add=True) # The uploaded time activated =models.BooleanField(default=False) # If file successfully uploaded to return true def __str__(self): return f"File id: {self.id}" class dv_model(models.Model): Defect_Area_dv = models.CharField(_('Defect Area dv'), max_length=200 ) Key_Driver_dv = models.CharField(_('Key Driver dv'), max_length=200) Sub_Key_Driver_dv = models.CharField(_('Sub Key Driver dv'), max_length=200 ) QS_Login_dv = models.CharField(_('QS Login dv'), max_length=200) QS_Name_dv = models.CharField(_('QS Name dv'), max_length=200) Status_dv = models.CharField(_('Status dv'), max_length=200) Correct_Associate_Action_dv = models.CharField(_('Correct Associate Action dv'), max_length=200) Correct_investigator_Action_dv = models.CharField(_('Correct investigator Action dv'), max_length=200) Action_Correctly_Captured_dv = models.CharField(_('Action Correctly Captured dv'), max_length=200) Audit_Outcome_dv = models.CharField(_('Audit Outcome dv'), max_length=200) Document_Name_dv = models.CharField(_('Document Name dv'), max_length=200) Document_Type_dv = models.CharField(_('Document Type dv'), max_length=200) Type_of_Audit_dv = models.CharField(_('Type of Audit dv'), max_length=200) If_Correctly_Captured_No_dv =models.CharField(_('If Correctly Captured … -
how to display the contents displayed in another html inside a div of the parent html file
The below code shows that when the anchor tag is clicked the content related to that specific title is retrieved and shown in another html page name doc1.html. The link that redirects it to next page in present in this file. judge_civil.html file <div class="container-middle"> <div id="limitations" class="tabcontent"> {% for data in law_data %} {% if data.law_type == 'civil' and data.law_category == 'limitations' %} <div class="tab"> <!--<button class="tablinks" onclick="openLawtype(event,'title')">{{data.title}} &nbsp<i class="fas fa-chevron-circle-right"></i></button>--> <a href="{% url 'doc1' data.pk %}" target="_blank">{{data.title}}</a ><br /><br /> </div> {% endif %} {% endfor %} </div> </div> Here when the link is clicked the content that is associated with {{data.title}} is opened and displayed in a new html file dynamically using the primary key that i have passed along with it. The code in doc1.html is below <p>{{ object.judgements|safe}}</p> But now I want to display this content that is being displayed in doc1.html in the judge_civil.html inside the below : <div class="container-right"></div> I assume that this can only be done with javascript. I don't know javascript at all so if you can provide me the code to this task it will be really helpfull. I am also providing the models and viwes and urls code if … -
how to access to through field in ManyToMany relation to convert to json django
i'm trying to change my object to json response but the database has some relations class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,related_name='rooms') takes_by = models.ManyToManyField('vistors.Vistor',through='BookingVisitor',related_name='vistors') class BookingVisitor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT,related_name='visitor_admin') visitor = models.ForeignKey('vistors.Vistor',on_delete=models.PROTECT,related_name='visitor_booking') booking = models.ForeignKey(Booking,on_delete=models.PROTECT,related_name='booking_bookingvisitors') reason = models.CharField(max_length=50) class Vistor(models.Model): full_name = models.CharField(max_length=150) city = models.ForeignKey(City,on_delete=models.CASCADE) gender = models.CharField(max_length=10,choices=genders,default=male) date = models.DateTimeField(auto_now_add=True) and my views.py def booking_detail(request,id): obj = get_object_or_404(Booking.objects.annotate(no_persons=Count('takes_by')),id=id) visitors = [] for i in obj.takes_by: print(i.full_name,i.city,i.visitor_booking.reason)#'RelatedManager' object has no attribute 'reason' visitors.append({ 'full_name':i.full_name, 'reason':i.visitor_booking.reason }) but it returns this error : 'RelatedManager' object has no attribute 'reason' i also tried this print(i.full_name,i.city,i.visitor_booking.get(visitor__id=i.id,booking_bookingvisitors__id=i.vistors.id)) it returns this error : 'ManyRelatedManager' object has no attribute 'id' thank you for helping .. -
Weasyprint not Showing images after deployment of Django Project
I have recently deploy a Django project, weasyprint was not loading properly it was returning several errors, now that they are fixed I am facing an image issue which is not showing on the PDF: The image is parked in: static/img/report-cover.jpg I also added it to be dynamic with the following models: class Info(models.Model): logo = models.ImageField(null=True, blank=True) Here is the settings.py to have a full picture of my trials: STATIC_URL = '/static/' #if DEBUG: # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] #else: #STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static' )] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here is the pdf.html trial 1: {% load static %} <link rel="stylesheet" href="{% static '/css/report.css' %}" /> <style> @page :first { background: url('/static/img/report-cover.jpg') no-repeat center;} </style> Trial 2: <style> @page :first { background: url('{{ info.logo.path }}') no-repeat center;} </style> Trial 3: <style> @page :first { background: url('{{ info.logo.url}}') no-repeat center;} </style> Here is the views.py def admin_order_pdf(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/pdf.html', {'info': info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(info.id) # response['Content-Disposition'] = 'attachment; filename="order_{}.pdf"'.format(info.id) weasyprint.HTML(string=html,base_url=request.build_absolute_uri()).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '/css/report.css')], presentational_hints=True) return response From this answer I have changed the following but still didn't work: weasyprint.HTML(string=html,base_url=request.build_absolute_uri("/")).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '/css/report.css')], presentational_hints=True) I … -
Django annotate field with queryset of objects
Supponse I have two models: ModelA and ModelB How can I annotate a queryset of ModelB with objects from ModelA? queryset = ModelB.objects.filter(...).annotate(models_a=Subquery(ModelA.objects.filter(...))) In order to have queryset.models_aas a Queryset of objects ModelA. Thanks you all! -
How can we paginate the older messages in Django channels?
I have an interface with Flutter that requests connection to a websocket using Django channels. The websocket is frequently sending real time data. When the connection is made to the websocket, all the older messages are currently sent at once. I want to paginate the older messages. What is the best way or best practice to make the pagination for the interface. The current consumer code is like this: def fetch_messages(self, data): messages = get_last_10_messages(data['chatId']) content = { 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): user_contact = get_user_contact(data['from']) message = Message.objects.create( contact=user_contact, content=data['message']) current_chat = get_current_chat(data['chatId']) current_chat.messages.add(message) current_chat.save() content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'id': message.id, 'author': message.contact.user.username, 'content': message.content, 'timestamp': str(message.timestamp) } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message } def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) self.commands[data['command']](self, data) def send_chat_message(self, message): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) def send_message(self, message): self.send(text_data=json.dumps(message)) def chat_message(self, event): message = event['message'] self.send(text_data=json.dumps(message)) -
unable to show success page after payment completion in django
i am using razorpay payment gateway for my ecommerce site currently using test mode all the thing work fine payment can be done but some data annot be saved like reazorpay order id its signature in my model and handler view does not work after payment success here is my views for checkout before payment class Checkout_Pre(View): def post (self, request,): user = request.user address = Address.objects.filter(default=True, user=request.user) cart = request.session.get('cart') items = Item.get_items_by_id(list(cart.keys())) prefer = request.POST.get('payment') total_price = request.POST.get('paying_price') total_item_price = json.loads(total_price) order = Order.objects.create( user=user, total_price=total_item_price, address=address.first(), method = prefer, ) for item in items: item_order = OrderItem.objects.create( order=order, item=item, size=cart.get(str(item.id)), price=item.price, ) order_currency = 'INR' callback_url = 'http://'+ str(get_current_site(request))+"/handlerequest/" print(callback_url) notes = {'order-type': "Basic order from the coolbuy website", 'key':'value'} razorpay_order = razorpay_client.order.create(dict(amount=total_item_price*100, currency=order_currency, notes = notes, receipt=order.order_id, payment_capture='0')) **print(razorpay_order['id'])** order.razorpay_order_id = razorpay_order['id'] order.save() request.session['cart'] = {} return render(request, 'payment/razorpaypaymentsummary.html', {'order':order, 'order_id': razorpay_order['id'], 'orderId':order.order_id, 'final_price':total_item_price, 'razorpay_merchant_id':settings.razorpay_id, 'callback_url':callback_url,}) as you can see i am printing razorpay_order_id it shows in terminal but when i tried to save in model it got blank and does not save my handler after payment completition @csrf_exempt def handlerequest(request): if request.method == "POST": try: payment_id = request.POST.get('razorpay_payment_id', '') order_id = request.POST.get('razorpay_order_id','') signature = request.POST.get('razorpay_signature','') … -
How can logged in users update or edit their own created product?
A user can create a product by logging in first. I want them to update their own product if they want to. In a way they cannot access others or change others product (I think I have to use conditionals). I'm sure my views.py is wrong because I am only getting blank details of the product. When I try to go to update them nothing is saving in the admin. views.py @login_required(login_url='product:login-user') def product_update_view(request): user = request.user form = ProductForm(instance=user) print(user) if request.method == 'POST': form = ProductForm(request.POST or None, request.FILES, instance=user) if form.is_valid(): form.save() context = { 'form': form } return render(request, "product/product_create.html", context) urls.py path('update/', product_update_view, name='product-update'), models.py class Product(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) prodname = models.CharField(max_length=255, null=True) description = models.CharField(max_length=255, null=True) price = models.FloatField(null=True) image = models.ImageField(null=True, upload_to='images') def __str__(self): return self.prodname + ' | ' + str(self.creator) def get_absolute_url(self): return reverse("product:product-detail", kwargs={'pk': self.id}) -
Manually add User / Socialacount with Django-Allauth
I'm using django-allauth, strictly using google account for user sign in. However, I want it so that only manually added user can sign in. For example, A certain user with email test@google.com wants to be able to login. Now what I must do is manually add this user's email using the admin app. After that, the user would be able to login using google account. I tried disabling signup by returning false for the function 'is_open_for_signup' from DefaultAccountAdapter and then in the admin panel I added the user with the email provided and added the socialaccount. But when I try to login, it's recognized as signup instead. I think it has something to do with the uid or extra data in the socialaccount model. I tried signing up using google account and then deleted the uid and extra data. After that, I disabled signup and tried to login again but it says signup is closed/blocked. I don't know what to do next. -
how to display contents dynamically when the button is clicked
The below code shows that when the anchor tag is clicked the content related to that specific title is retrieved and shown in another html page name doc1.html. The link that redirects it to next page in present in this file. judge_civil.html file <div class="container-middle"> <div id="limitations" class="tabcontent"> {% for data in law_data %} {% if data.law_type == 'civil' and data.law_category == 'limitations' %} <div class="tab"> <!--<button class="tablinks" onclick="openLawtype(event,'title')">{{data.title}} &nbsp<i class="fas fa-chevron-circle-right"></i></button>--> <a href="{% url 'doc1' data.pk %}" target="_blank">{{data.title}}</a><br/><br/> </div> {% endif %} {% endfor %} </div> </div> Here when the link is clicked the content that is associated with {{data.title}} is opened and displayed in a new html file dynamically using the primary key that i have passed along with it. The code in doc1.html is below <p>{{ object.judgements|safe}}</p> But now I want to display this content that is being displayed in doc1.html in the judge_civil.html inside the below : <div class="container-right"> </div> I assume that this can only be done with javascript. I don't know javascript at all so if you can provide me the code to this task it will be really helpfull. I am also providing the models and viwes and urls code if needed: models.py … -
Is it safe just to remove the installed app and then delete the folder in Django?
I am using Django and I have an app inside called "stuff". I decided I didn't need it anymore so I removed all usage of it from all my files, I removed it from settings.py under installed apps, and then I just deleted its entire folder. Is that okay to do? So far everything seems to still be running fine and it no longer shows up in my admin panel which is what I want. I was reading some other posts on how to remove a Django App and they were doing a lot of extra things like this: https://stackoverflow.com/questions/3329773/django-how-to-completely-uninstall-a-django-app#:~:text=To%20remove%20the%20app%20from,your%20PYTHONPATH%20where%20it%20resides. Should I be worried something bad will happen down the road? I can makemigrations and changes and do everything perfectly fine currently. -
Django multiple user type implemenation
I am trying implementation where, one user type(end user) who will have email/phone number + password authentication where as the other type of user(admin/staff) will have username + password authentication. Struggling with many resources available on the internet but still has not been able to get through it. -
why django models error keeps raising error?
I moved these to models to chat app class Message(models.Model): sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="فرستنده") receiver = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="گیرنده", related_name="reciver") text = models.CharField("متن", max_length=500) date_and_time = models.DateTimeField(auto_now_add=True) subject=models.CharField(max_length=200,verbose_name="موضوع") notification=models.OneToOneField(Notification,on_delete=models.DO_NOTHING,related_name="message",null=True) class Meta: verbose_name = "پیام" verbose_name_plural = "پیام ها" class Response(Message): darkhast_sabt_sherekat=models.ForeignKey(SabteSherkat,on_delete=models.CASCADE,related_name="responses") After that it raise an error saying local id of Response crashed with message i made everything undo and this error keeps coming up * Operations to perform: Apply all migrations: accounts, admin, auth, consultation, contenttypes, sessions, utilities, web Running migrations: Applying web.0007_auto_20210815_0831...Traceback (most recent call last): File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near ")": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate …