Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot apply makemigrations to model after modifying
I implemented a model for my Django app in models.py. Everything worked fine. Then I tried adding a new property to the class. If I now run "makemigrations" I get the error "table movieapp_movie_class has no column named show_movie". I thought that running makemigrations was the command to add this column to the table. I've tried deleting db.sqlite3 and the migration-folder in the app-folder which did not work. from django.db import models # Create your models here. class movie_class(models.Model): show_movie = models.CharField(max_length=100) # this is the new property I wanted to add movie_id = models.CharField(max_length=100) title = models.CharField(max_length=100) rating = models.CharField(max_length=100) poster = models.CharField(max_length=100) -
Django Rest Framework - issue with DELETE - CSRF not found
I'm using Django Rest Framework with CSRF. POST and PUT methods work as expected, but DELETE is giving error 403 with - following message "{"detail":"CSRF Failed: CSRF token missing or incorrect."}. It appears that frontend application (Angular) is doing a proper POST and PUT requests. I'm not getting any issues with CSRF nor CORS. Example: DELETE Request: Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,pl;q=0.8 Cache-Control: no-cache Connection: keep-alive Cookie: _ga=GA1.1.1418236812.1564012825; _gid=GA1.1.747517255.1564126213; sessionid=zho7t6c8vbot46uuwka8ufh53pkanein; _gat_gtag_UA_127399308_1=1; X-XSRF-TOKEN=hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp Host: 127.0.0.1:4200 http-x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp Origin: http://127.0.0.1:4200 Pragma: no-cache Referer: http://127.0.0.1:4200/cost_center/form/e503dbfd-8eae-49e4-becc-4aa60016b996 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp DELETE Response headers: HTTP/1.1 403 Forbidden X-Powered-By: Express access-control-allow-origin: http://127.0.0.1:4200 date: Sun, 28 Jul 2019 14:36:12 GMT server: WSGIServer/0.2 CPython/3.7.3 content-type: application/json vary: Accept, Origin, Cookie allow: GET, PUT, DELETE, HEAD, OPTIONS x-frame-options: SAMEORIGIN content-length: 58 access-control-allow-credentials: true connection: keep-alive DELETE Response: Request URL: http://127.0.0.1:4200/api/cost_center/e503dbfd-8eae-49e4-becc-4aa60016b996 Request Method: DELETE Status Code: **403 Forbidden** Remote Address: 127.0.0.1:4200 {"detail":"CSRF Failed: CSRF token missing or incorrect."} Then, when I do for example "PUT" request, it is executed without any issue: PUT Request: Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,pl;q=0.8 Cache-Control: no-cache Connection: keep-alive Content-Length: 82 Content-Type: application/json Cookie: _ga=GA1.1.1418236812.1564012825; … -
Aggregation of a related object does not output as expected
I have a related model to this one : class Node(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') name = models.TextField(blank=True, null=True) Which is this one : class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.related_tree.name What i want to do is to filter the Node objects with a search keywords that the user will type, and within the result i want to show the number of the visits for each objects so this is the view that i have written so far, if search_text_imported != '': filter = Q() cases = {} get_result_list = [x for x in search_text_imported.split() if x != ''] for i, keyword in enumerate(get_result_list): filter |= Q(name__icontains=keyword) filter |= Q(Tags__icontains=keyword) cases['keyword_match_{}'.format(i)] = Case( When(name__icontains=keyword, then=1), default=Value(0), output_field=models.IntegerField(), ) result = Node.objects.filter( filter, tree_type='root', published=True ).annotate( **cases ).annotate( total_views=Sum('related_views__views_count'), num_bookmarks=Count('bookmarked_by'), keywords_matched=reduce(add, (F(name) for name in cases)) ).order_by('-keywords_matched', '-num_bookmarks').annotate( ) context = { 'tree_result': result } Within the template this what i have {% if tree_result %} {% for tree in tree_result|slice:":14" %} {{ tree.total_views }} {% endfor %} {% endif %} Everything seems to work perfectly except one thing is in … -
Invalid interpolation format for "environment" option in service "web": "SECRET_KEY=
I am working on online book store project. I am trying to setup environment variables in dockercompose.yml project_folder/settings.py SECRET_KEY = os.environ.get('SECRET_KEY') The code inside dockercompose.yml file version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - SECRET_KEY=my_secret_key - DEBUG=1 db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: I am getting the following error when I ran the command $docker-compose down ERROR: Invalid interpolation format for "environment" option in service "web": "SECRET_KEY=my_secret_key" -
Django: How to follow ForeignKey in unique_together constraint?
I have three Django Models: a Property Model, most importantly having a slug field; a Collection Model; and a PropertyCollectionRelationship Model. The last model models a ManyToMany relationship between the other two and is used as an explicit through of a ManyToManyField. from django.db import models class Property(models.Model): slug = models.SlugField() collections = models.ManyToManyField('Collection', blank=True, through='PropertyCollectionRelationship') # ... other unimportant stuff omitted ... class Collection(models.Model): pass # ... lots of stuff omitted ... class PropertyCollectionRelationship(models.Model): prop = models.ForeignKey(Property, on_delete=models.CASCADE) coll = models.ForeignKey(Collection, on_delete=models.CASCADE) I would like to add a uniqueness constraint which ensures that each collection has at most one property with any given slug. I tried to express this via a unique_together option in the Model Meta: class PropertyCollectionRelationship(models.Model): class Meta: unique_together = [['coll', 'prop__slug']] prop = models.ForeignKey(Property, on_delete=models.CASCADE) coll = models.ForeignKey(Collection, on_delete=models.CASCADE) This resulted in the following System Check Error: SystemCheckError: System check identified some issues: ERRORS: myapp.PropertyCollectionRelationship: (models.E012) 'unique_together' refers to the nonexistent field 'prop__slug'. How, if at all, can I achieve such a constraint? -
How do I query the database for all the points that are within a certain radius from a users location?
I am trying to get all the points from the database that are with a certain radius from the users location(e.g 10km). So basically I would like the user to input a location, which would then be converted to lat and lng using the google maps api and have the application search for and return all the stores in the database that are within a 10 km radius of the users location. I have tried Haversines formula but can't seem to get that to work since I do not have a strong understanding of how to filter search results from the database. Could anyone please explain to me how best to query the database for results within a 10km radius using Haversines formula? models.py: class Detail(models.Model): name = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=300, blank=True) lat = models. DecimalField(max_digits=9, decimal_places=6) lng = models.DecimalField(max_digits=9, decimal_places=6) views.py: def feed(request): latitude = request.session['lat'] longitude = request.session['lng'] radius = 20000 unit = 6371 # Distance unit (kms) radius = float(radius) / 1000.0 # Distance radius convert m to km lat = float(latitude) # Central point latitude lng = float(longitude) # Central point longitude print(lat,lng,radius) limit = 1000 My views .py is returning to lng and … -
model() missing 1 required positional argument: 'request'
Error: model() missing 1 required positional argument: 'request' I want to do abstract api for all models in my app urls.py urlpatterns = [ path('api/object/', views.GeneralViewSet.as_view({'get': 'list'})) ] views.py class GeneralViewSet(viewsets.ModelViewSet): @property def model(self, request): return apps.get_model(app_label=self.request.data.get('app'), model_name=self.request.data.get('object')) def get_queryset(self, request): return self.model.objects.all() def get_serializer_class(self, request): GeneralSerializer.Meta.model = self.model return GeneralSerializer def post(self, request): queryset = self.model.objects.all() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I expect the list of my data of models for example for post api of { "app": "leads", "object": "Lead" } expect all data from Lead object -
How to display image from temp folder to template in Django
I have just started working on django(But I have worked on python for about a year). For my MFA application, I have created .png file(qr code) in my admin.py file and I have stored this png in /tmp/ dir. Now I need to show this image to template. The reason I have stored this file in temp dir becouse the image created is one time. SO I want to show this image view for once and delete after that. So anyone can help me to get me out from this? Thanks for advance qr_url = "otpauth://totp/%s:%s?secret=%s&issuer=%s" % (label, user, secret, label) url = pyqrcode.create(qr_url) random_file_path = datetime.datetime.now().strftime("%Y%m%d%H%M%S") url.png('/tmp/'+str(random_file_path)+'.png', scale=4)` This is how I created png I have tried by directly providing temp dir path. Also If I have to store the file in static then please help me for storing and deleting file in static folder`` -
What is exactly Meta in Django
i want know simply what is Meta class in django and what they do from django.db import models Class Author(models.Model): first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) class Meta: ordering=['last_name','first_name'] -
How to style certain tags when condition is met after extending 'base.html'?
I'd like to change the style of all 'select' in my DetailView, but only when certain condition is met (like {% if object.sth == 'sth' %} ). This html is extended from 'base.html' where I already have my css linked, and all 'select' styled. What would be the best approach? It seems I can not link new stylesheet while I'am already in (after extending base.html) -
Django rest fetch data from bridge model
I want to get all the user details and list of all the roles against the user details model My Models class UserDetail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userdetail_user', default='111') cn = models.CharField(max_length=200) sn = models.CharField(max_length=200) u_id = models.CharField(max_length=200) display_name_cn = models.CharField(max_length=200) display_name_en = models.CharField(max_length=200) given_name = models.CharField(max_length=200) employee_number = models.CharField(max_length=200) email = models.CharField(max_length=200) created_at = models.DateTimeField(default=datetime.now, blank=True) last_login = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.given_name class Role(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=200) created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) status = models.BooleanField(default=True) def __str__(self): return self.title class UserRole(models.Model): userdetail = models.ForeignKey(UserDetail, on_delete=models.CASCADE, related_name='userrole_userdetail') role = models.ForeignKey(Role, on_delete=models.CASCADE) approver = models.ForeignKey(UserDetail, on_delete=models.SET_NULL, null=True, related_name='userrole_userdetail_approver') created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) status = models.BooleanField(default=True) My Serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class UserRoleSerializer(serializers.ModelSerializer): class Meta: model = UserRole fields = ('id', 'userdetail', 'role', 'approver', 'last_updated', 'status') depth = 1 def to_representation(self, instance): representation = super(UserRoleSerializer, self).to_representation(instance) representation['userdetail'] = UserDetailSerializer(instance.userdetail).data representation['role'] = RoleSerializer(instance.role).data representation['approver'] = UserDetailSerializer(instance.approver).data return representation class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ('id', 'title', 'description', 'last_updated', 'status') class UserDetailSerializer(serializers.ModelSerializer): user = UserSerializer() roles = serializers.SerializerMethodField(read_only=True) class Meta: model = UserDetail fields = ('id', 'roles', 'user', 'cn', 'sn', … -
Deploying my Django website to Heroku with DEBUG=False doesn't work
When deploying django onto either localhost or heroku with DEBUG=False, it throws an error saying C:\Users\krish\Envs\PRREMIA\lib\site-packages\whitenoise\base.py:105: UserWarning: No directory at: c:\Users\krish\Documents\python\PRREMIA\staticfiles\ warnings.warn(u'No directory at: {}'.format(root)) [28/Jul/2019 16:05:43] "GET / HTTP/1.1" 500 27 When DEBUG=True, it works fine. Why? And how do I stop and fix this? -
Use of `get` for a `select_for_update` query in order to reduce the number of rows getting locked
I would like to know if there is a good solution for this scenario. When a select_for_update is used in a query set, all matching results are locked until the particular block of code has not finished execution. This has become a little critical as simultaneous requests which could be served are being returned back by DatabaseErrors. Below is a sample query for which select_for_update has been implemented qs = Coupons.objects.select_for_update().filter(brand=brand).values('coupon').order_by('id') return qs[0] If we have 1000 coupons for a particular brand, then the entire 1000 rows are locked. I am unable to use get since we are returning the coupons on a FIFO basis and we would need to return coupons which were added first Is there any way I could use get, or minimize the number of rows being locked -
Aggregate related integer-field values in Django template
I have this model which is related to a Node model, class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.related_tree.name In the template when i query a list of the Node's objects i want to aggregate the value of the 'views_count' of each object. I have tried this in my template {% for tree in tree_result|slice:":14" %} {% for view in tree.related_views.all %} {{ view.views_count }} {% endfor %} {% endfor %} i have all the related count_view of the current tree but what i want to do is to aggregate the value of the related field and show it within the for loop of tree_result. Any suggestions please ? -
Django Blog Page not found (404) - No Post matches the given query
I'm coding a blog with Django,There was an error 404 when I click on address http://localhost:8000/blog/2019/7/28/prim-algorithm-path No Post matches the given query. Raised by: blog.views.blog_detail views.py def blog_detail(request,year,month,day,post): print(year,month,day,post) post = get_object_or_404(Post, slug=post, publish__year=year, publish__month=month,publish__day=day) return render(request,'post.html',locals()) blog/urls.py from django.urls import path from .views import index,blog_detail app_name = 'blog' urlpatterns = [ path('', index, name='index'), path('<int:year>/<int:month>/<int:day>/<slug:post>',blog_detail,name='post_detail'), ] mysite/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls',namespace='blog')), ] what should I do -
Python dateparser fails when timezone is in middle
I'm trying to parse a date string using the following code: from dateutil.parser import parse datestring = 'Thu Jul 25 15:13:16 GMT+06:00 2019' d = parse(datestring) print (d) The parsed date is: datetime.datetime(2019, 7, 25, 15, 13, 16, tzinfo=tzoffset(None, -21600)) As you can see, instead of adding 6 hours to GMT, it actually subtracted 6 hours. What's wrong I'm doing here? Any help on how can I parse datestring in this format? -
User api request via app online - api server gets user or app IP adress?
I would like to publish an Django app on Vultr hosting. App (on user request) should connect an api on another server and return data to user. Api has requests limits by IP. When user connect api server via my app, api server will get user IP or my app server IP? If API server will get my app server ip my app will be banned after few request. How to avoid ban and send user ip to API server? Thank you for any help! -
How to save MultipleChoiceField to db
I want to create a settings page where a user can select multiple values of skills they have. It will have a main category and then subcategories. I need to save those into my database, so I can query them and show their selected skillset again. I know how to create the MultipleChoiceField but not how to save them to the database. How would I go on about that? Forms.py from django import forms class skills(forms.Form): jobs = [ ('Håndværker', ( ('Gulv', 'Gulv'), ('Væg', 'Væg'), ) ), ('Murer', ( ('Mur', 'Mur'), ('blabla', 'blabla'), ) ), ] job = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=jobs) Views.py from .forms import skills def index(request): if request.method == 'POST': form = skills(request.POST) if form.is_valid(): picked = form.cleaned_data.get('job') # do something with your results else: form = skills return render(request, 'settings/index.html', {"form":form}) It currently looks like this when the page loads which is good. Next step is just how I would save it to the database, so I can display this again with their previous chosen values. -
Error validating Django formset Modelform?
I am learning to implement Django formset using Modelform and I am getting this formset validation errors relating to my datefield. The error that I am getting is formset [{'from_date': ['Enter a valid date.'], 'to_date': ['Enter a valid date.']}] This is what I have tried so far.What could I be doing wrong ? models.py class WorkExperience(models.Model): company = models.ForeignKey(Company,on_delete=models.PROTECT) from_date = models.DateField() to_date = models.DateField() work = models.ForeignKey(Work,on_delete=models.PROTECT) date_last_modified = models.DateTimeField(auto_now=True) date_added = models.DateTimeField(auto_now_add=True) forms.py class WorkExperienceForm(ModelForm): class Meta: model = WorkExperience fields=('from_date','to_date') def __init__(self, *args, **kwargs): super(WorkExperienceForm, self).__init__(*args, **kwargs) self.fields['name']=forms.CharField( label='Company Name', widget=forms.TextInput(attrs={ 'id': 'company_name', 'class': 'form-control', 'required':True }), ) self.fields['street_address'] = forms.CharField( label='Company Address', widget=forms.TextInput(attrs={ 'id': 'company_address', 'class': 'form-control', 'required': True }), ) self.fields['from_date'] = forms.DateField( input_formats=['%y-%m-%d'], widget=forms.DateInput(format='%d %B, %Y',attrs={ 'id':'to_date', 'class':'form-control'}), required=True, ) self.fields['to_date'] = forms.DateField( input_formats=['%y-%m-%d'], widget=forms.DateInput(format='%d %B, %Y',attrs={ 'id':'to_date', 'class':'form-control'}), required=True, ) self.fields['country'] = forms.ChoiceField(choices=Country.objects.all().values_list('id', 'name')) self.fields['country'].widget.attrs.update({'class': 'btn btn-secondary dropdown-toggle','required':True}) self.fields['project_name'] = forms.CharField( label='Project Name', widget=forms.TextInput(attrs={ 'id': 'project_name', 'class': 'form-control', 'required': True }), required=True, ) self.fields['project_details'] = forms.CharField( label='Project Details', widget=forms.Textarea(attrs={ 'id': 'project_details', 'class': 'form-control', 'required': True }), ) from django.forms import modelformset_factory WorkExperienceFormSet = modelformset_factory( WorkExperience, WorkExperienceForm, extra=1, ) views.py def post(self,request,*args,**kwargs): try: print('fromdate',request.POST['form-0-from_date']) formset = WorkExperienceFormSet(request.POST) print('formset',formset.errors) for form in formset: print('form',form.is_valid()) if … -
How to save a model-instance using serializers in django?
I would like to save a class instance in my database using serializers, provided by DRF. Serializer: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' here I try to save an instance: p = Person(Name = "Test") _srlz = PersonSerializer(data = p) The real case is little bit more complicated, but sanse the same. Unfortunately the data - _srlz.data is empty. So if I try to save data via _srlz.save() method then nothing change. Otherwise if I request an existed object p = Person.objects.filter(id = 1) _srlz = PersonSerializer(data = p) Then my _srlz.data will not be empty. How should I save this object if datasource is not JSON-object, but model-class instance?Should I first serialize it and then deserialize again? I already tried to save instance calling a .save() method, provided by model's default Manager, but I would like to separate my model and service methods so all database operations performed by serializers. Or is it OK in this case, because I deal not with pure JSON, but with model instance? But how can I then validate data? -
How to fix this datetime iso format error in django-python which is occuring since I upgraded my python to 3.7
This is the error that I am facing when I try to run migrate or runserver or any command. Please Help. "raise ValueError(f'Invalid isoformat string: {date_string!r}')" Code -
NoReverseMatch at / on the start of the server
It's giving me an error: NoReverseMatch at / targeting the base.html file (shown in the pic).But the base.html file looks fine to me. Base.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Blog</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- Medium Style editor --> <script src="//cdn.jsdelivr.net/npm/medium-editor@latest/dist/js/medium-editor.min.js"></script> <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/medium-editor@latest/dist/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Montserrat|Russo+One&display=swap" rel="stylesheet"> </head> <body class="loader"> <!-- Navbar --> <nav class="navbar custom-navbar techfont navbar-default"> <div class="container"> <ul class="nav navbar-nav"> <li><a class="navbar-brand bigbrand" href="{% url 'post_list' %}">My Blog</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="https://www.github.com">GitHub</a></li> <li><a href="https://www.linkedin.com">LinkedIn</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a href="{% url 'post_new' %}" >New Post</a></li> <li> <a href="{% url 'post_draft_list' %}" >Drafts</a></li> <li> <a href="{% url 'logout' %}" >Logout</a></li> <li> <a href="#">Welcome: {{user.username}}</a> </li> {% else %} <li> <a href="{% url 'login' %}" class="nav navbar-right"> <span class="glyphicon glyphicon-user"></span> </a> </li> {% endif %} </ul> </div> </nav> <!-- COntent Block --> <div class="content container"> <div class="row"> <div class="col-md-8"> <div class="blog-posts"> {% block content %} {% endblock %} </div> </div> </div> </div> </body> </html> Post_detail.html {% extends 'blog/base.html' %} {% block content %} … -
how to get previous page url in django template?
i am using the django password reset but i want my template to behave differently when it come from password_rest_email and from password_reset_confirm urls.py from django.conf.urls import url,include #from django.urls import path from dappx import views from django.contrib.auth.views import PasswordResetView,PasswordResetDoneView,PasswordResetCompleteView,PasswordResetConfirmView # SET THE NAMESPACE! app_name = 'dappx' # Be careful setting the name to just /login use userlogin instead! urlpatterns=[ url('register/', views.register, name='register'), url('user_login/', views.user_login, name='user_login'), url('google_login/', views.google_login, name='google_login'), url('special/', views.special, name='special'), url('logout/', views.user_logout, name='logout'), url(r'^', include('django.contrib.auth.urls')), url('password_reset/', PasswordResetView.as_view(), name='password_reset'), url('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), url('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] i need that template i.e(password_reset_confirm) to show email is send when it come from password_reset_email and show password reset successful if it come from password_reset_confirm password_reset_complete.html {% extends 'dappx/base.html' %} {% block title %}Check your Email{% endblock %} {% block body_block %} <div class="row no-gutters"> <div class="col-12 col-sm-6 col-md-8"></div> <div class="col-6 col-md-4"> <div class="jumbotron"> <h4>The password reset link has been sent to youre Email</h4> <br> <p>Check your email to reset the password. You can log in now on the <a href="{% url 'dappx:user_login' %}">log in page</a>.</p> <br> </div> </div> {% endblock %} -
Django Data to JsonResponse
I have this model that store all my data. This is my model.py: from django.db import models class Showing(models.Model): movie_id = models.CharField(primary_key=True, max_length=11) movie_title = models.CharField(max_length=100) image_url = models.TextField(blank=True) synopsis = models.TextField(blank=True) rating = models.TextField(default="MTRCB rating not yet available") cast = models.CharField(max_length=100) release_date = models.CharField(max_length=50, blank=True) def __str__(self): return "{}".format(self.movie_id) And I want to retrieve all my data and pass it to context and make a customize JsonResponse like this: "results": [ { "id": "1eb7758d-b950-4198-91b7-1b0ad0d81054", "movie": { "advisory_rating": "PG", "canonical_title": "ROGUE ONE: A STAR WARS STORY", "cast": [ "Felicity Jones", "Donnie Yen", "Mads Mikkelsen" ], "poster_portrait": "", "release_date": "", "synopsis": "Set shortly before the events of Star Wars (1977), Following the foundation of the Galactic Empire, the story will center on a wayward band of Rebel fighters which comes together to carry out a desperate mission: to steal the plans for the Death Star before it can be used to enforce the Emperor's rule. (Source: Disney Pictures)", } }, ] In my views.py I have this function to get all the data, and try just to retrive the movie_id from my model. def show_all_movies(request): movie = Showing.objects.all() context={'result':[{ 'id':movie.movie_id, 'movie': }]} But it gets me an error of 'QuerySet' object … -
how to send pre_save signal only when hit the save button for multiple form in one view (formset)
i trying to send signal only when the user hit the button save class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,default='' ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) @receiver(pre_save , sender=ProductOrder) def create_order(sender, instance, **kwargs): Order.objects.create() if not instance.ordering: instance.ordering = Order.objects.all().order_by('-pk')[0] pre_save.connect(create_order,sender=ProductOrder) forms.py class ProductOrdering(forms.ModelForm): class Meta: model = ProductOrder fields = ['product','ordering','quantity'] ProductFormSet = formset_factory(ProductOrdering , extra=2) i want to make only one id from Order for all forms in the same view , while hit the button ? thanks for advice