Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am not able to send mail in django
THIS IS MY SETTINGS.PY FILE EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL= 'myyandexmail.com' EMAIL_HOST = 'smtp.yandex.com' EMAIL_HOST_USER = 'myyandexmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False This is my views.py file def contact(request): if request.method == "POST": name = request.POST['name'] email =request.POST['email'] message =request.POST['message'] data = { 'name': name, 'email': email, 'message': message } done_message = 'Your message has been sent. We will respond to you soon' try: #send_mail(data['name'],data['message']+ '\n' ' from ' + data['email'],'info@kahwart.com',['info@kahwart.com'],fail_silently=False) msg=EmailMessage(data['name'],data['message']+ '\n' ' from ' + data['email'],'myyandexmail.com',['myyandexmail.com']) msg.send() return render(request,'artgallery/contact.html',{'message':done_message}) except BadHeaderError: return render(request,'artgallery/contact.html',{'message':done_message}) This is working file on lcoal host but doesnot work on digital ocean.First it was showing errors then i made changes to the code ..But it is not showing any errors now ..But it is not sending mails either...when i click the submit message button it only gets refreshed..What should i do.. -
Django Object level permissions
I have to create groups in django for example, lets say A, B, C. I have a model X and each group has access to a set of instances (Objects) of X. I also have to create user, who belongs to one or more of these groups. Now based on the groups access to model X objects, i have to restrict view access to the user. Is there any solution in django that provides this kind of solution of out the box? Or do i have to create separate tables and control the permissions. -
Deployment to Heroku for Django with channels Failed
I'm trying to deploy to Heroku for Django, but it doesn't work and some logs appreared. I'm at a loss because I don't know the cause. I was wondering if someone could tell me what should do or some tips... heroku logs (web) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. heroku logs (worker) unicodeerror: label empty or too long backend(project name)/asgi.py import os import api.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django.setup() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import OriginValidator from django.core.asgi import get_asgi_application application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': OriginValidator( AuthMiddlewareStack( URLRouter( api.routing.websocket_urlpatterns, ) ), [ 'http://localhost:3000', 'http://127.0.0.1:3000' ] ) backend(project name)/wsgi.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django.setup() from dj_static import Cling from django.core.wsgi import get_wsgi_application application = Cling(get_wsgi_application()) backend(project name)/setting.py(excerpt) . . . WSGI_APPLICATION = 'backend.wsgi.application' ASGI_APPLICATION = 'backend.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(env('REDIS_URL'), env('REDIS_PORT'))], }, }, } . . . Procfile release: python manage.py migrate web: daphne backend.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=backend.settings -v2 manage.py import os import sys import django def main(): """Run administrative … -
how to integrate a vue js project within a django project?
I have an existing vue js project and for backend I want to use django, what came to my mind was to use rest api to communicate with the backend without any integration. is that what everyone is doing or my approach is old school and I have to put the vue project in django directory and go through the whole collectstatic thing? sorry if my question is too basic. -
Django heroku deployment No web process error
Please help me to fix this error. I already have Procfile but I still get same error[enter image description here][1] -
Call a stored-procedure mysql in django
I am using a procedure I have written in MySQL that I want to call in Django but I am just receiving an error : " AttributeError: 'Cursor' object has no attribute 'stored_results' " I can't find why is cursor has no attribute, all the info I get about calling a procedure with python goes with the code 'cursor.stored_results()'. Do you have an idea ? My procedure is : CREATE DEFINER=`root`@`localhost` PROCEDURE `ProcTime`(IN in_date int, OUT somme int) READS SQL DATA BEGIN SELECT SUM(tot) INTO somme FROM( SELECT Habitat, COUNT(DISTINCT(Transect)) AS tot FROM MyTable WHERE Year = @in_date GROUP BY Habitat ) AS t ; END And I am calling it in my views : cursor = connection.cursor() args = ['2004', 0] cursor.callproc('ProcTime', args) for result in cursor.stored_results(): print(result.fetchall()) Thanks !! -
Django search with AND operator many to many relationship
This is my model class MenuItem(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) menu_category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) def __str__(self): return f'{self.name}' class Venue(models.Model): name = models.CharField(max_length=500, null=False) def __str__(self): return f'{self.name}' class VenueMenu(models.Model): venue = models.ForeignKey(Venue, null=False, on_delete=models.CASCADE) menu_item = models.ManyToManyField(MenuItem, null=False) This is my view @api_view(['GET']) def search_menu_item(request): if request.GET.get('venue') and request.GET.get('search_name'): menu_item_filter = Q(menu_item__name__icontains=request.GET.get('search_name')) venue_filter = Q(venue__name=request.GET.get('venue').title()) menu_item_search = VenueMenu.objects.filter(venue_filter & menu_item_filter) serializer = VenueMenuSerializer(menu_item_search, many=True) return Response(serializer.data) This is my serializer class MenuItemSerializer(serializers.ModelSerializer): menu_category = MenuCategorySerializer(many=True) class Meta: model = MenuItem fields = '__all__' class VenueSerializer(serializers.ModelSerializer): class Meta: model = Venue fields = '__all__' class VenueMenuSerializer(serializers.ModelSerializer): menu_item = MenuItemSerializer(many=True) venue = VenueSerializer(many=False) I want to search a single menu item information in a specific venue, as you can see in my query am querying the object but this query is returning me all the menu items associated with that venue including the one which I have searched but I want to have a single menu item which I am searching associated to that venue. -
django-allauth or django in general render template on user status
My menu in the html looks like this: <ul id="nav-mobile" class="right"> {% user_display user %} <li><a href="/accounts/login">Login</a></li> <li><a href="/accounts/logout">Logout</a></li> <li><a href="/accounts/signup">Signup</a></li> </ul> Obivous this doesn't make much sense, cause if a user is not logged in it should be possible to logout and vice versa. Are there any template-tags in django or django-allauth, which I can write in the template like. PseudoCode <if user login> <a> logout </a> <end if> -
How can I give a value to a Django environment variable from within the application itself?
I developed an application with its respective access login, when the user tries to log in, he must select a value that will be used throughout the execution of the application until the user closes the session. I have my project configured with environment variables, I use the django-environ 0.8.1 library to configure these variables so that my application can access them in the .env file. How can I manage the login variable with these environment variables? import environ # environ init env = environ.Env() environ.Env.read_env() # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env.str('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool('DEBUG', default = False) # This is the variable that I need to change according to the option # that the user chooses when logging in DATABASE_SAP_CHOSEN = 'SBOJOZF' -
Django admin login not working for superuser
I'm a newcomer to Django, so sorry if this question is bad. I have looked on the internet but have not been able to find a solution. I am trying to login to a superuser account I created with manage.py. I have not modified any file in my Django project, and am using Django 3.2.5. Every time I try to log in on the admin page it gives me this error Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive (in the web browser of course). I know I am using the username and password that I used when creating the superuser account. I have created two super users the second to while trying to figure out what is going on with this error. I am using the default sqlite3 db. I am also using a anaconda virtual environment. I have also made sure to run migrations. -
Use viewset as action in DRF
i am learning Django and DRF, i have a problem. I need to register an url like this collaborators/<str:cc>/sympathizers but the default drf router is overriding the route with the primary key, like collaborators/<str:pk>/ i can do it with viewsets actions but i am going to implement some hard logic and i want my code to be order. router = SimpleRouter() router.register('candidates', CandidateViewSet) router.register('collaborators', CollaboratorViewSet) // the following route is overrided router.register('collaborators/<str:cc>/sympathizers', SympathizerViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(router.urls)) ] -
no such column: student_student.course_id
I am creating a simple system using Django Sqlite but I am facing this error whenever i try to open the table as an admin in the django/admin by clicking Studends table. The error is the following: OperationalError at /admin/student/student/ no such column: student_student.course_id I searched allot but could not find any exact solution to my problem. The following is my code. views.py from django.shortcuts import render from .models import Student # Create your views here. def index(request): return render(request, "student/index.html",{ "student": Student.objects.all() }) index.html {% extends "student/layou.html" %} {% block body %} <h2>Student information</h2> <ul> {% for student in Student %} <li> {{ student.id }} Student Full Name: {{ student.f_name }}{{ student.l_name }} in {{ student.grade }} with {{ student.gpa }} in {{ student.course_id }}</li> {% empty %} No information entered {% endfor %} </ul> {% endblock %} models.py from django.db import models # Create your models here. class Course(models.Model): code = models.CharField(max_length=10) course_name = models.CharField(max_length=64) def __str__(self): return f"Course name: {self.course_name} with course code ({self.code})" class Student(models.Model): f_name = models.CharField(max_length=64) l_name = models.CharField(max_length=64) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name= "Classes" ) grade = models.CharField(max_length=10) gpa = models.DecimalField(max_digits=4.0, max_length=4, decimal_places=2) def __str__(self): return f"{self.id} Full Name: {self.f_name} {self.l_name} in {self.grade} … -
Why can't Django find secrets.json file?
So I have my Django project, and am trying to deploy it via heroku server. I realized that I need to created secrets.json file (in the same directory as manage.py), and then add it to .gitignore, for sake of security. But after deploying the project, I got an error saying it couldn't find secrets.json file. Below is my code. settings.py secret_file = os.path.join(BASE_DIR, 'secrets.json') with open(secret_file) as f: secrets = json.loads(f.read()) def get_secret(setting, secrets=secrets): try: return secrets[setting] except KeyError: error_msg = "Set the {} environment variable".format(setting) raise ImproperlyConfigured(error_msg) SECRET_KEY = get_secret("SECRET_KEY") secrets.json { "SECRET_KEY" : xxx, "EMAIL_HOST_USER" : xxx, "EMAIL_HOST_PASSWORD" : xxx } After saving these, I added secrets.json to .gitignore. But an error occurs at line 2 (with open(secret_file) as f:), saying it can't find secrets.json file. What do you think is the problem? *FYI, The BASE_DIR doesn't seem to be the problem, since it works fine else where. Such as STATICFILES_DIRS. -
Django Rest Framework and Djongo: serializer create method returns an object with incorrect _id
I have following Djongo model: from djongo import models class Feedback(models.Model): _id = models.ObjectIdField() title = models.CharField(blank=False, max_length=100) text = models.TextField(blank=False) datetimestmp = models.DateTimeField(auto_now_add=True) I have following serializer for the model above: from rest_framework import serializers from .models import Feedback class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = Feedback fields = "__all__" read_only_fields = ["datetimestmp", "_id"] def create(self, validated_data): obj = super().create(validated_data) print(obj._id) return obj When I'm sending POST request to create a Feedback entry inside DB wrong id gets printed to the console: curl -X POST -H "Conte-Type: application/json" -d '{"title": "Example Title", "text": "Example Text"}' http://127.0.0.1:8000/api/feedbacks results in 24 being printed to the server console instead of real ObjectId from MongoDB: ObjectId("61f85ecbb0804f215c127c30"). Is there a way to resolve this issue? Thank you -
So I accidently added a META class and am trying to get rid of it, but the csrf.py file doesn't remove the Meta tag
This is the error I get when trying to go past the login page I have set up. module 'urllib.response' has no attribute 'META' What do I need to delete from the csrf.py file to fix this? -
Django order_by query runs incredibly slow in Python, but fast in DB
I have the following models: class Shelf(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, editable=False) games = models.ManyToManyField(Game, blank=True, through='SortedShelfGames') objects = ShelfManager() description = models.TextField(blank=True, null=True) class SortedShelfGames(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) shelf = models.ForeignKey(Shelf, on_delete=models.CASCADE) date_added = models.DateTimeField() order = models.IntegerField(blank=True, null=True) releases = models.ManyToManyField(Release) objects = SortedShelfGamesManager.as_manager() class Game(models.Model): name = models.CharField(max_length=300, db_index=True) sort_name = models.CharField(max_length=300, db_index=True) ... I have a view where I want to get all of a user's SortedShelfGames, distinct on the Game relationship. I then want to be able to sort that list of SortedShelfGames on a few different fields. So right now, I'm doing the following inside of the SortedShelfGamesManager (which inherits from models.QuerySet) to get the list: games = self.filter( pk__in=Subquery( self.filter(shelf__user=user).distinct('game').order_by('game', 'date_added').values('pk') # The order_by statement in here is to get the earliest date_added field for display ) ) That works the way it's supposed to. However, whenever I try and do an order_by('game__sort_name'), the query takes forever in my python. When I'm actually trying to use it on my site, it just times out. If I take the generated SQL and just run it on my database, it returns all of my results in a … -
How to upload file to django using requests_toolbelt
When i try to upload a file to django using requests_toolbelt and sending everything in client.post data param, django doesn't receive the file. client = requests.session() client = client.get(upload_url) csrftoken = client.cookies['csrftoken'] encoding = MultipartEncoder(fields={'file': open(file, 'rb'), 'csrfmiddlewaretoken': csrftoken}) monitor = MultipartEncoderMonitor(encoding, callback_function) client.post(upload_url, data=monitor, headers={'Content-Type': monitor.content_type}) but if i send the csrftoken in data param and the monitor in files param it gives me. TypeError: 'MultipartEncoderMonitor' object is not iterable All of this is just to get a working progress bar when uploading files to django. -
Convert SQL query set into Django Model Query-set
I need a little help, I come from working with relational data models and now I venture into Django Framework, I need to make an API that returns something like this SQL query SELECT user_profile_userprofile.email, user_profile_userprofile.name, business_unity.active AS status, profile.name AS profile, business_unity.name AS unit FROM user_profile_userprofile JOIN profile ON user_profile_userprofile.id = profile.id JOIN user_profile_unity ON user_profile_unity.user_id = user_profile_userprofile.id JOIN business_unity ON user_profile_unity.id = business_unity.id; The models are already created but I don't know how to make a view in python that meets the conditions of this query -
Django pagination in ListView raise Error "Slice"
i want display pagination on my page but i noticed that when i add "paginate_by" raise me error "slice" class BookNotLogged(generic.ListView): template_name="BookNotLogged.html" context_object_name='listofBook' paginate_by = 2 #when i add this its raise me error model = Book queryset = Book.objects.all() def get_queryset(self): context={ 'book1':Book.objects.get(id="2"), 'book2':Book.objects.get(id="3"), 'book3':Book.objects.get(id="4"), 'book4':Book.objects.get(id="8"), 'book5':Book.objects.get(id="9"), 'book6':Book.objects.get(id="10"), 'book7':Book.objects.get(id="11"), 'book8':Book.objects.get(id="12"), 'book9':Book.objects.get(id="13") } return context -
I keep getting the error OperationalError at /forums/ no such table: forums_simple_post
I am building a simple forum application and I keep getting the error OperationalError at /forums/ no such table: forums_simple_post when I go on my forum page. Does anyone know how to fix this I would much appreciate the help? views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from . import forms from forums_simple.models import Post # Create your views here. class ForumForm(generic.CreateView): template_name = 'forums_simple/forum.html' form_class = forms.ForumForm success_url = '/' def form_vaild(self, form): self.object = form.save(commit=False) self.object.save() return super().form_vaild(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_list'] = Post.objects.all() return context urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'forums' urlpatterns = [ path('', views.ForumForm.as_view(), name='forum') ] models.py from django.db import models # Create your models here. class Post(models.Model): message = models.TextField(blank=True, null=False) created_at = models.DateTimeField(auto_now=True) forms.py from django import forms from . import models class ForumForm(forms.ModelForm): class Meta: model = models.Post fields = ('message',) forum.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> {% for message in object_list %} {{ post.message }} {% endfor %} </div> <div class="container"> <form class="forum_class" action="index.html" method="post"> {% csrf_token %} {% crispy form %} … -
How to Validate CSV file while reading?
I would like to create a new validation for CSV file. The idea is: if in csv file while reading in the first line is header - id and code then continue, if not - raise an error. Right now I have some functionality for writing and reading csv file to StringIO. def write(): header = ['id', 'code'] buffer = io.StringIO() writer = csv.writer(buffer) writer.writerow(header) # after writing data from table def create(self, request, *args, **kwargs): serializer = CsvSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY) csv_file = serializer.validated_data['file'] file = csv_file.read().decode('utf-8') csv_fields = ['id', 'code'] csv_reader = csv.DictReader(io.StringIO(file), fieldnames=csv_fields) next(csv_reader) # skip headers from csv for processing the file and do other stuff Im asking for a help to add validation to this code or give me some advices. The csv file looks like (correct one): id code 0101010 2049583 3232323 3232232 3232323 4434454 3232333 4532222 This is the examples of incorrect csv: 01010 20493 3232323 3232232 3232323 4434454 3232333 4532222 abc dsdsd 0101010 2049583 3232323 3232232 3232323 4434454 3232333 4532222 Id and code quantity is every time different, because of the entered data in DB -
How to populate a django Model FormSet with Model instances AND default field values
The problem is how to populate each form of a Model Formset using a queryset, and also providing initial data to the unbound forms in the formset. Why? I have a model called Answer. I want to create many Answers to a Question model, and each Question is within a Section, another model. When in the question detail page, I already know the Section and the Question the Answer object should belong to, and these will eventually just be rendered as hidden fields, but I need them in order to save the Answer object. My models (reduced to the essential fields): class Section(models.Model): section = models.CharField(max_length=100) def __str__(self): return self.section class Question(models.Model): question = models.CharField(max_length=500) section = models.ForeignKey(Section, on_delete=models.CASCADE) def __str__(self): return self.question class Answer(models.Model): answer = models.CharField(max_length=200, null=True, default='') question = models.ForeignKey(Question, on_delete=models.CASCADE) section = models.ForeignKey(Section, on_delete=models.CASCADE) def __str__(self): return self.answer My form: class AddAnswerForm(forms.ModelForm): class Meta: model = Answer fields = ['answer', 'question', 'section'] I want to do this with Model Formsets since the user should be able to keep adding answers, and also edit answers previously given. I've looked at the docs, which for django are excellent, and found how to add initial data here. Initially, the … -
Django multiple forms, one form resets other form
Got some forms in my view... I want that only what I have submitted is changed in the database. So that no forms overwrite each other. How can I do this with my view? I even noticed that the order in which each '..._form.is_valid()' is, makes a difference in what gets overwritten views.py @login_required def DashboardView(request): browser = str(request.user_agent.browser.family) user = str(request.user) short_user = user[0:7] + "..." try: radius = request.user.fieldradius except FieldRadius.DoesNotExist: radius = FieldRadius(user=request.user) try: font_size = request.user.fontsize except FontSize.DoesNotExist: font_size = FontSize(user=request.user) try: change_color = request.user.colors except Colors.DoesNotExist: change_color = Colors(user=request.user) try: toggle_settings = request.user.togglesettings except ToggleSettings.DoesNotExist: toggle_settings = ToggleSettings(user=request.user) try: page_details = request.user.pagedetails except PageDetails.DoesNotExist: page_details = PageDetails(user=request.user) if request.method == 'POST': form = FieldForm(request.POST, instance=Field(user=request.user)) togglesettings_form = ToggleSettingsForm( request.POST, instance=toggle_settings) radius_form = FieldRadiusForm(request.POST, instance=radius) change_color_form = ColorsForm(request.POST, instance=change_color) fontsize_form = FontSizeForm(request.POST, instance=font_size) pagedetails_form = PageDetailsForm( request.POST, request.FILES, instance=page_details) if togglesettings_form.is_valid(): togglesettings_form.save() return redirect('/dashboard/#panel1') if form.is_valid(): time.sleep(1.5) obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard') if radius_form.is_valid(): radius_form.save() return redirect('/dashboard') if fontsize_form.is_valid(): fontsize_form.save() return redirect('/dashboard') if change_color_form.is_valid(): change_color_form.save() return redirect('/dashboard') if pagedetails_form.is_valid(): pagedetails_form.save() return redirect('/dashboard') else: form = FieldForm() radius_form = FieldRadiusForm(instance=radius) fontsize_form = FontSizeForm(instance=font_size) change_color_form = ColorsForm(instance=change_color) pagedetails_form = PageDetailsForm(instance=page_details) togglesettings_form = ToggleSettingsForm() return … -
How to bulk_create image field?
I have a model which I bulk_create and bulk_update from external data, but I havn't managed to do it with the model's image field. Is there a way to do so? I have a list of BytesIO objects (each corresponding to one object), for example: <_io.BytesIO object at 0x7f0ad4390b30> should be added as an image to object 1. Doing it manually and sequentially is possible, and I would add a single image to a single model like this: obj.image.save(file_name, files.File(file_object)) (With from io import BytesIO, from PIL import Image and from django.core import files prerequesite, if it is worth mentioning). But how can I do it in bulk, or as efficient as possible in any other manner? Thanks in advance :-)) Cheers -
don't let user create multiple objects with same value
I have a model with a foreign key called "title". I want to restrict each user to only be able to create an object with each title once, so that they can't have multiple objects with the same title. Does anybody know how I can achieve this?