Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it necessary to learn database before learning Django? [on hold]
I am new to learn python now i want learn Django, so is it necessary to learn database before going for Django. -
Django name 'request' is not defined while filtering based on users
In Django I am trying to filter some posts based on a user. I have looked it up and found that the way to do it (or the way that was suggested), is to use request.user, but when I do this I get an error saying name 'request' is not defined View: class MyPost(ListView): model = Post template_name = "public/list.html" paginate_by = 3 def get_context_data(self, **kwargs): context = super(MyPost, self).get_context_data(**kwargs) context['post'] = Post.objects.filter(live=True, user=request.user) return context I am unsure if this is the way to do it or not, but I couldn't find anywhere that had good documentation on this. If anyone can help that would be great. -
Append data insted of replace with UpdateView Django
Simple question, whenever I try to update my view, in this case by adding more users UpdateView replaces previous records and add selected one. To avoid that, I need to select those which are already in db and a new one. How to avoid replacing, and append data to db? views.py class AddPersonView(LoginRequiredMixin, UpdateView): model = Trip template_name = 'tripplanner/add_new_member.html' fields = ["profile"] success_url = '/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Keras with tensofrlow error when prediction
I working with sjango and I am trying to predict a image using Keras with tensorflow backend but I have this error : line 3669, in _as_graph_element_locked raise ValueError("Tensor %s is not an element of this graph." % obj) ValueError: Tensor Tensor("dense_6/Softmax:0", shape=(?, 50), dtype=float32) is not an element of this graph. [28/Apr/2019 16:54:53] "POST /facture/upload/ HTTP/1.1" 500 133945 Here is my code : #Loading the model pwd = os.path.dirname(__file__) with open(pwd+'/ModelML/model_architecture19.json', 'r') as f: model = model_from_json(f.read()) # Load weights into the new model model.load_weights(pwd+'/ModelML/model_weights19.h5') roi = cv2.cvtColor(roi,cv2.COLOR_BGR2GRAY) ret2, roi = cv2.threshold(roi, 127, 255, cv2.THRESH_BINARY_INV) roi = cv2.resize(roi, (IMG_SIZE, IMG_SIZE)) # Resize the image roi = roi.reshape(1,IMG_SIZE, IMG_SIZE,1) #normalize image roi = roi /255 graph = tf.get_default_graph() with graph.as_default(): pred =model.predict(roi) The error come from the last line "model predict" Thanks in advance for your help -
How to get the id of a object in Django database
I was watching the new Boston Django tutorials. I know they are older, but he explains them well. I’m having trouble with one thing though . He made a url Url[r’(?P<album_id)[0-9]+] I know in Django 2.0 it’s a better way to do this. That’s not the question His view looks like Def details(request,alblum_id) My question is how does Django know to get the id of the object from album_id if he never declared it. He just typed in a random variable? -
I am new to django and i need help in creating a separate tables for extra field
I have usertype model and schedule model. I need to create add a user-type relation with Student Table where student is enrolled in a specific subject like physics, math. similary In Counseller tables. counseller/teacher have specialty with their major subject. who can counsel in the given shcedule list class UserType(models.Model): user =models.OneToOneField(User, on_delete=models.CASCADE) USER_TYPE = ( (1, 'Student'), (2, 'Counseller'), ) user_type = models.IntegerField(choices=USER_TYPE) class Schedule(models.Model): Schedule_List = ( (1, '10:00 – 11:00'), (2, '11:00 – 12:00'), (3, '12:00 – 13:00'), (4, '13:00 – 14:00'), (5, '14:00 – 15:00'), ) schedule = models.IntegerField(choices=Schedule_List, null=True) user = models.ManyToManyField(User) class Counseller(models.Model): usertype = models.OneToOneField(UserType, on_delete=models.CASCADE) specialty = models.CharField(max_length=20) picture = models.ImageField(upload_to = '', default = '') #return the Counseller' name def __str__(self): return str(self.user) class Student(models.Model): usertype = models.OneToOneField(UserType, on_delete=models.CASCADE) enrolled_sub=models.CharField(max_lenght=20) #return the Students' name def __str__(self): return str(self.user) I need to assign student booking a shcedule with their respective specialty counseller. I want to have patient usertype in patient table with their enrolled subject. and counseller with their specialty fields in counseller table. Also while counselling, science student should be assigned with science counsleller. How can i do that -
Change url after a form submission without using a redirect
Following the submission of a registration form, I want the user to go to a thanks/confirmation page. The registration form is at /register/ and the confirmation page is at /register/confirm/ I understand I can do this like: if register_form.is_valid(): #save data etc. #SCENARIO 1 #go to the confirmation view return register_confirm(request) This displays the confirmation page in the browser, but the actual URL does NOT change from /register/ to /register/confirm/. #SCENARIO 2 #redirect to confirmation view return redirect('register_confirm') This displays the confirmation page in the browser, but the actual URL does NOT change from /register/ to /register/confirm/. #SCENARIO 3 #redirect to URL return redirect('confirm/') This displays the confirmation page in the browser and the actual URL DOES change from /register/ to /register/confirm/ So the scenario in number 3 above does what I want in terms of the users being shown the confirmation page and the URL changing in the browser. (It's important to me that the URL changes in the browser for a few reasons, but not least because I want my analytics to record hits to the confirmation page). However, I really don't think any use of 'redirect' is relevant in this scenario. I simply want to move the … -
Adding SSL to the Django app, Ubuntu 16+, DigitalOcean
I am trying to add my SSL certificate to my django application according to this tutorial. I can turn on my website using 'https://bluedesign.online'. But web browsers return something in style 'The certificate can not be verified due to a trusted certificate authority.' After accepting the messages, my page is displayed correctly. My nginx file looks like this: upstream app_server { server unix:/home/app/run/gunicorn.sock fail_timeout=0; } server { #listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name ebluedesign.online; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/ebluedesign.online/cert.pem; ssl_certificate_key /etc/letsencrypt/live/ebluedesign.online/privkey.pem; keepalive_timeout 5; client_max_body_size 4G; access_log /home/app/logs/nginx-access.log; error_log /home/app/logs/nginx-error.log; location /static/ { alias /home/app/static/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } server { listen 80; listen [::]:80; server_name ebluedesign.online; return 301 https://$host$request_uri; } My certificates are also visible here: /etc/letsencrypt/live/ebluedesign.online/... How can I solve this problem with SSL certificate. I use free SSL by https://letsencrypt.org/. -
Django model polymorphic related field
I am trying to remove duplicate code within my Django models. As you can see in the code below, the only difference between send_salary_notification and send_pension_notifications is that one uses the related field jurisdiction and the other uses agency. How can I refactor the code so that jurisdiction/agency is set once, based off record_type? I tried creating a class variable as record_type, and in that first function set the variable with cls.record_type = record_type, then this: agencies_changed.append(subscription.record_type) But that gives an error that record_type is not a valid instance. Here is my code: class Subscriber(models.Model): email = models.EmailField(null=False, unique=True) activation_key = models.CharField(max_length=64) key_expires = models.DateTimeField(default=get_key_expiration) verified = models.BooleanField(default=False) @classmethod def send_notifications(cls, record_type, slugs): """ Sends notifications for all subscribers. """ subscribers = cls.objects.all() for subscriber in subscribers: if record_type == 'salary': subscriber.send_salary_notifications(slugs, record_type) elif record_type == 'pension': subscriber.send_pension_notifications(slugs, record_type) def send_salary_notifications(self, slugs, record_type): matching_subscriptions = self.get_matching_salary_subscriptions(slugs) agencies_changed = [] if not matching_subscriptions: return None for subscription in matching_subscriptions: agencies_changed.append(subscription.jurisdiction) self.update_salary_last_year_sent(subscription) message = self.build_notification_message(agencies_changed, record_type) self.send_notification_email(message) def send_pension_notifications(self, slugs, record_type): matching_subscriptions = self.get_matching_pension_subscriptions(slugs) agencies_changed = [] if not matching_subscriptions: return None for subscription in matching_subscriptions: agencies_changed.append(subscription.agency) self.update_pension_last_year_sent(subscription) message = self.build_notification_message(agencies_changed, record_type) self.send_notification_email(message) class SalarySubscription(models.Model): subscriber = models.ForeignKey('subscriptions.Subscriber', related_name='salary_subscriptions') jurisdiction = models.ForeignKey('jurisdiction.Jurisdiction') … -
I can not get the user id logged in
trying to grab the user id and save it to the form, but it only goes into the else views.py def comments(request): if request.method == 'POST': form = CommentsForm(request.POST) if form.is_valid(): form = form.save() form.user = request.user.pk form.comments.comments = form.cleaned_data.get('comments') form.comentario.number = form.cleaned_data.get('number') return redirect('profile') else: form = CommentsForm() return render(request, 'comments/profile.html', {'form': form}) -
Incomplete media url in nested serializers
I have a django-rest-api application with models Record, Tag and Weight, where Record and Tag have many-to-many relation through the Weight model: # models.py class Tag(models.Model): image = models.ImageField(upload_to='tag_images', null=True, blank=True) class Record(models.Model): file = models.FileField(upload_to='record_files', null=True, blank=True) class Weight(models.Model): record = models.ForeignKey( Record, related_name='weights', on_delete=models.CASCADE ) tag = models.ForeignKey( Tag, related_name='weights', on_delete=models.CASCADE ) value = models.IntegerField() class Meta: unique_together = ('record', 'tag',) Both Record and Tag models have a FileField/ImageField parameter. In my REST API view I would like to display Record detail with its full file url and all related Tags with their full image url. This is how my serializers look like: # serializers.py class RecordSerializer(serializers.ModelSerializer): tags = serializers.SerializerMethodField() class Meta: model = Record fields = ('id', 'file', 'tags') def get_tags(self, obj): return TagSerializer(Tag.objects.filter(weights__in=obj.weights.all()), many=True).data class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('id', 'image') The problem is that when I see record detail view its file url is complete but tag image urls are not: # record detail results { "id": 1, "file": "http://127.0.0.1:8080/media/record_files/record00.mp3", "tags": [ { "id": 4, "image": "/media/tag_images/image04.jpg" }, { "id": 10, "image": "/media/tag_images/image10.jpg" } ] } In the end I have bypassed the problem by creating a separate tag list view … -
How to have multiple values in django render to string
I have a email template that I want to pass values in to. This I achieve by the following code. I wish to know how to pass 2 variables that way subject = request.POST.get('inq_sub') message = request.POST.get('inq_mes') html_content = render_to_string('customer_inquiry.html',{'subject': subject}) -
Django creates persistent connections on startup even though CONN_MAX_AGE is set to 0
We recently had the MySQL Server has gone away error. After a week of debugging we found out that Django was creating a few persistent connections on startup even though our CONN_MAX_AGE was 0(has always been 0). The queries that were running on startup were queries from django-simple-history and a few queries on class level of modelforms. Since these forms were somehow making it to the imports of the urls hence these queries were being executed on all calls(I know very bad we fixed this). Now the weird behavior was as follows. on Startup these class level queries and the queries from django-simple-history would create connections to MySql but they would be persistent connections. Several queries were being run on these connection(s) during startup. Now after startup all queries would create their connections apart from the queries from the modelforms. They would come back and try to connect using the old connections. How we got the error was that if the application was idle for the wait_timeout of MySql. MySql would terminate these connections and django would try to query using the same connection hence the "MySQL server has gone away" We did move the class level queries to instance … -
Is it possible to pass a variable as a CSS class to a Django html template?
Pretty much a Django any Python noob - been studying for a month or so and watching tutorials...so I know enough to be dangers. I'm trying to randomize the CSS class in an HTML template. I'm using a custom Bootstrap template to display database entries as cards, and I want to randomize the background. I've got the basics down, but haven't been able to figure out how to randomize the CSS class value in the actual html template. I've tried the randomizing the value in the relevant Django views template. Searched through 2.2 docs, stack, google, etc., but so far no joy views.py: import random from django.shortcuts import render from compliments.models import Compliments def compliment(request): compliment = Compliments.objects.all() return render(request, 'compliments/home.html', {'compliment': compliment}) classList = [ 'bg-secondary', 'bg-success', 'bg-danger', 'bg-warning', 'bg-info', 'bg-light', 'bg-dark' ] css_class = random.choice(classList) my HTML: {% extends 'base.html' %} {% block body %} <div class="row"> <div class="col-12"> <h4 class="mb-4">Compliments</h4> </div> <!-- end col --> </div><!-- end row --> <div class="row"> {% for compliment in compliment %} <div class="col-md-4"> <div class="card {{ compliment.css_class }} text-white"> <div class="card-body"> <p class="card-text">{{ compliment.body }}</p> <a href="javascript: void(0);" class="btn btn-primary btn-sm">Select</a> </div> <!-- end card-body--> </div> <!-- end card--> </div> <!-- … -
How to filter a queryset with a many many to field object in django?
I am creating an app in which I can display user properties but the problem that I am facing is creating specific property categories. For e.g If a user clicks Condour Apartment then only those properties should be displayed. I wanna know how we can display on those properties which are connected by that category title. Here's the models.py for properties and category class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Property(models.Model): title = models.CharField(max_length = 210,default = 'None') STATUS_CHOICES = ( ('R','Rent'), ('S','Sale'), ) status = models.CharField(max_length = 210,choices = STATUS_CHOICES,default = 'None') price = models.IntegerField() area = models.CharField(max_length = 210,default = 'None') ROOM_CHOICES = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('MORE','More'), ) rooms = models.CharField(max_length = 210,choices = ROOM_CHOICES,default = 'None') BATHROOM_CHOICES = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ) bathroom = models.CharField(max_length = 210,choices = BATHROOM_CHOICES,default = 'None') address = models.CharField(max_length = 210,default = 'None') state = models.CharField(max_length = 210,default = 'None') code = models.CharField(max_length = 210,default = 'None') images = models.ImageField(upload_to = 'images',) info = models.TextField(max_length = 1000,default = 'None') parking = models.BooleanField(default = False) air = models.BooleanField(default = False) swimming = models.BooleanField(default = False) laundry = models.BooleanField(default = False) dealer_name = models.CharField(max_length = 210,default = … -
Joining 2 lists Django
I have 2 ArrayField lists and I want to join them using the zip method so I can Iterate through two lists in Django my django templates. But the output is treating each as array as seperate lists. my model class programas(models.Model): title = models.CharField(unique=True, max_length=250) script = ArrayField(models.CharField(max_length=8000, blank=True)) created_on = models.DateTimeField() show_date = models.CharField(max_length=300, blank=True, null=True) script_eng = ArrayField(models.CharField(max_length=8000, blank=True)) description = models.CharField(max_length=2000, blank=True, null=True) description_eng = models.CharField(max_length=2000, blank=True, null=True) url = models.CharField(max_length=200, blank=True, null=True) show_id = models.IntegerField(primary_key=True) id = models.IntegerField(null=True) my view where I try to join the lists def pages(request, id): obj = programas.objects.get(id=id) script = programas.objects.values_list('script') script_eng = programas.objects.values_list('script_eng') zip_scripts = list(zip(script , script_eng)) context = {'title': obj.title, 'show_date': obj.show_date, 'script' : obj.script, 'script_eng': obj.script_eng, 'description': obj.description, 'description_eng': obj.description_eng, 'show_id':obj.show_id, 'url': obj.url, 'zip_scripts' : zip_scripts, } return render(request, 'rtves/pages.html', context) my code on the template page {% if script %} {% for text1, text2 in zip_scripts %} <p> {{ text1 }} </p> <p> {{ text2 }} </p> {% endfor %} {% else %} <p>Nothing here</p> {% endif %} Have I got to make changes in the database? -
Django Channels NOT NULL constraint failed: chat_chatmessage.message
I am trying to finalize the notifications system in my Django Channels application. When I send a message or a string of text through the websocket, websocket.recieve will generate a load of empty strings after the initial message is sent. 127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECTING /messages/trilla" - - connected {'type': 'websocket.connect'} 127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECT /messages/trilla" - - receive {'type': 'websocket.receive', 'text': '{"message":"hi there"}'} websocket.receive receive {'type': 'websocket.receive', 'text': '{"message":""}'} websocket.receive receive {'type': 'websocket.receive', 'text': '{"message":""}'} websocket.receive receive {'type': 'websocket.receive', 'text': '{"message":""}'} websocket.receive The navbar has a JS script which adds new notifications. An html string is constructed from the server message and then inserted to the page html. I am getting NOT NULL constraint failed: chat_chatmessage.message when I click on the navbar notification icon. I assume because of the empty string problem generating a load of empty messages. This is the log when I click on the notification icon receive {'type': 'websocket.receive', 'text': '{"type":"notification_read","username":{},"notification_id":{"jQuery33100053785670652706231":{"display":""}}}'} websocket.receive 2019-04-28 11:59:47,041 ERROR Exception inside application: NOT NULL constraint failed: chat_chatmessage.message It's clear the data is not getting passed properly. I followed a tutorial for the Django Channels portion and had no experience with JS / WebSockets before trying to do this so … -
what is wrong is here?
File "/Users/user/Desktop/Dp1/simplesocial/groups/views.py", line 24 messages.warning(self.request=,('Warning already a member!')) SyntaxError: invalid syntax from django.shortcuts import render from django.contrib.auth.mixins import (LoginRequiredMixin,PermissionRequiredMixin) from django.urls import reverse from django.views import generic from groups.models import Group,GroupMember from django.shortcuts import get_object_or_404 from django.contrib import messages # Create your views here. class CreateGroup(LoginRequiredMixin,generic.CreateView): fields = ('name','description') model = Group class SingleGroup(generic.DetailView): model = Group class ListGroups(generic.ListView): model = Group class JoinGroup(LoginRequiredMixin,generic.RedirectView): def get_redirect_url(self,*args,**kwargs): return reverse('groups:single',kwargs={'slug':self.kwargs.get('slug')}) def get(self,request,*args,**kwargs): group = get_object_or_404(Group,slug=self.kwargs.get('slug')) try: GroupMember.objects.create(user=self.request.user,group=group) except IntegrityError: messages.warning(self.request=,('Warning already a member!')) else: messages.success(self.request,'You are now a member!') return super().get(request,*args,**kwargs) class LeaveGroup(LoginRequiredMixin,generic.RedirectView): def get_redirect_url(self,*args,**kwargs): return reverse('groups:single',kwargs={'slug':self.kwargs.get('slug')}) def get(self,request,*args,**kwargs): try: membership = models.GroupMember.objects.filter(user=self.request.user,group__slug=self.kwargs.get('slug')).get() except models.GroupMember.DoesNotExist: messages.warning(self.request,'Sorry you are not in this group!') else: membership.delete() messages.success(self.request,'You have left the group!') return super().get(request,*args,**kwargs) -
django_podcasting migrattion: TypeError: __init__() missing 1 required positional argument: 'on_delete'
I am using django-podcasting in a django project [2.0.8] project. When I run python manage.py makemigrations, I get the following stacktrace: (site-env) me@YOURBOX:~/Projects/dev/mysite$ python base_app/manage.py makemigrations Traceback (most recent call last): File "base_app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/path/to/proj/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_comman d_line utility.execute() File "/path/to/proj/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/path/to/proj/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/path/to/proj/env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/path/to/proj/env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/path/to/proj/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/path/to/proj/env/lib/python3.6/site-packages/podcasting/models.py", line 103, in <module> class Show(models.Model): File "/path/to/proj/env/lib/python3.6/site-packages/podcasting/models.py", line 128, in Show help_text=_("""Make certain the user account has a name and e-mail address.""")) TypeError: __init__() missing 1 required positional argument: 'on_delete' -
How can I store my session storage to redis using django?
I currently have my session storage in my db (postgreSql) and now I am moving towards redis to store the session data I currently used redis for Django Cacheing Backend. Using, the package django-redis-cache, this is currently what I have come upto in my settings.py file. MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", 'django.middleware.cache.FetchFromCacheMiddleware' ] SESSION_ENGINE = 'django.contrib.sessions.backends.cache' CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'localhost:6379', 'OPTIONS': { 'DB': 1, }, }, } I expect the redis server to be used as a session storage. -
How to request user data from facebook open graph?
I want to write an app where user can login by facebook and request his data from facebook open graph? Are there any plugins, manuals useful for this task? -
Django-ajax-selects with AJAX_SELECT_BOOTSTRAP = False
At work we are using django-admin webapp. I wanted to implement django-ajax-selects functionality to some of fields. Our network is isolated from Internet and I cannot use django-ajax-selects's CDNs. Documentation says that in such case you should set AJAX_SELECT_BOOTSTRAP to False in settings.py file. However, when I set this parameter, django-ajax-selects fails to use django's jquery. Django's version is 1.11.10, Python2. Steps to reproduce my issue: pip install django==1.11.10 django-ajax-selects django-admin startproject proj ./ python manage.py startapp test_app python manage.py migrate python manage.py createsuperuser test_app/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Tag(models.Model): name = models.CharField(max_length=100) something = models.CharField(max_length=100) def __str__(self): return self.name class SecondModel(models.Model): name = models.CharField(max_length=200) tag = models.ForeignKey(Tag, on_delete=models.CASCADE) def __str__(self): return self.name test_app/lookups.py from ajax_select import register, LookupChannel from .models import Tag @register('tags') class TagsLookup(LookupChannel): model = Tag def get_query(self, q, request): return self.model.objects.filter(name__icontains=q) def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.name **test_app/admin.py # -*- coding: utf-8 -*- from django.contrib import admin from ajax_select import make_ajax_form from .models import Tag, SecondModel @admin.register(Tag) class TagAdmin(admin.ModelAdmin): fields = ['name', 'something'] @admin.register(SecondModel) class SecondModelAdmin(admin.ModelAdmin): form = make_ajax_form(SecondModel, { 'tag': 'tags' }) proj/settings.py - adding the app and ajax_select to INSTALLED_APPS INSTALLED_APPS = … -
how to search all the data of app from one search form in django?
In the main homepage i have a search form which searchs all the data student,course,teacher and users of this app and for this i have done this.This works fine .But if student and teacher have the same name then it only gives the result for one either student or teacher.Is there any other method to search all the data of student,course,teacher and users of app through only one search form.?? And also this icontains method is giving the case sensitive data.It is behaving like the exact method ,i am using mysql for the database. views.py def searchall(request): q = request.GET.get('q') if q: courses = Course.objects.filter(title__icontains=q) students = Student.objects.filter(name__icontains=q) teachers = Teacher.objects.filter(name__icontains=q) users = User.objects.filter(username__icontains=q) if courses: return render(request,'students/view_course.html',{'courses':courses}) elif students: return render(request,'students/view_students.html',{'students':students}) elif teachers: return render(request,'students/view_teacher.html',{'teachers':teachers}) elif users: return render(request,'students/view_users.html',{'users':users}) else: messages.info(request, 'no results found for {}'.format(q)) return redirect('students:home') else: return request('students:home') template <li class="search-box"> <a class="nav-link hidden-sm-down" ><i class="iconsmind-Magnifi-Glass2"></i></a> <form class="app-search" style="display: none;" action="{% url 'students:search_all' %}"> <input type="text" name="q" class="form-control" placeholder="Search &amp; enter"> <a class="srh-btn"><i class="ti-close"></i></a> </form> </li> -
Get url argument to process generic views
I would like to write a one-template view, which depending on the url path will show different field of the model. So for instance if path is http://127.0.0.1:8000/trip/2/1/ I will get second trip from my db (that works), and 1 should give (as html is written) a description field. I don't know how to process this to context_processor in my view. Do you have any ideas? views.py class TripDescriptionCreate(LoginRequiredMixin, UpdateView): model = Trip template_name = 'tripplanner/trip_arguments.html' fields = ["description", "city", "country", "climate", "currency", "food", "cost", "comment", "accomodation", "car", "flight", "visa", "insurance", "remarks"] context_object_name = 'trips' success_url = '/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) trip_arguments.html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">{{ trips.tripName }}</legend> {% if field_id == 1 %} {{ form.description|as_crispy_field }} {% elif field_id == 2 %} {{ form.city|as_crispy_field }} {% endif %} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> urls.py path('trip/<int:pk>/<int:field_id>', TripDescriptionCreate.as_view(), name='trip-fullfill'), -
NOT NULL constraint failed: accounts_user profile.user_id
HI i trying to save the user profile information but keep get error and i'm new django this my form.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UserProfile class RegistrastionForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: proxy = True model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) help_texts = { 'username' : 'Your username cannot contain spaces and must cannot exceed 10 characters. You can use letters, digits and @/./+/-/_ only.' } def save(self,commit=True): user = super(RegistrastionForm,self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('surname', 'initial', 'given', 'title', 'street', 'suburb', 'state', 'postcode', 'phone', 'mobile', ) def save(self,commit=True): user = super(RegistrstionForm,self).save(commit=False) user.surname = cleaned_data['surname'] user.initial = cleaned_data['initial'] user.given = cleaned_data['given'] user.title = cleaned_data['title'] user.street = cleaned_data['street'] user.suburb = cleaned_data['subrub'] user.state = cleaned_data['state'] user.postcode = cleaned_data['postcode'] user.phone = cleaned_data['phone'] user.mobile = cleaned_data['mobile'] if commit: user.save() return user class EditProfileForm(UserChangeForm): class Meta: model = UserProfile fields = ('surname', 'initial', 'given', 'title', 'street', 'suburb', 'state', 'postcode', 'phone', 'mobile', 'password' ) help_texts = { 'password' : 'This information cannot be changed. You will need to contact …