Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HTTP_REFERER refers to incorrect page
I have a django app that contains a link from the homepage that links to View1 that redirects to View2 and should redirect back to View1. However, the HTTP_REFERER header in View2 sees the homepage as the referer and not View1. Homepage Template ... <!-- This links to the LoginView --> <a href="{% url 'login' %}">Login</a> ... Login View class LoginView(views.View): def dispatch(self, request, *args, **kwargs): if not request.session.test_cookie_worked(): request.session.set_test_cookie() # This redirects to the create_captcha view return redirect(reverse('create_captcha')) return super().dispatch(request, *args, **kwargs) create_captcha view def create_captcha(request): if not request.session.test_cookie_worked(): return render("Please enable cookies and try again.") # This SHOULD redirect to LoginView but instead redirects to the homepage. return redirect(to=request.META.get('HTTP_REFERER')) Expected Behavior: homepage link -> LoginView -> create_captcha -> LoginView Actual Behavior: homepage link -> LoginView -> create_captcha -> homepage Question: How do I make the HTTP_REFERER point to the LoginView instead of the homepage? -
Django beginner define an index url and load the view
I am learning django and I am trying to add a new url to '/' here is my urls.py: from django.contrib import admin from django.urls import path from blog import views as blog_views urlpatterns = [ path(r'^$', blog_views.index), path('admin/', admin.site.urls), ] and here is the index method from blog/views: def index(request): return HttpResponse("Hey There") But when I go to '/' route, I get a 404 response. It seems that it fails at import from blog import views as blog_views in urls.py. What is going wrong? Here is my project structure: -
Django issue with formset validation
I'm new to django and have been pulling my hair out on this one. A co-worker coded a manual post function that validates is_valid()=true, and I'm trying to move towards using the built-in validation by overriding the formset_valid function, but it's never valid. I have this model.py: class Assignment(PACSModel): course_id = models.IntegerField(unique = False) assignment_number = models.IntegerField(unique = False) assignment_name = models.CharField(max_length = 100) start_date = models.CharField(max_length = 10) due_date = models.CharField(max_length = 10) end_date = models.CharField(max_length = 10) This forms.py: class AssignmentDatesForm(forms.ModelForm): class Meta: model = Assignment fields = [ 'assignment_number', 'assignment_name', 'start_date', 'due_date', 'end_date', ] widgets = { 'assignment_name' :forms.TextInput(attrs={'readonly':'readonly', 'class' : 'grey-text', 'size' : '25'}), 'start_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker'}), 'due_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker' }), 'end_date' : forms.DateInput(format = '%m/%d/%Y', attrs ={ 'class' : 'datepicker' }),} class Media: css = {'assignment_name': ('changeDates.css',)} AssignmentDatesFormSet = forms.modelformset_factory( model = Assignment, form = AssignmentDatesForm, extra = 0, ) manually iterating through the forms to display: <table class = "table table-striped table-condensed table-hover"> <thead > <tr> <th>Assignment Number</th> <th>Assignment Name</th> <th>Start Date</th> <th>Due Date</th> <th>End Date</th> </tr> </thead> <tbody> {% for t in form %} <tr> <td>{{ t.assignment_number }}</td> <td … -
In Tastypie with nested resources, for a given url, what is the best way to get the view function name?
I can get the view name through the following steps Get the View name of the child resource from django.core.urlresolvers import resolve resolve(/api/v1/parent/child).view_name api_get_children Look for view name the prepend_urls() under the parent resource. I will see something like url(r"^(?P%s)/(?P\w[\w/-]*)/children%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_children'), name="api_get_children") Search for the function definition def get_children Is there a method to get the function name in one step? -
How to compare date from a form with date from db in django query?
I am trying to filter tours based on the date in Django 2.0, i.e. to show all the tours that start on or after June 01, 2019 (should be received from a form). I have a model 'Tour': class Tour(models.Model): destination = models.ForeignKey(Destination, on_delete=models.PROTECT) Created = models.DateTimeField(auto_now_add=True) Updated = models.DateTimeField(auto_now=True) Available = models.BooleanField(default=True, help_text="Tick it if you still operate this tour") And I have a model 'Departures': class Departures(models.Model): tour = models.ForeignKey(Tour, on_delete=models.CASCADE) DepartingDate = models.DateField(auto_now=False) FinishingDate = models.DateField(auto_now=False) DepartureStatus = models.CharField(max_length=200, choices = DEPARTURE_STATUS, help_text="Select from the list") PlacesAvailable = models.BooleanField("Places avalable", default="True") DepartureGaranteed = models.BooleanField("Departure Garanteed", default="True") I want the user should select a start date of the tour from the html form: <div class="form-group"> <input class="form-control" id="dateStart" name="DateStart" type="date"/> </div> I have a form in my models.py: class SearchForm(forms.Form): Country = forms.CharField(max_length=255, required=False) TourType = forms.CharField(max_length=255, required=False) TourTheme = forms.CharField(max_length=255, required=False) Duration = forms.IntegerField(required=False) #, blank=True Price = forms.CharField(max_length=255, required=False) #, blank=True DateStart = forms.DateField(required=False) #input_formats='%d/%m/%Y', So I am trying to filter the tours like below: tours = Tour.objects.filter(Q(Departures__DepartingDate__gt=DateStart)) But it is not working. I guess the problem is that the html form date format and the django db date format are not matching. It does not … -
How to render out a queryset in Django templating?
I'm creating an inbox where the logged in user can see all of their messages using Django Channels 2. I would like to render out the queryset in the InboxView in order to return all thread objects for the logged in user. I am having trouble with the syntax and the threads aren't appearing. If someone could kindly help me, I would appreciate it. I would like to render out the queryset in the InboxView in order to return all thread objects for the logged in user. views.py class InboxView(LoginRequiredMixin, ListView): template_name = 'chat/inbox.html' def get_queryset(self): return Thread.objects.by_user(self.request.user) models.py class ThreadManager(models.Manager): def by_user(self, user): qlookup = Q(first=user) | Q(second=user) qlookup2 = Q(first=user) & Q(second=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs class Thread(models.Model): first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first') second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() def __str__(self): return f'{self.first}' class ChatMessage(models.Model): thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='sender', on_delete=models.CASCADE) message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.id}' inbox.html {% for thread in object.thread_set.all?? %} <div class="chat_list"> <h5>{{ thread.second }}<span class="chat_date">{{ thread.timestamp }}</span></h5> <p>{{ chat.message? }}</p> </div> {% endfor %} -
Count unique words in blog's article and save it in model
I have blog with articles ( Article is model). Every article contains title and body. I need to add field, which contains list of unique words of that article and occurrence in the article. For example, article " Hello my name is John, hello", field "words" should looks like: {"hello": 2, "my": 1, "name":1, "is":1, "john":1} Additionally, i should have endpoint, which returns ALL words from ALL articles and their occurrence. How I want to implement it: Add field "unique_words" (type JSONField) and default value "please wait, word's occurrence are being calculated...". Then add post save signals which via Celery will do all calcuration and update field "unique_words" with data like this {"hello": 2, "my": 1, "name":1, "is":1, "john":1} Also I add endpoint, which will retrieve unique_words from all articles and summarize them. Is it best solution? Could you please recommend something better? -
Django: Object of type 'datetime' is not JSON serializable
I'm trying to save a date in my sessions. I always receive the error Object of type 'datetime' is not JSON serializable. I found this here in the Django documentation: stored as seconds since epoch since datetimes are not serializable in JSON. How can I save my expiry_date as seconds instead of datetime? code = social_ticketing_form.cleaned_data['a'] expiry_date = timezone.now() + timezone.timedelta(days=settings.SOCIAL_TICKETING_ATTRIBUTION_WINDOW) request.session[social_ticketing_cookie_name(request.event)] = {'code': code, 'expiry_date': expiry_date} -
Calling a function from another file to use in templates
I have a function to create a percentage in this file status.py class Status: read_books = Books.objects.filter(read="True") all_books = Books.objects.all() def percentage(self): asdf = get_percentage(len(self.read_books),len(self.all_books)) return asdf I am trying to be able to use this function in my template to display this percentage by using something like this in my template {{ status.percentage }} Is this possible? would i have to put logic into my view in order to do this? perhaps i could put this function in my view class and call it from there? -
A model for "generic" component connections with conditions
I am trying to create a model which represents a completed "product". A "product" consists of multiple parts, which are connected together, using connectors. One part would "provide" the connector, and the other part would "require" the connector A general product will consist of at least a housing and a backplane. The backplane could itself provide a processor, but could also provide a socket into which a processor could be inserted. The size of the housing would restrict the sizes of backplane which could be used in the specific housing. The backplane could have multiple sockets (of different types), each of which could host a processor, but the processor and socket must match. At least one processor in total must be present A concrete example of a valid product would be Housing A +- max width 100 Backplane B + width 90 + socket type A + socket type A processor + processor model Y + socket type A Another valid product would be Housing B +- max width 50 Backplane C + width 50 + processor model X <-- This is builtin to the backplane A final valid product Housing B +- max width 50 Backplane C + width … -
django-table2 ->how to accomplish getting a multiline cell
I have one column in my table (based on a class, not a model class) that is a python Dict object, I'd like the cells in it's column to display as one line per dict entry. the class I'm displaying: class MegaDatapoint: def __init__(self, id=None, name=None, display_name=None, description=None, enum_dict=None, ): self.id = id self.name = name self.display_name = display_name self.description = description self.enum_dict = enum_dict in my tables.py I have the following: class DictColumn(tables.Column): def render(self, value): if type(value) is dict: v = "" for d in value: v += f"{d}->{value[d]}\n\r" else: v = "--" return v class MegaTable(tables.Table): name = tables.Column() display_name = tables.Column() description = tables.Column() enum_dict = DictColumn(attrs={'td': {' white-space':'pre-wrap'} }) the template "megadatapoint_table2.html" is: {% extends "base.html" %} {% load render_table from django_tables2 %} {% block title %}{{ block.super }}Projects{% endblock %} {% block container %} <div> <title>List of Datapoints</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> </div> <div> {% render_table table %} </div> {% endblock %} And finally the view: class MegadatapointTableView(SingleTableView): table_class = MegaDatapointTable template_name = 'megadatapoint_table2.html' def get_queryset(self): """ Return the product features for this product """ self.enums = Enumeration.objects.all().order_by('enumeration_group') self.enum_values_dict = {} for enum in self.enums: if enum.enumeration_group.id not in self.enum_values_dict: self.enum_values_dict[enum.enumeration_group.id] = {} self.enum_values_dict[enum.enumeration_group.id][enum.ordinal] … -
Getting Error with Django Social Authentication
I have been working on social authentication with my current project but i am getting an error which leads to two more errors depending on the social media platform am using to signing in. Upon successful redirection from the social media platform, i get an error from my Custom Model Manager create user that user must enter A password for Google auth or User Must enter a password for Facebook auth. From these above error it could be summed up that Django is trying to create a user account immediately upon redirection from social platform. My first question is should this behavior considered normal, as there might be some complications if the user already has an account. Second if the behavior is normal, how then should i go about completing the signup process. Thanks -
Listing all permissions from a specific model, and putting the result in a table
I'm having trouble listing all model-specific permissions in a table. I'm able to pull out permissions through {{ perms.account }} in the html, but it won't filter for permissions specific to the account model. Futhermore i want to list each permission in a html table, with the permissions description, and a checkmark if its granted: Permission1 Desc1 V <!-- Granted --> Permission2 Desc2 X <!-- Not granted --> I have tried for-looping all permissions, and filtering out the ones related to the model account, and then for looping to get the different rows in the table. This, however, just returned a long string of all permissions names (including the django native ones). I have also tried the code bellow, but was not able to retrieve data in the html template through {{ permissions }}, {{ account.permissions }} or {{ permissions.account }} class cms_users_user_permissions(generic.DetailView): model = Account template_name = 'cms/users/cms-users-user-permissions.html' content_type = ContentType.objects.get_for_model(Account) permissions = Permission.objects.filter(content_type=content_type) views.py class cms_users_user_permissions(generic.DetailView): model = Account template_name = 'cms/users/cms-users-user-permissions.html' models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) site = models.CharField(max_length=50, choices=(('all', 'all'), ('danielk', 'danielk')), blank=True) role = models.CharField(max_length=50, choices=(('Administrator', 'Administrator'), ('Moderator', 'Moderator'), ('Editor', 'Editor'))) phone_number = models.CharField(max_length=8) birth_date = models.DateField() street_adress = models.CharField(max_length=255) note = models.TextField(blank=True); … -
How to tell if user's email address has been verified using Django, allauth, rest-auth and a custom user
I'm using Django 2.0.10 with rest-framework, rest-auth and allauth. I have a custom user model. I've got email verification apparently working by using the allauth view. The verification email is sent when a user registers. If I click the link in the email, I'm taken to a page with a button to click to verify the email. This all works without error. However what I can't find out is what this actually does. No field in the user's data seems to change. The behaviour I want is for users to be able to register and login, but only to be able to add content to the site after they have verified their email. settings.py # django rest auth ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_EMAIL_VERIFICATION = 'optional' api/urls.py from allauth.account.views import confirm_email urlpatterns = [ re_path(r'^rest-auth/registration/account-confirm-email/(?P<key>[-:\w]+)/$', confirm_email, name='account_confirm_email'), ... ] users/models.py import uuid from django.contrib.auth.models import AbstractUser, UserManager from django.db import models from django.utils.http import int_to_base36 class CustomUserManager(UserManager): def get_by_natural_key(self, username): case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) return self.get(**{case_insensitive_username_field: username}) ID_LENGTH = 12 def pkgen(): from base64 import b32encode from hashlib import sha1 from random import random pk = int_to_base36(uuid.uuid4().int)[:ID_LENGTH] return pk class CustomUser(AbstractUser): … -
How do I narrow down my results to 1 per user?
I have the following code, that retrieves contracts from users and returns them in ascending or descending order. This will display every contract for every user. How do I limit this query to 1 result for every user, as I'm only looking for the last or first contract? first_contract = Contract.objects.select_related('user').order_by('contract_start') last_contract = Contract.objects.select_related('user').order_by('-contract_start') Model: class Contract(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) contract_start = models.DateField(null = True, blank = True) contract_end = models.DateField(null = True, blank = True) Putting [:1] on the end is not what I'm looking for, this will only give me 1 result of 1 user. -
How to send error message from Django DeleteView?
Let's say there are two models Parent and Child. Parent to child is one to many relationship. I am creating DeleteView for Parent model. Before deleting I need to check whether Parent has Children. If there are no Children then Parent model is deleted as usual. But if there are Children then I need to send error message to DeleteView confirmation page. How can I achieve this using DeleteView? -
Django: Combine two similar util functions
I have the following get function in my views.py. My two until functions do almost look the same and I don't seem to follow the DRY principle. However, I currently don't know how to write this better. Can you suggest a better way? def get(self, request, *args, **kwargs): # Delete discount code cookie if ?delete_discout is set in get parameter delete_discount_code = request.GET.get('delete_discount') if delete_discount_code: self.discount_code = delete_discount_session(request, self.discount_code_session) # Delete discount code cookie if ?delete_social_ticketing is set in get parameter delete_social_ticketing = request.GET.get('delete_social_ticketing') if delete_social_ticketing: self.social_ticketing_code = delete_social_ticketing_session(request, self.social_ticketing_session) My utils.py are structured like this: def discount_cookie_name(event): """Unique discount cookie name per event""" return f'discount_code_{str(event.pk)}' def social_ticketing_cookie_name(event): """Unique social ticketing cookie name per event""" return f'social_ticketing_{str(event.pk)}' def delete_social_ticketing_session(request, social_ticketing_code_session): if social_ticketing_code_session: del request.session[social_ticketing_cookie_name(request.event)] return None def delete_discount_session(request, discount_code_session): if discount_code_session: del request.session[discount_cookie_name(request.event)] return None -
Recursively displaying a MPTT tree in Django Template with multiple models
So, I am using Django-mptt to establish a tree structure within my database, I would then like to recurse over the tree and display the objects in an html tree type structure. However, whenever I use the {% recursetree Architecture %} call in my template it only displays the Architecture objects. I was hoping to find a way to iterate down through the tree displaying each node. Any help is appreciated. models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Architecture(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='Children') class MPTTMeta: order_insertion_by = ['name'] class Vehicle(MPTTModel): name = models.CharField(max_length=50, unique=True) mass = models.IntegerField() parent = TreeForeignKey('Architecture', on_delete=models.CASCADE, null=True, blank=True, related_name='Systems') class MPTTMeta: order_insertion_by = ['name'] class System (MPTTModel): name = models.CharField(max_length=50, unique=True) mass = models.IntegerField() parent = TreeForeignKey('Vehicle', on_delete=models.CASCADE, null=True, blank=True, related_name='SubSystems') class MPTTMeta: order_insertion_by = ['name'] class SubSystem(MPTTModel): name = models.CharField(max_length=50, unique=True) mass = models.IntegerField() parent = TreeForeignKey('System', on_delete=models.CASCADE, null=True, blank=True) class MPTTMeta: order_insertion_by = ['name'] class Mission(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('Architecture', on_delete=models.CASCADE, null=True, blank=True, related_name='Events') class MPTTMeta: order_insertion_by = ['name'] class Event(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('Mission', on_delete=models.CASCADE, null=True, blank=True) class MPTTMeta: order_insertion_by = ['name'] views.py from django.shortcuts … -
Object of type 'Mycart' is not JSON serializable in Django
I want to add dictionary(having models) datatype object to request.session but getting "Object of type 'Mycart' is not JSON serializable in Django" product_details = {} for product in products_in_cart: product_details.update({product.id: (product,request.POST['quantity'+str(product.product.id)])}) request.session['product_details'] = product_details I expect the dictionary updated in session but the actual output is "Object of type 'Mycart' is not JSON serializable in Django" -
Django ORM get Latest version of each row (Inner Join)
I have a table (short version ofcourse) like the following -------------------------------------------------------- |id | Simulation_Name | Simulation_Version | sim_key | -------------------------------------------------------- | 1 | MySim1 | 1 | 10 | | 2 | MySim1 | 2 | 10 | | 3 | MySim2 | 1 | 11 | | 4 | MySim2 | 2 | 11 | -------------------------------------------------------- On the Front End, I just want to display the latest version for each simulation. I'd appreciate any help on how to do this using Django ORM. I know there is a Max field but that only works with dates.. Currently, I'm using Raw SQL with an inner join to achieve this. Any pointers on ORM? Thanks in advance This is how I do it right now, SELECT * FROM simulation_table AS A INNER JOIN (SELECT id, max(simulation_version) as max_version from simulation_table group by sim_key) AS B ON A.sim_key= B.sim_keyAND A.simulation_version= B.simulation_version -
Annotate aggregate Sum of a Subquery in Django
Before moving forward and writing raw sql I wanted to see if anyone could shed some light onto an issue I am trying to solve using the Django ORM. I want to annotate the aggregate Sum of Subquery onto a queryset. The Subquery returns the correct data. The issue I am having is getting the Sum from that query and annotating it onto the OuterRef's queryset. I've tried, multiple ways. The line below illustrates the ideal example of what I want, but does not work. total_spend=Subquery(subq.aggregate(Sum('spend')), IntegerField()) This errors with This queryset contains a reference to an outer query and may only be used in a subquery. I also have attempted to do the aggregation on the subq variable but haven't been able to figure out how to group by account. Here is the subquery and attempt to annotate. from django.db.models import Sum, Q, F, OuterRef, Value as V, Subquery, IntegerField from django.db.models.functions import Coalesce import datetime acc = Account.objects.all() subq = (Spend.objects.annotate( latest_date=Coalesce('campaign__account__end_date', V(datetime.date(2038, 1, 19))), earliest_date=F('campaign__account__start_date') ).filter( (Q(date__lte=F('latest_date')) & Q(date__gte=F('earliest_date'))), campaign__account_id=OuterRef('pk'), campaign__campaign_dates__type=1 )) a = acc.annotate( total_spend=Subquery(subq.aggregate(Sum('spend')), IntegerField()) ) I appreciate any direction! -
Django PasswordResetView custom email
I'm creating a password-reset function in Django. I want to choose a custom email (in HTML). I can't find any docs and I think my files are completely wrong but I really don't know how Django's email service work. I guessed by other peoples questions on stackoverflow. Here are my files: urls.py: urlpatterns = [ path('reset', auth_views.PasswordResetView.as_view(template_name='authenticate/reset.html'), { 'template_name': 'email/test.html', 'html_email_template_name': 'email/test.html', 'email_template_name': 'email/test.txt', 'subject_template_name': 'email/test.txt', }, name='password_reset'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done', auth_views.PasswordResetDoneView.as_view(template_name='authenticate/reset_done.html'), name='password_reset_done'), ] test.html: <html style="font-family:sans-serif;margin:0;padding:0;"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>E-Mail</title> </head> <body> <header style="background-color:#fff;"> <div class="navbar-container"> <div class="navbar-branding" style="margin:0;"> <p style="margin:0;">Logo</p> </div> </div> </header> <div style="background-color:#f0f0f0;padding-left:10vw;padding-right:10vw;padding-top:200px;min-height:50vh;"> <div style="background-color:#fff;color:#aaa;"> <table style="margin:auto;color:#aaa;padding: 20px;"> <th> <h1>{% block subject %}{% endblock %}</h1> <p>{% block body %}{% endblock %}</p> </th> </table> </div> </div> {% include 'template/footer.html' %} </body> </html> test.txt: {% block subject %} Password reset {% endblock %} {% block body %} Reset your password <a href="{{ site_name }}">here</a>. {% endblock % } -
“select_for_update” called inside an atomic block still TransactionManagementError
the code blow @transaction.atomic def cancel_one(o_id): order= Order.objects.select_for_update().get(id=o_id) raise TransactionManagementError('select_for_update cannot be used outside of a transaction.') django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction. I have checked my code is in transaction by transaction.get_connection().in_atomic_block. it appeared in the transaction, but still raise Error: django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction. My Code: # Step1 def cancel_one(o_id): print("DO") cxn = transaction.get_connection() if cxn.in_atomic_block: print("We're inside a transaction!") order= Order.objects.select_for_update().get(id=o_id) # Step2 @transaction.atomic def cancel_one(o_id): print("DO") cxn = transaction.get_connection() if cxn.in_atomic_block: print("We're inside a transaction!") order= Order.objects.select_for_update().get(id=o_id) Code Result # Step1 ----------------------- DO ----------------------- # Step2 ----------------------- DO "We're inside a transaction!" ----------------------- -
How to fix this NoReverseMatch exception in Django rest frameworks routers?
I'm working on this Django project for learning and I'm not able to resolve the URL using reverse(). I have tried to understand this concept from online documentations and I'm not able to succeed with it. I'm using ModelViewSet in my views.py In my tests.py POSTS_URL = reverse('posts:posts-list') And this is my urls.py of posts(i.e., app) app_name = 'posts' router = DefaultRouter() router.register('', PostsViewSet) urlpatterns = [ path('', include(router.urls)) ] This is my urls.py in root urlpatterns = [ path('admin/', admin.site.urls), path('api/posts/', include('posts.urls')), path('docs/', include_docs_urls(title='My API title')), ] And this is the error I'm getting django.urls.exceptions.NoReverseMatch: Reverse for 'posts-list' not found. 'posts-list' is not a valid view function or patternname. And also can someone suggest a good place to understand properly how reverse() and routers work together.. -
form is not valid : Django
I am trying to make image upload functionality through ajax.I have checked everything and still Django is returning form.is_valid() to be False and i still can not figured out any possible error in this. form.is_valid() is returning False . Here i am sharing my views.py and html as well as ajax code def upload_profile_picture(request): data={} uploadform=update_profile_photo(request.POST,request.FILES) if uploadform.is_valid(): image=request.FILES['profile_picture'] if image: userID=request.POST['vuserID'] usr=User.objects.get(pk=userID) if usr.id == request.user.id: usr.profile.profile_picture=image usr.profile.save() data['success']=True else: data['error_message']='you are not an authorized user' print('you are not an authorized user for uploading this photo') else: data['error_message']='image not supplied' print('image is not supplied in the form') else: data['error_message']='profile photo upload form is not valid' print('this form is not valid') return JsonResponse(data) Here is my ajax code that is sending form data to views.py Here is ajax code: <script> $(document).ready(function () { $('#upload_profile_picture').submit(function (e) { e.preventDefault(); alert(" i am uploading profile_picture"); var form = $(this); var formData = new FormData(this); var user_id=$(this).attr('data-user-id'); //var postDescription = $('#post-form-description').val().trim(); var image = $('.upload_profile_photo').val().trim(); //console.log(postDescription); console.log(image); if(!image){ alert('cannot submit empty forms!'); return false; } $.ajax({ type: 'POST', url: "{% url 'account:upload_profile_picture' %}", data: formData , success: function (data) { if(data.success){ location.reload(); } }, cache: false, contentType: false, processData: false }); }); }); and …