Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add login/logout functionality and improve the code?
I am trying to make a school management system.I am trying to add login/logout functionality on the Person model so that student, guardians and staffs can login. Also I don't want to create another class for teachers. I wonder if we can add a Department field on Staff when the Staff_Type is teacher.And any other improvements are also welcomed. from django.db import models from . import constants # I will create class and subjects field later. class Location(models.Model): current_address = models.CharField(max_length=512) permanent_address = models.CharField(max_length=512) class Person(models.Model): Name = models.CharField(max_length=200) Sex = models.CharField(max_length=1, choices=constants.SEX_CHOICES) Nationality = models.CharField(max_length=20, choices=constants.NATIONALITY) BirthDate = models.DateField('Date of birth') Email = models.EmailField(max_length=200) Telephone = models.CharField(max_length=14) CellPhone = models.CharField(max_length=14) class Guardian(Person): pass class Student(Person): guardians = models.ManyToManyField(Guardian, db_table='Student_Guardian_Bridge') Address = models.ForeignKey(Location, on_delete=models.CASCADE) class Staff_Type(models.Model): type_of_staff = models.CharField(max_length=50) def __str__(self): return self.type_of_staff class Staff(Person): staff_type = models.ForeignKey(Staff_Type, on_delete=models.PROTECT) Salary = models.IntegerField() guardians = models.ManyToManyField(Guardian, db_table='Staff_Guardian_Bridge') Address = models.ForeignKey(Location, on_delete=models.CASCADE) -
'Matrix' object has no attribute 'profile_set'
I have been struggling with this problem for an hour. I have searched everywhere but I can't find a solution to this. Maybe my problem is different. Will you kindly help me figure out whats wrong. I am stuck class Matrix(models.Model): code = models.CharField(max_length=6) count = models.IntegerField() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) country = models.CharField(max_length=100) phone = models.CharField(max_length=12) level = models.IntegerField(default=0) #Parent matrix parentmatrix = models.ForeignKey(Matrix, on_delete=models.CASCADE, related_name='parentmatrix') #Child matrix childmatrix = models.ForeignKey(Matrix, on_delete=models.CASCADE, related_name='childmatrix') -
i'm unable to run server due to this error i check every thing ,please help" 'urls.py'>' does not appear to have any pattern'"
error raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'p.urls' from 'D:\pylearn\dt\dtapp\ then the issue is probably caused by a circterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.news), ] views.py from django.shortcuts import render from django.http import HttpResponse def news(request): return HttpResponse ("n iuri u iou") urls.py(django) from django.contrib import admin from django.conf.urls import url,include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^dtapp/', include('dtapp.urls')) ] -
I've added extra functionalities in the Django admin view but i can't see the changes
I have a Django application deployed in a Google App Engine. I've added a button in the Django Admin panel to import a CSV file and it works properly on localhost, but in production i can't see the button. Django Admin (Localhost) I've collected the statics but I don't really know if this affects to the admin html templates... thoughts? -
changing debug to false causes styles not work
when I change DEBUG = False my page CSS styles not work. also, I set allowed hosts but no difference made. ALLOWED_HOSTS = ['localhost'] I use djngo2.2 and here is part of my setting.py: DEBUG = False ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'matab', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'labsolutions.urls' TEMPLATE_DIR= os.path.join(BASE_DIR,'media/template/') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'labsolutions.wsgi.application' STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR,'media/static/'), ) STATIC_ROOT = os.path.join(BASE_DIR,'statcifiles') -
Django Admin Show / Hide Fields if Specific Value is Selected in a Dropdown Not Working
Before anyone marks it as duplicate and closes, here is Link to Old Thread Now, I implemented same steps except I am using CharFields in place of DateFields shown by @Jarad but I am not able make those 2 fields hidden when the choices are any but "Custom", there are no error shown, seems to me like the JS is getting loaded but not executed and since I want those (Char) fields dynamically populated from db later for my project, I am using postgres sql for storage. -
how to use PasswordChangeView django 2.2
i've to try make a change password page with Django.contrib.auth.views.PasswordChangeView like: [views.py] class ChangePasswordView(LoginRequiredMixin, PasswordChangeView): template_name = 'accounts/password_change.html' success_url = reverse_lazy('account:password_change_done') class ChangePasswordDoneView(LoginRequiredMixin, PasswordChangeDoneView): template_name = 'accounts/password_change_done.html' with url like : [urls.py] path('profile/update/password/', views.ChangePasswordView.as_view(), name='password_change'), path('profile/update/password/success/', views.ChangePasswordDoneView.as_view(), name='password_change_done'), i use custom user, but i look the source code, django get the user by request.user so its not be a problem if i use the custom user. but why my change password not work, if i change the password with right old password and new password the form return the success page but not changing my password. and i try to use worng password in old password but always return the success page. whats the problem ? thanks before, -
Sending Status code in json format in Django
I have to send the error status code or the success status code in json format same as the one which we recieve on the local terminal For eg : [23/Dec/2019 10:16:04] "GET /group/ HTTP/1.1" 200 1121 [23/Dec/2019 10:16:06] "POST /group/ HTTP/1.1" 500 61 How can I do this or what should be my code in the views.py I am quite new to this so thanks for all the help!! -
"AttributeError: 'tuple' object has no attribute 'get' " on django application
I couldn't able to figure out where the error is from in my django application. Internal Server Error: /app/register/ Traceback (most recent call last): File "/home/stokesy/Desktop/MyDjangoEnv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/stokesy/Desktop/MyDjangoEnv/lib/python3.7/site-packages/django/utils/deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "/home/stokesy/Desktop/MyDjangoEnv/lib/python3.7/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'tuple' object has no attribute 'get' views.py: from django.shortcuts import render from basic_app.forms import UserProfileInfoForm,UserForm Create your views here. def index(request): return render(request,'basic_app/index.html') def register(request): registered = False if request.method == "POST" : user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES : profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else : print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'basic_app/registration.html'),{'user_form':user_form,'profile_form':profile_form,'registered':registered} -
Building a schedule event
I want to build a similar event schedule to that one : https://websummit.com/schedule and include it in a webapp using django. I got a bit closer using pure JS + Vuejs + Bulma + Bootstrap. It got so complicated though and some basic functionalities were tough to add (like tabs, horizontal & vertical scrolling with fixed head & index, drag & scroll horizontally, drag & drop events..). Besides, the fact that Bulma and Bootstrap were used in the same time prevents some functionalities from working (like Bootstrap Modals doesn't work properly when using bulma). Any suggestions of how can I build that kind of schedule in a "cleaner" way ? (and if I could use only one framework: VueJS / Bootstrap / Bulma/ Pure JS..) PS: I only use pure JS and VueJS. Still didn't learn other JS frameworks -
Nginx/Daphne/WebSocket connection to failed: Error during WebSocket handshake: Unexpected response code: 404
so I am using Ubuntu 18.04.3 LTS, Django 3.0.0, Python 3.6, Nginx, Daphne, docker, Channels for a chat project on AWS EC2 instance. I started a project like the tutorial from Channels. I'm trying to build websocket connection via wss protocol. Everything works great when host is http and websocket connection is ws protocol. But error if host is https and websocket connection is wss protocol. The error as below. (index):16 WebSocket connection to 'wss://mydomain/ws/chat/1/' failed: Error during WebSocket handshake: Unexpected response code: 404 I'm running my django aspi app by Daphne. Here's how I run my app server: daphne -u /home/ubuntu/virtualenvs/src/werewolves/werewolves.sock werewolves.asgi:application Here's my nginx setting: upstream websocket { server unix:/home/ubuntu/virtualenvs/src/werewolves/werewolves.sock; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name mydomain; location = /favicon.ico { access_log off; log_not_found off; } location ^~ /static/ { autoindex on; alias /home/ubuntu/virtualenvs/static/static-only/; #STATIC_ROOT } # SSL settings ssl on; listen 443 ssl http2; listen [::]:443 ssl http2 default_server; ssl_certificate /etc/letsencrypt/live/mydomain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mydomain/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/mydomain/fullchain.pem; ssl_session_timeout 10m; ssl_session cache shared:SSL:1m; location / { # proxy setting for django using wsgi include proxy_params; #proxy_pass 0.0.0.0:8000; proxy_pass websocket; # CORS config. settings for using AWS S3 serving static file set … -
sender, *args and **kwargs are not active "parameter value is not used" in pycharm
in views.py def get(self, *args, **kwargs): and in models.py def userprofile_receiver(sender, instance, created, *args, **kwargs): if created: userprofile = UserProfile.objects.create(user=instance) *args, **kwargs, sender, and userprofile are dark since I got (RelatedObjectDoesNotExist, User has no userprofile.) -
Is it possible to integrate React with django?
What is the need of integrating React Js with Django? How to do that? What is the advantage of using react over ajax with django? -
Create a string that contains values from related objects to display in view
I'm new to Django so please bear with me. I'm trying to create a view which lists JournalEntries. The list needs to include selected values from the LineItems that are related to each JournalEntry. I'm struggling to create a string that I can pass to my template that has this information. models.py class JournalEntry(models.Model): date = models.DateField(null=True, blank=False) class LineItem(models.Model): journal_entry = models.ForeignKey(JournalEntry, on_delete=models.PROTECT) ledger = models.ForeignKey(Ledger, on_delete=models.PROTECT) description = models.CharField(max_length=255, null=True, blank=True) cr = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) dr = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) class Ledger(models.Model): name = models.CharField(max_length=255) This is my attempt which doesn't work at all: views.py def journalentries_show_all(request): journal_entries = JournalEntry.objects.all() for count,string in enumerate(journal_entries): string[count].account_ledger = string.lineitem_set['0'].ledger string[count].expense_ledger = string.lineitem_set['1'].ledger string[count].description1 = string.lineitem_set['0'].description string[count].description2 = string.lineitem_set['1'].description context = { 'journal_entries': string, } return render(request, 'journal/journalentries_show_all.html', context) In this particular view I'm only interested in displaying information from the first two related LineItems. Other views will deal with JournalEntries that have more than two LineItems. -
Django : Updating row data in sqlite without reloading page
I am displaying a random image from the database. After the image is displayed, it's count should be set to 1 the moment it gets displayed so it is not used again. I have tried to write a view function which tries to change the count when the image is selected for display. There is no update form or button click involved. views.py from django.shortcuts import render from django.conf import settings from .models import Image import random # Create your views here. def index(request): y= random.randint(0,10) p = Image.objects.all()[y] if (p.p_image_count==0): p_img = Image.objects.all()[y] Image.objects.all()[y].p_image_count += 1 # Image.save(self) lst = [p.s_image1, p.s_image2, p.s_image3, p.s_image3, p.s_image4, p.s_image5] x = random.randint(0,4) tmp =[] for i in range(0,3): p = Image.objects.all()[random.randint(0,14)] tmps=[p.s_image1, p.s_image2, p.s_image3, p.s_image3, p.s_image4, p.s_image5] tmp.append(tmps[random.randint(0,4)]) s_img = [lst[x]]+ tmp random.shuffle(s_img) return render(request,'index.html',{"p_img":p_img, "s_img": s_img, 'media_url':settings.MEDIA_URL})``` models.py - Image model class Image(models.Model): p_image = models.ImageField(max_length=255,upload_to='p_image',default='NULL', blank='NULL') p_image_count = models.IntegerField(default=0) s_image1 = models.ImageField(max_length=255,upload_to='s_image') s_image1_flag = models.BooleanField(default=False) s_image2 = models.ImageField(max_length=255,upload_to='s_image',default='NULL', blank='NULL') s_image2_flag = models.BooleanField(default=False) s_image3 = models.ImageField(max_length=255,upload_to='s_image',default='NULL', blank='NULL') s_image3_flag = models.BooleanField(default=False) s_image4 = models.ImageField(max_length=255,upload_to='s_image',default='NULL', blank='NULL') s_image4_flag = models.BooleanField(default=False) s_image5 = models.ImageField(max_length=255,upload_to='s_image',default='NULL', blank='NULL') s_image5_flag = models.BooleanField(default=False) #if image displayed currently , set flag to true -
Django + Celery Beat: Unable to call GET request in Celery task
I am trying to do the following in my Django application: Make an API call, with the response returned in a CSV format. Attach the CSV file to an email, which will be sent using Django's EmailMessage object. When implementing the above logic in my Views, I was successfully able to attach the CSV file to the email, with the contents of the CSV file intact. Below is the code from views.py: response = requests.get('https://a.b.c.d:e/.../', auth=HTTPBasicAuth(user, pwd), verify=False) # Using Django-Templated-Email library email = get_templated_mail( template_name='test.email', from_email='example@example.com', to=['example@example.com'], context={}, ) email.attach('test.csv', response.content, 'text/csv') email.send() However, when trying to implement the above code in Celery, I am only able to receive the email with the attachment, with no contents in the CSV file (i.e. the CSV file is empty when it should be populated with information). Below is the code from tasks.py: @shared_task def send_email(): # using the exact code as above The code is called in another function in tasks.py using the django-celery-beat library: @shared_task def before_send_email(): PeriodicTask.objects.update_or_create( interval=schedule, name='test_schedule', task='app.tasks.send_email', args=json.dumps([...]), ) This is my settings for Celery in the settings.py file: CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672' CELERY_RESULT_BACKEND = 'amqp://guest:guest@localhost:5672' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Any help … -
Is collectstatic command necessary if application only serves media files?
A Django-based service that I'm working on allows users to upload media files via REST API or Django admin but does not provide or use any static files (like css styles, js libraries, etc.). Media files are stored in specific fields in database and use S3 bucket as storage backend so server itself does not directly serve any files at all. Having such a case is running collectstatic command required every time application is being deployed? Thought the concept of static and media files in Django application is rather simple I'm still confused about whether configurations for them should be somehow related? -
Django Models Maintain History of Related fields
How can I maintain the history of a Model as well as its related_fields ?? For Eg: ====Contact==== | name | =============== ====ContactPhone====== | contact <ContactID> | | number | ======================= I want to maintain revisions of Contact, even if the ContactPhone changes. Is there any way? P.S. I know https://django-simple-history.readthedocs.io/en/latest/ but it is for only one model. I'm having a problem with managing related fields for a revision. -
How to create generic relationships with inheritance?
I have structure something like this: A Campaign can contain multiple Action. Every Action should related to a campaign. There is different type of action, such as Email, Web hook etc.. Common point of these actions is "run" method. When I run campaign's run method, the actions related to the campaign should run too. I think something like this will work for me: class Campaign(models.Model): def run(self, data): for action in self.actions: action.run(data) class Action(models.Model): name = models.CharField(max_length=32) campaign = models.ForeignKey( Campaign, on_delete=models.CASCADE, related_name='actions', ) def run(self, data): print(f'The {self.name} action ran.') print(f'Data: {data}') class EmailAction(Action): subject = models.CharField(max_length=128) body = models.TextField() def run(self, data): super(EmailAction, self).run(data) class WebhookAction(Action): url = models.CharField(max_length=256) body = models.TextField() def run(self, data): super(WebhookAction, self).run(data) What is the best way to achieve this workflow? -
Creating choices from admin page
I am trying to make a school management system with django. I want to add 'staff_type' field in the 'staff' model. On the front end, that will be selected from a dropdown menu. But I don't want to hardcode the choices. I want to add the choices from the admin page. How can I do that with django? ''' from django.db import models #this is over-simlified. class person(models.model): name = models.Charfield(max_length =100) class staff(person): staff_type = models.Charfield(max_length =20) ''' -
How to create a registration form in Django that is divided into two parts, such that one call fill up the second part only after email verification?
I have the logic for email verification, but I am not sure how to make it such that only after clicking the link on the verification email, the user is taken to the second page of the form, and only after filling the second part the user is saved. -
Celery Signals vs Django Signals
Are celery signals asynchronous unlike django signals that are synchronous? Just curious for instance task_success signal from celery vs post_save signal from django. -
Authentication and Authorization with Django GraphQL JWT and Graphene Relay
I would like to ask how I can do authentication and query tags limited to a specific user (owner) using Graphen Relay and Django JWT Here is my Model: class Tag(models.Model): """Tag to be used for a objective""" name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='tag', on_delete=models.CASCADE, ) Here is my Schema code: TagNode: class TagNode(DjangoObjectType): class Meta: model = Tag filter_fields = ['name'] interfaces = (relay.Node,) Here is my query: class Query(graphene.ObjectType): tag = relay.Node.Field(TagNode) all_tags = DjangoFilterConnectionField(TagNode) def resolve_all_tags(self, info): # context will reference to the Django request print(info.context.user) if not info.context.user.is_authenticated: return Tag.objects.none() else: return Tag.objects.filter(user=info.context.user) Here is the document for Django JWT: https://github.com/flavors/django-graphql-jwt but I do not know how to get the user (already use info.context.user) but it does not work, when I tried to add Authorization (JWT token) in the header or as argument. It also does not work. Thanks -
quote_from_bytes() expected bytes
I'm nebie. I do not have any idea what does this error mean. I'm getting this error while creating saving stripe card on userprofile model. views.py class PaymentStripe(LoginRequiredMixin, View): def get(self, *args, **kwargs): order = get_object_or_404(Order, user=self.request.user, ordered=False) if order.billing_address: context = {'order': order, 'coupon': CouponForm, 'display_coupon_form': False} userprofile = self.request.user.userprofile if userprofile.one_click_purchasing: card = stripe.Customer.list_sources( userprofile.stripe_customer_id, limit="3", object="card" # getting error from this line ) card_list = card['data'] if len(card_list)>0: context.update({ 'card': card_list[0] }) return render(self.request, 'pay-with-stripe.html', context) # else: # return render ( self.request, "checkout-page.html", context ) else: messages.warning(self.request, 'Please, fill up the form first.') return redirect('home:checkout') def post(self, *args, **kwargs): order = Order.objects.get ( user=self.request.user, ordered=False ) form = PaymentForm(self.request.POST) userprofile = UserProfile.objects.get(user = self.request.user) if form.is_valid(): token = form.cleaned_data.get('stripeToken') save = form.cleaned_data.get('save') use_default = form.cleaned_data.get('use_default') if save: if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: customer = stripe.Customer.retrieve(userprofile.stripe_customer_id) customer.sources.create(source=token) userprofile.stripe_customer_id = customer['id'] userprofile.one_click_purchasing = True userprofile.save() else : customer = stripe.Customer.create ( email=self.request.user.email, ) customer.sources.create ( source=token ) userprofile.stripe_customer_id = customer['id'] userprofile.one_click_purchasing = True userprofile.save () Any information about this error and how can I avoid this? -
I want to pass user information to other page in Django 3.0 ,so How can i?
I am new Django i am creating a simple login page and wants to redirect to home page with user info as soon as user clicks login button in login form user should be redirected to the home page with username def login1(req): if req.method == 'POST': user = ppl.objects.filter(username = req.POST['text']) print(req.POST['text']) pwd = ppl.objects.filter(pwd = req.POST['pass']) print(req.POST['pass']) if user and pwd: return HttpResponseRedirect(reverse('home', {'u':user})) else: return render(req,'login.html',{'error':"username and password does not match"})