Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to differentiate b/w receiver and sender in django?
I have a problem when sending an email. Whenever I send an email from bilalkhangood6@gmail.com to bilalkhangood4@gmail.com. The email I open shows me that bilalkhangood4@gmail.com is the receiver and sender also. The email shows me that it is sent and received both from bilalkhangood4@gmail.com Although this is not the case. The send sender is bilalkhangood6@gmail.com and receiver is bilalkhangood4@gmail.com settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' # this should an official account from which every user will get password change link EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' views.py class ViewSendEmail(FormView): form_class = FormEmailSend template_name = 'nextone/email_send.html' def form_valid(self, form): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] from_email = form.cleaned_data['from_email'] to_email = form.cleaned_data['to_email'] emails = [] if ',' in to_email: for email in to_email.split(''): emails.append(email) else: emails.append(to_email) if 'send_mail' in self.request.POST: send_mail_example(subject, message, from_email, emails) else: send_email_message(subject, message, from_email, emails) return redirect('ViewSendEmail') def send_email_message(subject, message, from_email, emails): email = EmailMessage(subject, message, from_email, to=emails) email.send() def send_mail_example(subject, message, from_email, emails): send_mail(subject, message, from_email, emails) forms.py class FormEmailSend(forms.Form): to_email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Email(s) to send to','class': 'form-control'})) subject = forms.CharField(required=False,widget=forms.TextInput(attrs={'placeholder': 'Subject', 'class': 'form-control'})) message = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Email body', 'class': 'form-control'})) from_email = forms.EmailField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Email(s) from receive … -
Why is the return value of a model method in Django not showing up to the template?
I have this function inside my model that is not appearing when I try to run the server. I think I am accessing the method correctly but when I tried writing print("ENTER") inside the total_balance() function, nothing showed up which makes me think that it's not even entering the method at all. Oddly, the function works if I take out the search functionality. model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def total_balance(): transaction_list = Transaction.objects.filter(user=User) total_balance_amount = 0 for transaction in transaction_list: if transaction.category=='Income': total_balance_amount += transaction.amount elif transaction.category=='Expense': total_balance_amount -= transaction.amount return total_balance_amount views.py def profile(request): if request.method == 'GET': query = request.GET.get('q') if query and query!="": results = Transaction.objects.filter(Q(tag__icontains=query)) else: results = Transaction.objects.all() transactions = { 'transactions' : results, } profile = { 'profile' : Profile.objects.all() } return render(request, 'users/profile.html', transactions, profile) template.py <h5 class="card-title">Total Balance</h5> <p class="card-text">₱{{ profile.total_balance }}</p> Can someone please help me identify the reason this is not working and how I might be able to fix it? Thank you. -
Django inline formset with manytomany fields
Ive spent a fair bit of time searching on this subject without finding some real up to date answers. I'm trying to create a form that creates a db entry. The basic idea is this: Many events can have many people So, the struggle here is that the user needs to create an event where the user can select all the people that attend. Each person that attends though, has certain things that also needs to be tracked per event. See the model below: models.py from django.db import models from django.contrib.auth.models import User[] class PersonRole(models.Model): role = models.CharField(max_length=20, choices=ROLE_CHOICES, unique=True) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.role class PersonClass(models.Model): name = models.CharField(max_length=100, choices=CLASS_CHOICES, unique=True) color = models.CharField(max_length=6, choices=COLOR_CHOICES, unique=True) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=100, unique=True) personclass = models.ForeignKey(PersonClass, on_delete=models.CASCADE, blank=True, null=True) personrole = models.ForeignKey(PersonRole, on_delete=models.CASCADE, blank=True, null=True) value = models.IntegerField(default=0) reliability = models.IntegerField(default=0) last_item = models.DateField(auto_now=False, blank=True, null=True) last_event_attended = models.DateField(auto_now=False, blank=True, null=True) last_manager_attended = models.DateField(auto_now=False, blank=True, null=True) item_received = models.BooleanField(default=False) … -
Data relationship on application level in Django
Is it possible to build data relationship on programming level using models but not in tables, If yes how. For example in Laravel we can define model relationship inside model, it does not require database level foreign key relations. My question is, Like that can we define that in Django model or any other methods to achieve that. -
multiprocessing in python with error 'takes 1 positional argument but 2 were given'
) i'm a beginner in python and django and try to run a external code with multiprocessing. On my first try import a .txt with numpy, my code runs. On my second try to import a .csv with pandas, i get an error message. What is the different? Why doesn't run the second try? quick.py import os import pandas as pd import numpy as np def import_txt(q, w_url): w_data = np.loadtxt(w_url,delimiter=';', dtype='str') q.put(w_data) def import_csv(q, w_url): w_data = pd.read_csv(w_url) w_data.head() q.put(True) views.py from multiprocessing import Process, Queue, set_start_method from app.static.code.quick import import_txt as q_txt from app.static.code.quick import import_csv as q_csv this works def q_history(request): if request.method == 'POST' and request.is_ajax(): #erstellt den pfad m_user = request.user.username m_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) m_dir = os.path.join(m_dir, 'app', 'media', m_user, 'quick', 'ini.txt') set_start_method('spawn', True) q = Queue() p = Process(target=q_txt, args=(q,m_dir)) p.start() m_data = q.get() p.join() return JsonResponse(m_data.tolist(), safe=False) else : assert isinstance(request, HttpRequest) return render( request, 'quick.html', { 'title':'title', 'message':'Your application description page.', 'year':datetime.now().year, } ) this not def q_csv(request): if request.method == 'POST' and request.is_ajax(): #erstellt den pfad m_user = request.user.username m_file = '2019_Test.csv' m_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) m_dir = os.path.join(m_dir, 'app', 'media', m_user, 'quick', 'input', m_file) set_start_method('spawn', True) q = Queue() p = … -
Get images from database as known images for Facial recognition
I am playing around with a time attendance application that is going to utilize facial recognition. When you create a user, you add three pictures of that user and those pictures are saved in the database. Note that I'm using Django and Django models for this. I am thinking of connecting to the database itself because I can't of an easier way of retrieving the images from Django Models outside of Django. Anyways. Consider a standard OpenCV Facial recognition code. It has a thing called known images. What I want to do, is when a user enters their ID, the program retrieves the images of that user. The thing I don't understand, is how do I directly use those images for known_images. Do I first save the images in the OS's temp folder and read from there? Or how do I do this? Thank you, any and all ideas are appreciated. -
Adding a profile image in django is not working
I am trying to add profile image to my page, but for some reason "my image" text is shown instead of a image. I do not have any clue about what is wrong in my code, i jave read trough multiple tutorials and they all tells me to do this way. I have a folder "media" in my root directory and inside that i have folder "profile_pics". I have added these to settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' these to urls.py from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my html {% load static %} {%block content%} <div class="content-section"> <div class="media"> <img src="{% static "profile_pics/default.jpg" %}" alt="My image"/> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> </div> {%endblock content%} models.py class profiili(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) kuva=models.ImageField(default='default.jpg', upload_to='profile_pics') -
Sending data from form python
When I click on search button I need to get data using google api, but I get this error page. https://i.stack.imgur.com/imj6T.png index.html <!DOCTYPE html> <html> <head> </head> <body> <form method="POST"> {% csrf_token %} <input type="text" name="search" placeholder="some text"><br> <button class="button" name="submit" type="submit">Search</button> </form> </body> </html> views.py from django.http import HttpResponse from django.shortcuts import render def index(request): if request.method == 'GET': return render(request, 'index.html', context={}) # Handles the search once the submit button in the form is pressed # which sends a "POST" request if request.method == 'POST': # Get the input data from the POST request search_query = request.POST.get('search', None) # Validate input data if search_query and search_query != "": try: from googlesearch import search except ImportError: print("No module named 'google' found") for j in search(search_query, tld="co.in", num=10, stop=1, pause=2): print(j) else: return HttpResponse('Invalid input.') urls.py from django.urls import path from firstapp import views urlpatterns = [ path('', views.index, name='home') ] Please, help to solve that. -
Is there any specific way to override search_indexes of oscar core search app?
I am using Haystack with solr back-end in Django-Oscar. I want to override ProductIndex class of core search_indexes. But, the problem is it's not working with the regular way. Firstly, I forked the search app like other oscar apps. And I created custom ProductIndex class inside search_indexes.py file. I also tried excluding core search_indexes in setting. But, it's not taking from the overridden app. My custom class looks like: """ from oscar.apps.search.search_indexes import ProductIndex as AbstractProductIndex class ProductIndex(AbstractProductIndex): def index_queryset(self, using=None): # Only index browsable products (not each individual child product) return self.get_model().objects.all().order_by('-date_updated') def read_queryset(self, using=None): return self.get_model().objects.all().base_queryset() """ The ProductIndex class is supposed to run from my overridden app but, instead it's using core ProductIndex app. -
How to satisfy unique constraint in django unit test without hardcoding?
I have set a unique constraint on email field of my Member model. Now while writing unit tests, my tests fail due to expiring unique constraint. def setUp(self): self.car_provider = mommy.make(Member, username="car_provider") self.car_provider.set_password("12345678") self.car_provider.save() self.applicant = mommy.make(Member, username="applicant") self.applicant.set_password("12345678") self.applicant.save() I get following error: "django.db.utils.IntegrityError: duplicate key value violates unique constraint "account_member_email_a727987b_uniq" DETAIL: Key (email)=() already exists." -
Django zip multiple files from the list
Trying to compress multiple files and download .zip file via button. Here is my code: VIEW.py files = ['file1.txt','file2.txt','file3.txt'] file_path = os.path.join(settings.MEDIA_ROOT, '/') def downloads_files (requests): if 'zipall' in request.POST: if len(config_filenames) > 0: zipfile_name = zipped(directory=file_path, file_list=files ) resp = HttpResponse(FileWrapper(open(zipfile_name,'rb')), content_type='application/zip') resp['Content-Disposition']='attachment;filename=%s' % zipfile_name return resp def zipped(directory, file_list): zip_filename=directory + strftime("zipped_%Y_%m_%d_%H%M%S", gmtime()) + '.zip' with ZipFile(zip_filename, 'w') as zip1: for current_file in file_list: # Add file to zip zip1.write(directory+current_file) return zip_filename I was able to download, but when I unzip, creates a lengthy name and also create subfolder based on the root. Long name: _Users_<user>_<projectfolder>_src_media_zipped_2019_08_18_081747.zip -
How to Implement Dependent Dropdown list in Django
I have a Food table which contains Food name and it's price.Whenever a user selects a food from template form,the price associated with it should automatically be displayed in the form. How can I do it ?? models.py class Food(model.Models): name = models.CharField(max_length = 100) price = models.IntegerField() class Payment(models.Model): food = models.ForeignKey(Food, on_delete=models.CASCADE) forms.py class PaymentForm(forms.ModelForm): class Meta: model = Payment fields = '__all__' views.py def payment_details(request): amounts = Food.objects.all() context={ 'amounts' : amounts } return render(request, 'app_name/payment.html',context) template <label>Select the Food</label> <select name="name" class="form-control" required> {% for amount in amounts %} <option value="{{amount.food.name}}">{{amount.food.name}}</option> {% endfor %} </select> <label>Amount You Need to Pay</label> <select name="name" class="form-control" required> {% for amount in amounts %} <option value="{{amount.food.price}}">{{amount.food.price}}</option> {% endfor %} </select> -
Map raw sql query with join to model in Django
I want to execute a raw SQL query and map the result to model. Let's say I have the following model: class Message(Model): id = AutoField(primary_key=True) user = ForeignKey(User) test = CharField(max_length=100) And let's assume this is the raw SQL query I am trying to execute: messages = Message.objects.raw('SELECT * FROM message m JOIN user u ON m.user_id = u.id') However, I am having a hard time understanding how to map user fields from db to user fields in my Message model. The reason why I am using raw SQL query is that the original query seems to be quite complex to do it using Django ORM. It seems to be an easy task but I couldn't find an answer online. -
which front end framework best suits django?
which front end framework best suits django? -
Wagtail get all pages in GraphQL
I need to get all pages in wagtail with GraphQL with title and body fields by Page model in wagtail and pass body from child pages. How can I get all the inheritors inherited from Page in the wagtail with their body fields, where it is in the child pages class HomePage(Page): body = StreamField([ ('intro_header', blocks.TextBlock(icon="title")), ('intro_sub_header', blocks.TextBlock(icon="title")), ('intro_image', ImageChooserBlock()), ('technologies_title', blocks.TextBlock()), ], blank=True, null=True) class AboutPage(Page): body = StreamField([ ('header', blocks.TextBlock(icon="title")), ('content', RithTextBlock()), ], blank=True, null=True) query pages { pages { id title body } } -
TypeError: is_valid() missing 1 required positional argument
I have write models and form files successfully but still showing some error in views after passing argument is the self is not defined after defining self it is showing NoneType' object has no attribute 'is_bound -
Django transaction not working as expected
I want to add a job information into MySQL database via Django framework and make sure not to add the job already exist in the database. And I have already use transaction atomic with savepoint but still not working during testing. Could anyone have some ideas about how to make it work? Thanks in advance ! Django view function: def insert(request): name = request.GET["name"] jobs = Job.objects.filter(~Q(status='DONE'),name=name) if len(jobs) > 0: return HttpResponse("Already insert!") else: try: with transaction.atomic(): sid = transaction.savepoint() newJob = Job(name=name,status='NEW') newJob.save() # Could throw exception jobs = Job.objects.filter(~Q(status='DONE'),name=name) if len(jobs) > 2: transaction.savepoint_rollback(sid) return HttpResponse("Rollback Already insert!") transaction.savepoint_commit(sid) return HttpResponse("insert "+ name +" successfuly") except IntegrityError: transaction.savepoint_rollback(sid) return HttpResponse("Rollback insert error!") transaction.clean_savepoints() Test function: import multiprocessing import os import random import time from multiprocessing import Pool, Process import requests def run_proc(name): print("exec "+name) payload = {} payload['name'] = name r = requests.get("http://localhost:8080/dashboard/insert",params=payload) print(r.text) if __name__ == "__main__": pool = multiprocessing.Pool(processes = 10) for j in range(10): for i in range(10): pool.apply_async(run_proc, (str(j), )) print("Start") pool.close() pool.join() print("Sub-process(es) done.") And in Database: 1 0 2019-08-18 06:00:39.408953 NEW 2 1 2019-08-18 06:00:41.477532 NEW 3 2 2019-08-18 06:00:43.530742 NEW 4 3 2019-08-18 06:00:45.569131 NEW 5 4 2019-08-18 06:00:47.618674 NEW … -
Dupla camada de Cadastro
Tô iniciando no Django, e tenho algumas dúvidas: 1° No código abaixo, como vocês podem ver, tem uma classe chamada Aluno que tem relação com a classe Responsável, eu gostaria de numa tela de cadastro mostrassem as form das duas classes para realizar o cadastro, já que é necessário um Responsável para cadastrar aluno. Eu consegui fazer com o código abaixo, mas não sei se tem algum jeito melhor. Segue uma imagem de como eu quero, e consegui(https://imgur.com/bp6Aa2Z). Mas minha dúvida é, Tem algum modo melhor de realizar essa tarefa? 2º Eu queria também, pegar a altura e o peso do aluno, para realizar o IMC dele. Como eu faço isso? Quando eu faço a função que pega a altura e o peso, e comparo com EX: 18.5, diz que não é possível comparar a função com o valor. Tentei também colocar o valor do calculo numa variável, e também aparece um erro dizendo que não é possivel comparar um valor Floadinput com Float. Então alguma solução para isto? OBS: Ali no views.py percebam que há respform e cadform, a dúvida Nº 1, é em respeito a isso, tem como eu fazer em só 1? Tipo, em cadform eu realizar … -
How do I add or delete attributes on the 127.0.0.1:8000/admin/auth/user page?
How do I add or delete attributes on the 127.0.0.1:8000/admin/auth/user page? I don't know how to add or remove properties from an existing page class CustomAdmin(admin.ModelAdmin): list_display = ['emp_no', 'first_name', 'last_name', 'gender', 'birth_date', 'hire_date'] admin.site.unregister(User) admin.site.register(User, UserAdmin) Nothing changes -
not displaying objects from object.procedure_set.all
i am having objects that are linked with one to many relationship and i am trying to display data of object linked with foriegn key but displaying nothing, I have also tried to use the qs in view but ending up with error views.py : @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method == "POST": procedure = ProcedureForm(request.POST) if procedure.is_valid() : procedure.save() return HttpResponseRedirect(request.path_info) else: return HttpResponse(procedure.errors.as_data()) else: procedure = ProcedureForm() return render(request, 'dischargedetails.html', {'object':object, 'procedure':procedure}) template: {% for ab in Ipd.procedure_set.all %} <div class="col-lg-12"> <div class="feed-activity-list"> <div class="feed-element"> <div class="media-body"><small class="pull-right">{{ab.time}} {{ab.date}}</small> <p class="font-bold alert alert-success m-b-sm" > <a data-toggle="modal" id="1028" data-target="#modal-form-invest-update"> {{ab.report}} </a> {% endfor %} </p> </div> </div> </div> -
Django, What happens with pre_delete if model.delete() fails
seems like a simple question, but I can't find any documentation... when using pre_delete, if the model.delete() call fails for whatever reason (let's assume a child constraint fails), does the pre_delete signal still fire? -
trying to let users add new topics to page, but page only returns the bullet points, NO topic names. works fine in admin backend but defeats purpose
Working thru my 1st python/Django project. Need to let users add new topics to a blog page, but page only returns the bullet points, NO topic names. Works fine on admin back end which of course defeats purpose of user entry" {% extends 'blog/base.html' %} {% block content %} <p>Add a new topic:</p> <form action="{% url 'blog:new_topic' %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name='submit'>add topic</button> </form> {% endblock content %} {% extends 'blog/base.html' %} {% block content %} <p>BlogPosts</p> <ul> {% for topic in blogposts %} <li> <a href="{% url 'blog:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <li>Nothing's yet been posted</li> {% endfor %} </ul> <a href="{% url 'blog:new_topic' %}">Add a new topic:</a> {% endblock content %} -
Django channels cannot import name RequestAborted from exceptions
Using daphne here's my setup: PROCFILE: web: daphne my_application.asgi:application --port $PORT --bind 0.0.0.0 -v2 SETTINGS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'channels', 'django_summernote', .... ] CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], } } } ASGI_APPLICATION = "my_application.routing.application" ROUTING FILE: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.conf.urls import url application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( [ url(*), .... ] ) ), }) ASGI.PY - WHERE THE ERROR OCCURS """ ASGI entrypoint. Configures Django and then runs the application defined in the ASGI_APPLICATION setting. """ import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_application.settings") django.setup() # HERE IT THROWS THE IMPORT ERROR application = get_default_application() REQUIREMENTS: ... channels channels_redis ... So, using the latest 2.(2?) package I believe which I just verified has the source code required. IMPORT ERROR from channels.exceptions import RequestAborted, RequestTimeout ImportError: cannot import name 'RequestAborted' I clearly have the right package and this is available per the source code so wtf is going on here.....? -
How to Debug Django coode with Docker?
I am doing a project in Django, I use PyCharm in Windows 8.1. To start the web server and the database I use Docker installed on Debian (Linux) through a virtual machine (do not install Windows Docker for compatibility problems). The problem is that by working in this way, I can't find a way to debug the code (put breakpoints, etc.). I was looking everywhere but I didn't find any solution. Maybe someone could solve this problem. In case I leave the file docker-compose.yml: version: '3.4' services: db: image: postgres container_name: csuperior-postgres environment: POSTGRES_USER: xxxxxxx POSTGRES_PASSWORD: xxxxxxx broker: image: rabbitmq container_name: csuperior-broker environment: - RABBITMQ_DEFAULT_USER=xxxxxxx - RABBITMQ_DEFAULT_PASS=xxxxxxx web: container_name: csuperior-web volumes: - .:/code/ build: . ports: - '8000:8000' command: python3 manage.py runserver 0.0.0.0:8000 depends_on: - db - broker Thanks! -
can't debug django app in VS Code with docker database: 'could not translate host name "db" to address: Name or service not known'
My django app is connecting to a postgreSQL database that runs in a docker container. I can connect to this container no problem if I run the app manually: ./src/manage.py runserver However, if I try to run a debug configuration through VS Code, I get this error: psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known Here is the code the VSCode is running when I try to debug (I did not set any of these settings): /home/me/Developer/myproject/venv/bin/python /home/me/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/ptvsd_launcher.py --default --client --host localhost --port 37153 /home/me/Developer/myproject/src/manage.py runserver --noreload How can I get my debug configuration to work?