Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to restrict the access for staff users to view and edit only their inputted data in django admin
I need to restrict the access in the admin page like if a staff user is logging in the admin they need to see only their entry data's and can able to add or delete their data in the admin panel. As I tried the below code in the admin.py still I could able to view and delete everyone's data. Admin.py admin.site.site_header = "Inhouse Project Management" admin.site.site_title = "TimeSheet Admin Portal" admin.site.index_title = "TimeSheet Administration" TokenAdmin.raw_id_fields = ['user'] class MyModelAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) #Admin SuperUser @admin.register(User) class UserAdmin(ImportExportModelAdmin): list_display = ('id','employee_name','email','billable_and_non_billable','designation') search_fields = ['employee_name'] pass @admin.register(Project) class ProjectAdmin(ImportExportModelAdmin): list_display = ('id','project_name','client','start_date','end_date') search_fields = ['project_name'] pass Urls.py urlpatterns = [ path('', TemplateView.as_view(template_name="social_app/index.html")), #social_app/index.html path('admin/', admin.site.urls), #admin api path('api/',include(router.urls)), #api path('accounts/', include('allauth.urls')), #allauth re_path('rest-auth/', include('rest_auth.urls')), #rest_auth path('api-auth/', include('rest_framework.urls')), re_path('rest-auth/registration/', include('rest_auth.registration.urls')), #path('api-token-auth/', views.obtain_auth_token), #path('api-token-auth/',CustomAuthToken.as_view()), #path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('auth/login/',TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('conso/',view), path('chaining/', include('smart_selects.urls')), ] models.py class User(models.Model): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.CharField(max_length=50) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) class Meta: db_table ='User' def __str__(self): return self.employee_name serializers.py class … -
Unable to login Django admin with valid credential, also user is erratically showing logged in and logged out on refresh in DRF view
My problem closely relates to Unable log in to the django admin page with a valid username and password one more thing I noticed while trying to login into DRF login panel that after login, it is not showing logged in user in right side.... but on refreshing it is showing then again refreshing it is not showing... usually initially user is getting logged in and logged out automatically on alternate refresh and this behavior becomes erratic sometimes and user logged in is not showing on alternate refresh. You can try this on: Admin Login page: https://www.markonmap.com/admin DRF Login page: https://markonmap.com/api-auth/login/?next=/map/mappoint/1 username: leader password: abcd.1234 I have tried everything suggested in the answers of aforementioned following question Unable log in to the django admin page with a valid username and password I have cleaned all my browser history, cookies and cache... tried login through incognito I have flushed my session actually all tables of my database. but problem persists. Config for authentication backend AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] I am using Django 3.2 -
django-tenants: Newly created app’s migrations are reflecting as expected in public schema of the database, but not in tenant-specific schemas
We had authored two applications since the beginning the project* The same has been part of the multi-tenancy architecture in a single database, semi-isolated fashion using a multi-schema approach. We have built a third application that we also want to integrate into django-tenant schemas that’s failing to reflect their tables in the database, in tenant-generated schemas. However, the migrations for the newly created app is successfully migrating and creating tables in the public schema. The same is failing to reflect in tenant-generated schemas. This is happening for any new app that is created through Django. We are using PostGIS as original backend and django-tenants as database engine. Current Django version=3.2.12 Current PostgreSQL version=12 Current django-tenants=3.4.1 -
django makdmigrations raise error after remove a function in models.py
I define a model named Foo which has a FileField named bar, and I define a function baz which is callable used for bar's upload_to arguement in same file. When I removed the bar field and baz funcion and perform makemigrations operations, it raise error "AttributeError: module 'models' has no attribute 'baz'". How can I solve the bug? below is snippet demo import os import time from django.db import models def baz(instance, filename): ext = filename.split('.')[-1] fn = time.strftime('%Y%m%d%H%M%S') com = fn + '.' + ext return os.path.join('', com) class Foo(models.Model): name = models.CharField(max_length=255) bar = models.FileField(upload_to=baz) # wants to remove -
Getting Time data to Jinja2 without leading zero
I'm using PostgreSQL with Django to save a time data to DB with html time input like this <input type="time" name="houmon_time" value="{{ kokyaku.houmon_time.0 }}"> which works fine and data are saved in DB like this 09:00:00, but when I'm trying to GET the data to {{ kokyaku.houmon_time.0 }} data are parsed like <input type="time" name="houmon_time" value="9:00"> and I'm getting an error in browser console because of that leading zero The specified value "9:00" does not conform to the required format. The format is "HH:mm", "HH:mm:ss" or "HH:mm:ss.SSS" where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. I'm getting data from DB like this def get_details(self): if self.pk is not None and self.connection is not None: kokyaku_details = pd.read_sql( sql=f"SELECT * FROM cs_houmon_ WHERE code='{self.pk}'", con=self.connection ) kokyaku_details = kokyaku_details.to_dict('list') return kokyaku_details # and this # ... snipped kokyaku_list = list(kokyaku_instance.get_new()) if len(kokyaku_list) == 1: print(kokyaku_list) return render(request, self.template, self.context) column_names = [x.replace("\n", "") for x in kokyaku_list[0].split(",")] kokyaku_list = [x.split("\n") for x in kokyaku_list[1:]] new_kokyaku = [] for small_list in kokyaku_list: for val in small_list: if len(val) > 0: val = val.split(",") try: val[5] = val[5].split(".")[0] val[5] = datetime.datetime.strptime(val[5], "%Y-%m-%d %H:%M:%S") if val[5].year == 1999: … -
Popup With JavaScript not working with Django template
The follow code is not running in a Django project. Is there any limitation when using popups in django? In this case, the white window does not open with the text. Why doesn't the Django template open the div with the text? Apparently the css and javascript are being called and the screen in the background darkens, but the white window with the text does not appear. const openModalButtons = document.querySelectorAll('[data-modal-target]') const closeModalButtons = document.querySelectorAll('[data-close-button]') const overlay = document.getElementById('overlay') openModalButtons.forEach(button => { button.addEventListener('click', () => { const modal = document.querySelector(button.dataset.modalTarget) openModal(modal) }) }) overlay.addEventListener('click', () => { const modals = document.querySelectorAll('.modal.active') modals.forEach(modal => { closeModal(modal) }) }) closeModalButtons.forEach(button => { button.addEventListener('click', () => { const modal = button.closest('.modal') closeModal(modal) }) }) function openModal(modal) { if (modal == null) return modal.classList.add('active') overlay.classList.add('active') } function closeModal(modal) { if (modal == null) return modal.classList.remove('active') overlay.classList.remove('active') } *, *::after, *::before { box-sizing: border-box; } .modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0); transition: 200ms ease-in-out; border: 1px solid black; border-radius: 10px; z-index: 10; background-color: white; width: 500px; max-width: 80%; } .modal.active { transform: translate(-50%, -50%) scale(1); } .modal-header { padding: 10px 15px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px … -
How to add multiple fields' reference to "unique_together" error message
I have a model with multiple fields being checked for uniqueness: class AudQuestionList(BaseTimeStampModel): aud_ques_list_id = models.AutoField(primary_key=True,... aud_ques_list_num = models.CharField(max_length=26,... aud_ques_list_doc_type = models.ForeignKey(DocType,... short_text = models.CharField(max_length=55,... aud_scope_standards = models.ForeignKey(ScopeStandard, ... aud_freqency = models.ForeignKey(AuditFrequency, ... aud_process = models.ForeignKey(AuditProcesses, ... unique_together = [['aud_scope_standards', 'aud_freqency', 'aud_process',],] My model form is as described below: class CreateAudQuestionListForm(forms.ModelForm): class Meta: model = AudQuestionList fields = ('aud_ques_list_doc_type', 'aud_scope_standards', 'aud_freqency', 'aud_process', 'short_text', ... def validate_unique(self): try: self.instance.validate_unique() except ValidationError: self._update_errors({'aud_scope_standards': _('Record exists for the combination of key values.')}) The scenario works perfectly well, only that the field names (labels) itself are missing from the message. Is there a way to add the field names to the message above, say something like: Record exists for the combination of key fields + %(field_labels)s. -
Docker-Compose Init Postgres Failing
I've been attempting to make a docker-compose file work, and so far it's been closer and closer, but not quite there. Maybe asking the questions will be useful to someone else in the future. Anyway, the previous thread was here: Docker-Compose Postgresql Init Entrypoint From which I learned, between runs a docker-compose file should have docker compose volumes --down and if the POSTGRES_DATABASE isn't specified, then the POSTGRES_NAME will replicate to the POSTGRES_DATABASE. another suggestion from Discord has been to rewrite some of the volume signature to include the file path to init.sql as in docker-entrypoint-initdb.d/init.sql So if I docker-compose down --volume and then sudo docker-compose build && docker-compose up with version: "3.9" services: db: restart: always image: postgres volumes: # - ./data/db:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.db environment: - POSTGRES_NAME=dev-postgres - POSTGRES_USER=pixel - POSTGRES_DATABASE=lightchan - POSTGRES_PASSWORD=stardust web: build: . restart: always command: sh -c "./waitfor.sh db:5432 -- python3 manage.py runserver" volumes: - .:/code ports: - "8001:8001" environment: - POSTGRES_NAME=dev-postgres - POSTGRES_USER=pixel - POSTGRES_DATABASE=lightchan - POSTGRES_PASSWORD=stardust depends_on: - db Then the following is output: Attaching to lightchan-db-1, lightchan-web-1 lightchan-db-1 | The files belonging to this database system will be owned by user "postgres". lightchan-db-1 | This user must also own the server process. … -
using .all() gives me everything inside the Primary Model How can i change it to gives what i needed
I have 2 models Album and Primary when i go to the Albums Templates and clicking the viewAlbum templates it's shows me every Students from every Album I have created, instead of showing the only students inside the album i have choosing during creating a new student. the create album template: <div class="row"> <div class="col-md-3"> <a href="{% url 'post_create' %}">Create Album</a> </div> <!--Albums--> {% for my_album in albums %} <div class="col-md-9"> <div class="card" style="width: 18rem;"> <img src="{{ my_album.image.url }}" alt="" class="card-img-top"> <div class="card-body"> <p>{{ my_album.name }}</p> <br> <a href="{% url 'view-Album' my_album.pk %}">viewAlbum</a> </div> </div> </div> {% endfor %} </div> </div> the viewAlbum view: def viewAlbum(request, pk): primaries = Primary.objects.all() post = get_object_or_404(Album, id=pk) my_album = Album.objects.get(id=pk) return render(request, 'viewAlbum.html', {'primaries': primaries, 'post':post, 'my_album':my_album}) the students templates: <div class="container"> <div class="row"> <div class="col"> <a href="{% url 'students' %}" class="btn btn-primary">Create Students</a> </div> </div> </div> <br> <div class="container"> <div class="row justify-content-center"> {% for prima in primaries %} <div class="col"> <div class="card my-2" style="width: 18rem;"> <img src="{{ prima.profilePicture.url }}" alt="" class="card-img-top"> <div class="card-body"> <p>{{ prima.firstName }}</p> <br> <a href="{% url 'view-Student' prima.pk %}">view Students</a> </div> </div> </div> </div> {% endfor %} </div> the models: class Album(models.Model): image = models.ImageField(null=False, blank=False) name = … -
Django local server not starting after hard reboot
I am a newbie developing a Django site in a pipenv virtual environment. The server has been starting and working with no problems. After my computer froze and I restarted with a hard reboot, I can't get the Django server to work. Here is the error I see after running, python manage.py runserver ((site1) ) userone@theusers-MBP site1 % python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? The above exception was the direct cause of the following exception: Traceback (most recent call … -
Cannot Access Django Object After Creating it
I'm having difficulty running a function with the following code. It works when I run these lines individually in shell, but in the function 500s and I cannot access the object I just created. order = Order.objects.create( user=user, date_created=datetime.datetime.now(), ) print(order.id) #works fine and displays the new id print(Order.objects.get(id=order.id)) # 500s and cannot find the object -
Django Template Multi Image Carousel
I'm trying to create a Carousel that shows multiple pictures of a single cat for a cattery project I'm doing. I'm trying to figure out the right template to make this work. My Models class Cat(models.Model): name = models.CharField(max_length=32, null=True) available = models.BooleanField() main_image = models.ImageField(upload_to="images/") age = models.CharField(max_length=64, null=True) mix = models.CharField(max_length=128, null=True) dob = models.CharField(max_length=16) sex = models.CharField(max_length=16) description = models.TextField(max_length=256, null=True) def __str__(self): return f"{self.name} : {self.sex} {self.age} || Available : {self.available}" class Images(models.Model): name = models.CharField(max_length=64, null=True) image = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): return self.name My View def available(request): context = {} return render(request, "cattery/available.html", {'available_kittens': Cat.objects.exclude(available=False).all()}) My HTML {% for kitten in available_kittens %} <div class="flexbox-item"> <img class="thumbnail" src="{{ kitten.images.url }}"> <h2> {{ kitten.name }} </h2> <hr> <h4> {{ kitten.sex }} </h4> <h6> {{ kitten.dob }} </h6> <p> {{ kitten.description}} </p> </div> {% endfor %} How can I call the images related to each kitten with a django Template? I know I could just include multiple image fields, but I've seen people suggest this method of creating a secondary class. -
Django object update using htmx and SingleObjectMixin
I'm using htmx for the first time. I have a table where each cell is a grade object. Previous to htmx I made each cell a link to an UpdateView for the object. I am now trying to have the user modify the the object's score field directly in the table using htmx. I'm sure I'm doing several things wrong. My page loads as expected and the table is displayed as expected. when I type in a cell, I get an error Forbidden 403. CSRF Verification Failed. The purpose of this post/question is to figure out how to get past this 403 error. Having said that, if it turns out that I'm going down the completely wrong path with using a SingleObjectMixin, please let me know. View class GradeChange(SingleObjectMixin, View): """ view to handle htmx grade change""" model = Grade def post(self, request, *args, **kwargs): grade = self.get_object() assessment = Assessment.objects.get(grade=grade.pk) print(assessment) classroom = Classroom.objects.get(classroom=grade.cblock) print(classroom) if grade.score == "EXT" or grade.score=="APP" or grade.score=="DEV" or grade.score=="BEG": grade.save() return HttpResponse("S") else: return HttpResponse("") template <table class="table table-bordered table-sm"> <thead> <tr> <th class="col-3" scope="col">Students</th> {% for obj in objective_list %} <th class="col-2" scope="col">{{ obj.objective_name }}</th> {% endfor %} <th scope="col">Comments</th> </tr> </thead> … -
How to get object from detailview in .views? Django
I've created a function that adds the user to an event, that is working fine but, i'm having problems with the one that removes the users from the event, I didn`t figure out how to get the attendant so that the owner can remove it. By now, I have this: views.py (Function that adds the user to the event) @login_required def request_event(request, pk): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) Attending.objects.create(post=post, attendant=request.user) messages.success(request, f'Request sent!') return redirect(previous) except post.DoesNotExist: return redirect('/') (Function that removes users from the event, handled by the event owner) @login_required def remove_attendant(request, pk, attendance_id): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) attendant = Attending.objects.get(id=attendance_id) Attending.objects.filter(post=post, attendant=attendant).delete() messages.success(request, f'User removed!') return redirect(previous) except post.DoesNotExist: return redirect('/') Urls.py path('post/(?P<pk>[0-9]+)/remove_attendant/(?P<attendance_id>[0-9]+)$', views.remove_attendant, name='remove-attendant'), Any help or comment will be very welcome! thank you!!! -
How test the presence of CSRF in an APIView (DRF)?
I have an API, with JSON as content-type, built with Django Rest Framework. There is an endpoint which permit login the users, for that I am using simple-jwt package, and how the view has permission_classes = [AllowAny] and works through POST method to make the login, so I added the CSRF token to this view: @method_decorator(csrf_protect, name='post') class TokenCookieObtainPairView(TokenObtainPairView): ... When the header and cookie that have the CSRF doesn't match, a template of django (views.csrf.csrf_failure) return a 403 status, but I overrided that (method finalize_response()) to return a message to the consumer. if response.status_code == status.HTTP_403_FORBIDDEN: serializer = MessageSerializer({'message': self.MESSAGE}) new_response = Response(serializer.data, status=status.HTTP_403_FORBIDDEN) return super().finalize_response(request, new_response, *args, **kwargs) I created a test for that view. I am using pytest and the DRF's APIClient. from pytest import mark, fixture @fixture def api_client_csrf() -> APIClient: return APIClient(ensure_csrf_checks=True) @mark.django_db def test_login_view_csrf(api_client_csrf): """Verify that the 'login' view need the CSRF_token.""" path = reverse_lazy('login') credentials = { 'email': 'xxx@yyyy.com', 'password': '******' } response = api_client_csrf.post(path, data=credentials) print(response.data) assert response.status_code == 403 The test failed because the CSRF token is not required and the credentials are invalid, hence pytest return: assert response.status_code == 403 E assert 401 == 403 E +401 E -403 The … -
Fail to access my Model fields in the views using /<int:pk>/ in the urls
I have a model called Primary and I want to access the fields of the models inside my viewStudent template, because i have more fields in the models. the model: class Primary(models.Model): profilePicture = models.ImageField(blank=False, null=False) firstName = models.CharField(max_length=25, blank=False, null=False) sureName = models.CharField(max_length=25, blank=False, null=False) lastName = models.CharField(max_length=25, blank=False, null=False) address = models.CharField(max_length=50, blank=False, null=False) classOf = models.CharField(max_length=20, blank=False, null=False) yearOfGraduations = models.CharField(max_length=20, blank=False, null=False) hobbies = models.TextField(blank=False, null=False) dateOfBirth = models.CharField(max_length=20) year = models.ForeignKey(Album, on_delete=models.CASCADE) when i type this inside my: viewAlbum template it's throws me an error like this: NoReverseMatch at /viewAlbum Reverse for 'view-Student' with arguments '('',)' not found. 1 pattern(s) tried: ['view/(?P[0-9]+)/\Z'] <a href="{% url 'view-Student' primaries.id %}">view Students</a> the urls.py path('viewAlbum', views.viewAlbum, name='view-Album'), path('view/<int:pk>/', views.viewStudent, name='view-Student'), the views: def viewAlbum(request): primaries = Primary.objects.all() return render(request, 'viewAlbum.html', {'primaries': primaries}) def viewStudent(request, pk): post = get_object_or_404(Primary, id=pk) primaries = Primary.objects.get(id=pk) return render(request, 'viewStudent.html', {'post': post, 'primaries': primaries}) inside my viewAlbum template i have tried this: <a href="{% url 'view-Student' primaries.pk %}">view Students</a> but it's not working how can I solves this problem? -
Widgets and static files
I'm trying to use a custom widget for plus and minus buttons and I struggle to link the widget to its css and js files. So in my app I got this form : class MyForm(forms.Form): degree = forms.DecimalField(label="Degree", max_digits=3, decimal_places=1, required=True, widget=PlusMinusNumberInput()) Calling this widget : class PlusMinusNumberInput(Widget): template_name = 'widgets/plus-minus-input.html' class Media: css = { 'all': ('css/plus-minus-input.css',) } js = ('js/plus-minus-input.js',) I got a "static" directory at the root, with my files in css and js folders. The static parts of my settings are as follow : STATIC_URL = '/static/' STATICFILES_DIRS = [Path.joinpath(BASE_DIR, 'static'),] STATIC_ROOT = Path.joinpath(BASE_DIR, 'staticfiles') At the end the html file render well but not the js and css. Do you know why ? -
How to drop tables using Django 2.2 migrations?
Im trying to drop unused tables from the database with a single migration. The models and the references was already removed from the code, but I can't get the migration to work. When I run the makemigration command I get something like this: class Migration(migrations.Migration) dependencies = [ ('hiring', '0040_last_migration'), ] operations = [ migrations.DeleteModel( name='Position', ), migrations.DeleteModel( name='ReviewProcess', ), migrations.DeleteModel( name='ReviewProcessType', ), ] But if i run this migration it makes nothing, also if i run the sqlmigrate command it shows only commented lines in the sql response: BEGIN; -- -- Delete model Position -- -- -- Delete model ReviewProcess -- -- -- Delete model ReviewProcessType -- COMMIT; -
How to make payments with stripe in a django and react app?
So, I am going to build an e-commerce site where the price will depend on how many days the person stays in a housing boat. I am planning to use material UI's date and time picker. So I want to be able to: 1) get the difference of the check in and check out dates in the front-end 2) then compute the total cost in the frontend 3) then make stripe (django backend) know about this total cost and charge accordingly I need help with (3). How do I send the price to the backend and have stripe know about this price? for example, here is some code: Django Backend: import django.conf import settings from rest_framework.views import APIView import stripe from django.shortcuts import redirect # This is your test secret API key. stripe.api_key = settings.STRIPE_SECRET_KEY class StripeCheckOutView(APIView): def post(self, request): try: checkout_session = stripe.checkout.Session.create( line_items=[ { # Provide the exact Price ID of the product you want to sell 'price': '{{PRICE_ID}}', 'quantity': 1, }, ], mode='payment', success_url=YOUR_DOMAIN + '?success=true', cancel_url=YOUR_DOMAIN + '?canceled=true', ) return redirect(checkout_session.url) except: return React Frontend: import "./App.css"; const ProductDisplay = () => ( <section> <div className="product"> <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> <div className="description"> … -
HELPS - I just ran "git reset --hard HEAD~50" not knowing it would revert all my files
I was trying to solve a problem I was having with Django and used the command "git reset --hard HEAD~50" not knowing it would revert all my files. I just lost a month of code. I'm looking for a fix right now but I wanted to post here instead of touching anything right now. It might be a simple fix but please help. -
Elastic Beanstalk Django project working but not listed in AWS console for Elastic Beanstalk
I followed this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html The application is deployed perfectly. On the AWS console for Elastic Beanstalk however, nothing is listed under environments or applications. What could be causing the problem? -
When I try to send mail using Django EmailMultiAlternatives I get an error [closed]
Note: it's working in local host but not in after deploy. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_HOST_USER='mymail@gmail.com' EMAIL_HOST_PASSWORD='mypassword' EMAIL_USE_TLS=True EMAIL_USE_SSL=False Error code: Exception Type: SMTPAuthenticationError at /homecontact Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 9_jo-fg-EeQ7zjo3vQOvaG6o9TtP_RLjSe1tciyNAxxgmWFHjN7rxYoZRUEAaofnmz2MG\n5.7.14 boEeJELbxm-aTrY4S4T2mbhUmSeSGbT2JNPVLXkfzYGpl5XO54L0gn1U8JGxEFuk>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 r13-20020ac85c8d000000b002de72dbc987sm9921275qta.21 - gsmtp') -
Django add to watchlist, listings not showing
I am trying to work on a project and one of the features is that users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist. So far, I am redirected when 'add to watchlist' is clicked but it does not bring up the button of 'remove from watchlist' and also when it redirects me to the watchlist page (where i should view the users entire watchlist), it shows me 'No watchlist found.'. URLS.PY path("add_watchlist/<int:listing_id>/", views.add_watchlist, name="add_watchlist"), path("watchlist", views.watchlist, name="watchlist"), MODELS.PY class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ManyToManyField(Auction) def __str__(self): return f"{self.user}'s watchlist" LAYOUT.HTML <li class="nav-item"> <a class="nav-link" href="{% url 'all_category' %}?category={{ category.name}}">Category</a> <li class="nav-item"> <a class="nav-link" href="{% url 'create_listing' %}">Sell</a> </li> <li class="nav-item"> {% if user.is_authenticated %} <a class="nav-link" href="{% url 'watchlist' %}">Watchlist</a> {% endif %} </li> </ul> VIEWS.PY @login_required def add_watchlist(request, listing_id): items = Auction.objects.get(pk=listing_id) watched = Watchlist.objects.filter(user=request.user, item=listing_id) if watched.exists(): watched.delete() messages.add_message(request, messages.ERROR, "Successfully deleted from your watchlist") return HttpResponseRedirect(reverse("watchlist")) else: watched, created = Watchlist.objects.get_or_create(user=request.user) watched.item.add(items) messages.add_message(request, messages.SUCCESS, "Successfully added to your watchlist") return redirect('index') @login_required def watchlist(request): watchlists = Watchlist.objects.all() context = {'watchlists':watchlists} return render(request, 'auctions/watchlist.html', context) … -
Django project cannot be accessed using IPV6 address
I am running my Django project on a ubuntu server. I have changed the allowed host in settings.py ALLOWED_HOSTS = ['my_IPV4', 'my_IPV6', 'localhost'] I allowed access to port 8000 by sudo ufw allow 8000. I run the server by python manage.py runserver 0.0.0.0:8000 however I can only access the IPV4 address but the IPV6 address on port 8000 is not reachable. My IPV6 address is active but port 8000 seems not working. Did I miss something on configuring IPV6? -
Using CreateView with 2 Models at the same time
I am learning django. I am attempting to create a website that logs a user's workout. The user will be able to make premade workouts. For each workout routine, there will be a workout name and it will consist of different exercises and the number of sets per exercise. In order to achieve this, I have created a custom through model so I can associate a number of sets to each exercise for that premade workout routine. The trouble I am having is that in order to create a workout routine I need to use the WorkoutRoutine model in order to create a WorkoutRoutine object. Then I also need to use SetAmount in order to assign an exercise associated with a number of sets to the WorkoutRoutine. Here is my models.py: from django.db import models from django.contrib.auth import get_user_model from django.core.validators import MaxValueValidator, MinValueValidator class WorkoutRoutine(models.Model): title = models.CharField(max_length=25) owner = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) exercise = models.ManyToManyField( 'Exercise', through='SetAmount', related_name='workoutRoutines' ) def __str__(self): return self.title class Exercise(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class SetAmount(models.Model): workout_routine = models.ForeignKey( 'WorkoutRoutine', related_name='set_amounts', on_delete=models.CASCADE, null=True ) exercise = models.ForeignKey( 'Exercise', related_name='set_amounts', on_delete=models.SET_NULL, null=True, blank=True ) set_amount = models.IntegerField( default=0, validators=[ MaxValueValidator(100), …