Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validate several fields together in django admin
Django 3.1.5 form class GoogleAnalyticsCounterForm(forms.ModelForm): def clean(self): pass # Break return self.cleaned_data class Meta: model = GoogleAnalytics exclude = [] Registration for admin site class GoogleAnalyticsAdmin(admin.ModelAdmin): form = GoogleAnalyticsCounterForm admin.site.register(GoogleAnalytics, GoogleAnalyticsAdmin) Problem I want to validate the several form fields together. But the interpreter doesn't stop at the breakpoint in the clean method. Could you tell my why? -
Testing urls django
I have a flatpage in my website. I created it by writing this: urlpatterns = [path('admin/', admin.site.urls),path('facts/', include('django.contrib.flatpages.urls')),] After that in admin page I created a page about-me, so the whole url for that page is ‘localhost/facts/about-me/’ I tried to write test for this page: class StaticURLTests(TestCase): def setUp(self): self.guest_client = Client() def test_about_author(self): response = self.guest_client.get('/facts/about-me/') self.assertEqual(response.status_code, 200) But I get the following error: self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 FAILED (failures=1) Destroying test database for alias ‘default’… Can’t figure out why. Maybe smb was facing the same problem. I thought that the error was because of the flatpage but, the same error occured when I tried to test url of the Task model urlpatterns = [path('task/<slug:slug>/',views.task, name='task'),] Test: @classmethod def setUpClass(cls): super().setUpClass() Task = Task.objects.create( title='Title', slug=' test-slug', description='Desc', ) def setUp(self): self.guest_client = Client() user = get_user_model() self.user = user.objects.create_user(username='Bob') def test_task_url_exists_at_desired_location_authorized(self): response = self.guest_client.get('/task/test-slug/') self.assertEqual(response.status_code, 200) I tried to change response = self.guest_client.get('/task/test-slug/') to response = self.guest_client.get(reverse('/task/')) but nothing seems to work. -
Display only those objects on django admin based on the user profile which is related to user that has logged in currenty
I want to have an admin where any operator who logs in the admin dashboard can only view their package objects and not see/change package objects added by other operators (from user). My models: class Package(models.Model): operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE) destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) city = models.CharField(max_length=255) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) user_type = models.CharField(max_length=1, choices=USER_TYPES, default='g') first_name = models.CharField(max_length=255, default="") My package/admin.py: class PackageAdmin(ModelAdmin): icon_name = 'explore' autocomplete_fields = ['destination'] list_display = ('image_display','package_name', 'featured', 'price', 'discounted_price', 'savings', 'fix_departure', 'rating', 'date_created',) image_display = AdminThumbnail(image_field='thumbnail') image_display.short_description = 'Image' readonly_fields = ['image_display'] def get_queryset(self, request): abc = super(PackageAdmin, self).get_queryset(request) if request.user.is_superuser: return abc else: operator = request.user.id return abc.filter(operator=operator) I have overridden the get_queryset(self, request) function but it is not working. -
I am unable to Post Total HitCount Or Views from anonymous user to related Post using django web framework
I am doing a online streaming site as someone click on any post to watch then this should add a view tracking their Ip address simply and I m not getting the results Please look into the code and help my identifying the problem or if there is any better way to do that then please mention too. models.py there I created and Ip model and also added a views variable for the main Post model class IpModel(models.Model): ip = models.CharField(max_length=100) def __str__(self): return self.ip class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') cover = models.ImageField(upload_to='upload/', null=True) body = models.TextField() link = models.CharField(max_length=1000, null=True) imdb_rating = models.DecimalField(null=True, max_digits=12, decimal_places=1) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views = models.ManyToManyField(IpModel, related_name="post_views", blank=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() def total_views(self): return self.views.count() views.py Here I think there is problem in logic to render the actual count and retracting the Ip from visitor. … -
TransactionManagementError when saving model with OneToOne relationship in Django
I'm trying to make it so that when a User model is created, it also creates the corresponding MyAppProfile class to go with it. But when I do so, as I've seen online, I get an error. An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I've tried various methods to do this, and they give that error when I try it. I can't figure out why I'm getting that error, or where exactly it's coming from. My profile class: class MyAppProfile(models.Model): user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="myapp_profile") # Other fields for this app's profile go here def __str__(self): return f'{self.id}: MyApp Profile for {self.user.username}' def save(self, *args, **kwargs): super().save(*args, **kwargs) @receiver(post_save, sender=AUTH_USER_MODEL) def update_profile_signal(sender, instance, created, **kwargs): if created: MyAppProfile.objects.create(user=instance) instance.myapp_profile.save() -
ASGI vs WSGI resource needs
i need to choose a web server for a project im doing with the need to serve a web application. while i know the difference between ASGI and WSGI web servers, i could not find any information regarding the resource needs difference between them. currently i want to make development fast and easy so i intend to use FastAPI with Uvicorn, but uncertain about the resources needed. the machine ill run it on is fairly weak, should i use Flask + gunicorn for resource saving? whats the benchmark resource difference between the 2 technologies? -
Celery Periodic task getting executed multiple times
I have a celery task that is scheduled to run at a specific time of the day. The problem is this task is getting executed multiple times, so I am receiving the same email at least 2 to 3 times. @periodic_task(run_every=crontab(hour=7, minute=10)) def send_reminder_email_at_7(): obj = Service() obj.send_email() return On server, I have setup the project using gunicorn and the supervisor Following is the configuration of celery and celery beat [program:proj_worker] command=/home/ubuntu/venv/bin/celery -A baseproj worker -l debug directory=/home/ubuntu/proj/ user=ubuntu numprocs=1 stdout_logfile=/home/ubuntu/logs/celerylogs/proj_worker.log stderr_logfile=/home/ubuntu/logs/celerylogs/proj_worker_err.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 [program:proj_beat] command=/home/ubuntu/venv/bin/celery -A baseproj beat -l debug --scheduler django_celery_beat.schedulers:DatabaseScheduler directory=/home/ubuntu/proj/ user=ubuntu numprocs=1 stdout_logfile=/home/ubuntu/logs/celerylogs/proj_beat.log stderr_logfile=/home/ubuntu/logs/celerylogs/proj_beat_err.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 Following is gunicorn configuration [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/ubuntu/proj ExecStart=/home/ubuntu/venv/bin/gunicorn --access-logfile /home/ubuntu/logs/gunicorn/gunicorn-access.log --error-logfile /home/ubuntu/logs/gunicorn/gunicorn-error.log --workers 3 --bind unix:/home/ubuntu/proj/proj.sock baseproj.wsgi [Install] WantedBy=multi-user.target -
django models imagefield upload_to method not working
I am using create view to create a model instance (product). Evey thing is working fine bt after doing some new migrations i can't get the uploaded image, instead getting default image. I think upload_to method of models isn't working. i also used this in my urls urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my settigs vars: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' This is my models.py: class Product(models.Model): TYPE = [ ('Sell','Sell'), ('Rent','Rent'), ('Sell or Rent','Sell or Rent'), ] owner = models.ForeignKey(Owner, on_delete=models.CASCADE) title = models.CharField(max_length = 25) type = models.CharField(max_length = 12, choices = TYPE, default = 'Sell') price = models.IntegerField() description = models.TextField(default="No Description Given") image = models.ImageField(default='default.jpeg', upload_to='product') def __str__(self): return self.title def get_absolute_url(self): return reverse('store') and this is my views.py: class ProductCreateView(LoginRequiredMixin, CreateView): model = Product fields = ['title','type', 'price','description', 'image'] def form_valid(self, form): print(self.request.POST) owner , created = Owner.objects.get_or_create(user=self.request.user) form.instance.owner = self.request.user.owner return super().form_valid(form) I am getting default image for every new product created. Thanks P.S. when i am adding product from admin panel then every thing is working fine. -
Django Not Displaying ID properly in admin page
I have a model that's a profile in a 1-1 relationship with the User model. class MyAppProfile(UUIDModel): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="myapp_profile") # Other fields for this app's profile go here used = models.BooleanField(default=False) def __str__(self): return f'{self.id} {self.pk}: MyApp Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) def create_user_profile(sender, instance, created, **kwargs): if created: MyAppProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=AUTH_USER_MODEL) When I view this in the admin page, it shows the ID for the user.id field instead of the id of the MyAppProfile. For example, for the one I manually created, it has user.id value of 4TeBms2K; and an ID of 4SrBSXw1. Yet when I view it in the admin panel, it shows up as 4TeBms2K 4TeBms2K: MyApp Profile (see that the __str__ method shows that that should be the ID instead of the user ID) Custom model that it's inheriting from def gen_uuid(length: int = 8): return base58.b58encode(uuid.uuid4().hex).decode('utf-8')[:length] class UUIDField(CharField): description = "Unique UUID primary key for model." def __init__(self, max_length=8, *args, **kwargs): super().__init__( primary_key=True, unique=True, max_length=max_length, editable=False, serialize=False, default=gen_uuid, ) class UUIDModel(Model): id = UUIDField() max_length = 8 class Meta: abstract = True def __init__(self, max_length=8, *args, **kwargs): self.max_length = 8 self.id = UUIDField(max_length=max_length) super().__init__(*args, **kwargs) def save(self, *args, **kwargs): saved … -
Two Widgets in one form for same fields are not working at the same time
I have build a BlogApp and I am working on Forms. BUT I want to add two Widgets in One Form and Both widgets are for one same Field. forms.py class EditBlogPost(forms.ModelForm): class Meta: model = BlogPost fields = ['title'] widgets = {'title':forms.TextInput(attrs={'placeholder': 'e.g. For Painting, For Sculpting'})} widgets = {'title' : forms.Textarea(attrs={'cols':30})} The Problem When i put TextInput widget right below fields instance then TextInput widget works in Browser page but Textarea doesn't work AND when i put Textarea widget below fields instance then Textarea works and TextInput doesn't work. BUT i want them to run both at same time. I don't know what to do. Any help would be Appreciated. Thank You in Advance -
Creating a website that can help other create playslists from external sites [closed]
I'm a beginner ato Django and web development. recently as more edTech startups are rising. I'm planning on making a site that enables users to create a playlist of free materials that they find useful. Like if the playlist can contain videos from youtube, khan academy etc.. I tried googling on how to make such sites but I found no way. Any resources on getting me started and suggestions? -
JSON Web Token no longer has 'decode' attribute despite no changes
I have a function which provides a token for a user so they can access a video chat room using the Twilio Video API. Following their docs, we decode a JSON Web Token with the following code to give us their token: token = AccessToken(ACCOUNT_SID, API_KEY, API_SECRET, identity=f'{request.user.email}') token.add_grant(VideoGrant(room='My Room')) context = { 'token': token.to_jwt().decode() } This worked perfectly locally, and upon pushing it to live servers, continued to work there without fault. However, a few pushes later, with no changes to this code, and this error (below) has suddenly occurred. This also comes at the same time as another error, which is an ascii encoding error, which I believe may be linked. It's strange that although no changes have been made to this token object, or the function, that we suddenly encounter this error with decoding this token. If anyone has any pointers, would be greatly appreciated. -
How to redirect from payment page to index page
After payment, I have redirected it to the success page. form action="success" method="POST" Views tab def success(request): return render(request, 'success.html') Now I want the page to automatically redirect to the index/home page after a small delay. How can that be achieved. Can anyone please help with this? -
Query set is not JSON serializable
I am trying to create an endpoint but I keep getting an error: "Object of type model is not JSON serializable". I tried passing it through list() and json.dumps() but it int work. I tried printing the query and it was like [<Lead: Test>, <Lead: user2>, <Lead: user3>, <Lead: user4>] Here is the code I wrote: def leads(request): full = [] lead_list = list(Lead.objects.all()) print(lead_list) for i in lead_list: full.append(json.dumps(i)) print(full) return JsonResponse(list(full), safe=False) Here are a few question I looked at and tried: Output Django queryset as JSON I tried serializing it with serializer but the response was like this: "[{\"model\": \"leads.lead\", \"pk\": 1, \"fields\": {\"first_name\": \"Test\", \"last_name\": \"User\", \"age\": 25, \"city\": \"kolkata\", \"country\": \"India\", \"email\": \"ankr@gmail.com\", \"agent\": 1, \"status\": \"Potential\"}}, {\"model\": \"leads.lead\", \"pk\": 2, \"fields\": {\"first_name\": \"user2\", \"last_name\": \"test2\", \"age\": 44, \"city\": \"Mumbai\", \"country\": \"India\", \"email\": \"test2@gmail.com\", \"agent\": null, \"status\": \"prospect\"}}, {\"model\": \"leads.lead\", \"pk\": 4, \"fields\": {\"first_name\": \"user3\", \"last_name\": \"test3\", \"age\": 19, \"city\": \"Paris\", \"country\": \"France\", \"email\": \"test3@gmail.com\", \"agent\": null, \"status\": \"Prospect\"}}, {\"model\": \"leads.lead\", \"pk\": 8, \"fields\": {\"first_name\": \"user4\", \"last_name\": \"test4\", \"age\": 33, \"city\": \"London\", \"country\": \"UK\", \"email\": \"test4@gmail.com\", \"agent\": null, \"status\": \"Converted\"}}]" -
How do i redirect url to my admin page or home page once the user signed up and try to login after that ? Help Appricated
I have created a login and logout form and able to create the user at the admin page with sign up. I want the user when he signed up and login should redirect the page. login.html {% load static %} {% block content %} {% load crispy_forms_tags %} <!--Login--> <html> <head> <title> login </title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> </head> <div class="container py-5"> <h1>Login</h1> <form method="POST"> {% csrf_token %} {{ login_form|crispy }} <button class="btn btn-primary" type="submit">Login</button> </form> <p class="text-center">Don't have an account? <a href="/register">Create an account</a>.</p> </div> </html> {% endblock %} register.html {% load static %} {% block content %} {% load crispy_forms_tags %} <!--Register--> <html> <head> <title> login </title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> </head> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form|crispy }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> </html> {% endblock %} views.py from django.shortcuts import render, redirect from .models import * from .forms import NewUserForm from django.contrib.auth import login, authenticate from django.contrib import messages #import messages from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm #add this # Create your views here. def homeView(request): views = … -
Error reading XMLStreamReader by django request
My xml data: xml_payload = <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <Authentication > <username>blabla</username> <password>123456789</password> </Authentication> </soap:Header> <soap:Body> <data> <title>Test title</title> <content>Test body format</content> </data> </soap:Body> </soap:Envelope> My request in django project: try: url = "http://someurls.com" res = requests.post(url=url, data=xml_payload, headers={'Content-type': 'application/xml'}) return response.content, response.status_code except Exception as e: print(e) return None, 500 When i hit the request using postman then i get response is given bellow: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <soap:Fault> <faultcode>soap:Client</faultcode> <faultstring>Error reading XMLStreamReader.</faultstring> </soap:Fault> </soap:Body> </soap:Envelope>' It returns an error. I am surfing around the internet but didn't find any answer which is fulfilled my query. -
I want Auto Select corresponding values of two Select2 dropdown for large data
Requirement :- Web-Framework - Django I have got the task from my company in which i have two Select2 dropdown let say X and Y respectively and i am loading the values of X and Y from the excel file using pandas library. problem is data size of the excel file is very large around 15k of records and they want a functionality of if anyone value of dropdown is selected then their corresponding value should also be selected automatically in the other select2 dropdown. When i load the data in bulk select2 dropdown is lagging to solve. Also client is demanding that they want to see options when he click to select2 dropdown before making any search. What i have tried :- this is my index.html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index2.html</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" /> <style> #id_language { width: 100%; } </style> </head> <body> <div class="container"> <h3>Select Anyone</h3> <br> <br> <select name="language" id="id_fragname" class="w-50"> <option value="-1">Select Fragrance</option> </select> </div> <br> <br> <div class="container"> <br> <br> <select name="language" id="id_fragcode" class="w-50"> <option value="-1">Select Code</option> </select> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <script> //put your jquery code here $(document).ready(function () … -
Getting user's IP after sign up
I have a Django Website and I'm using IPInfo. When the user signs up, I have the following signal: def create_profile(request, user, **kwargs): ip = request.ipinfo.ip city = request.ipinfo.city country = request.ipinfo.country region = request.ipinfo.region timezone = request.ipinfo.timezone postal = request.ipinfo.postal loc = request.ipinfo.loc //Save into DB However, instead of saving the user's details it saves the server's IP, city, etc. What am I doing wrong and how can I fix this? -
Xvfb-run as a subprocess in Django running xfreerdp fails
I have a ThreadPoolExecutor object(rdp_connector_global) in a Dockerized Django application's view method calling the below method(_rdp_connect) via submit as follows: rdp_connector_global.submit(_rdp_connect, login.ip_address, login.remote_port, login.username, login.password, login.rdp_width_pixels, login.rdp_height_pixels) def _rdp_connect(hostname_or_ip, port, username, password, rdp_width_pixels=1920, rdp_height_pixels=1080): domain = None username_simple = username if "\\" in username: split = username.split["\\"] domain = split[0] username_simple = split[1] elif "@" in username: split = username.split["@"] username_simple = split[0] domain = split[1] connection = None if domain is None: xvfb_args_str = "/usr/bin/xvfb-run /usr/bin/xfreerdp /sec:tls /u:{0} /p:{1} /w:{2} /h:{3} /v:{4}:{5} /cert-ignore".format(username_simple, password, rdp_width_pixels, rdp_height_pixels, hostname_or_ip, port) connection = subprocess.Popen(xvfb_args_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) else: xvfb_args_str = "/usr/bin/xvfb-run /usr/bin/xfreerdp /sec:tls /d:{0} /u:{1} /p:{2} /w:{3} /h:{4} /v:{5}:{6} /cert-ignore".format(domain, username_simple, password, rdp_width_pixels, rdp_height_pixels, hostname_or_ip, port) connection = subprocess.Popen(xvfb_args_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) logging.info(connection.communicate()) connection.wait() logging.info(connection.communicate()) Xvfb and freerdp are installed in the Docker container correctly. The login command succeeds when I run it from Django shell or the shell inside the Docker. But the same command fails to login to the remote Windows machine when running via code. I am wit's end to solve this, any help is appreciated! When running via Django I get a ERRINFO_LOGOFF_BY_USER after 30 seconds of unsuccessful wait to connect to Windows machine. -
How to show rendered template as raw source code block?
I want to provide a rendered HTML block that shows an email signature - what it looks like with user data from the context - and also displays the populated HTML code as raw src to be copied for pasting into customers email signature. What would be the best (dry) way to do this? I have tried render_to_string as a variable in the context but the HTML is rendered. -
Customising Admin Panel In Django
I am working on An Ecommerce website, in this I am using following model: ''' class Order(models.Model): user = models.ForeignKey(User) date = models.DateTimeField(auto_now_add=True) order_total = models.PostiveIntegerField(default=0) class OrderItem(models.Model): order = models.ForeignKey(Order) item_name = models.CharField(max_length=20) quantity = models.PositiveIntegerField(default=0) ''' Inside admin panel I want to show these ordered Items detail together which belongs to the same order id. How can I customise my modelAdmin in order to OrderItem details as a readonly_Field. -
TypeError at /datatable datatable() missing 1 required positional argument: 'file'
In views.py def datatable(request,file): csv_fp = open(f'csv_upload_files/{file}.csv', 'r') reader = csv.DictReader(csv_fp) headers = [col for col in reader.fieldnames] out = [row for row in reader] return render(request, 'result.html', {'data' : out, 'headers' : headers}) In urls.py urlpatterns = [ path('', views.upload,name='upload'), path('datatable',views.datatable,name='datatable') ] I am unable to understand how to provide the saved csv file to the function datatable -
Django Error: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
It gives the error: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('App.urls')), path('accounts/', include(('django.contrib.auth.urls', 'django.contrib.auth'), namespace='login')), path('accounts/', include('Account.urls')), ] index.html <a href="{% url 'login' %}"><h3 class="agileinfo_sign">Sign In </h3></a> -
ValueError: invalid literal for int() with base 10: 'testuser1-2'
I'm trying to allow users to delete their own comments. I received this error: ValueError: invalid literal for int() with base 10: 'testuser1-2 Any idea whats wrong with my code? html {% for comment in blog_post.comments.all %} <form action = "{% url 'HomeFeed:deletecomments' comment.post_id %}" method = "POST"> {% csrf_token %} <br> {{ comment.body }} <button>Delete</button> </form> {% endfor %} urls.py path('comments/<slug>', AddCommentView.as_view(), name= "add_comment"), path('deletecomments/<post_id>', delete_own_comment, name= "deletecomments"), views.py @login_required def delete_own_comment(request, post_id): if request.method == 'POST': comment = get_object_or_404(Comment, post_id=post_id) if comment.user == request.user: comment.delete() return redirect('HomeFeed:detail', slug=slug) models.py class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE) body = models.TextField() date_added = models.DateField(auto_now_add=True) class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) brief_description = models.TextField(max_length=300, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) -
UserCheckout matching query does not exist
I'm trying to display all orders matching each logged in user, I dont understand why it gives me issues when trying to filter for users as it gives me that UserCheckout does not have any matching queries: orders/views.py class OrderList(LoginRequiredMixin, ListView): queryset = Order.objects.all() def get_queryset(self): user_check_id = self.request.user.id user_checkout = UserCheckout.objects.get(id=user_check_id) return super(OrderList, self).get_queryset().filter(user=user_checkout) orders/mixins.py class LoginRequiredMixin(object): @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs) orders/models.py class UserCheckout(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete = models.CASCADE) # not required as to allow guests to checkout too email = models.EmailField(unique=True) # required, unique as if there the guest already has an authentication just one email needed def __str__(self): return self.email Error it gives me: DoesNotExist at /orders/ UserCheckout matching query does not exist.