Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send image as part of email body in django
I am building a portal for sending dynamic emails. Part of the form is an image field which the user can upload an image which I would like to be rendered in the image body, not as an attachment after the form is filled out. This is my code: views.py def emailView(request): if request.method == 'POST': form = ContactForm(request.POST, request.FILES) if form.is_valid(): form.save() name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] image = form.cleaned_data['image'] message = form.cleaned_data['message'] recipient = form.cleaned_data['recipient'] image_url = Email.objects.all().last() domain = request.get_host() final_image = str(domain) + str(image_url.image.url) msg = loader.render_to_string( 'email_portal/email.html', { 'name': name, 'subject': subject, 'domain' : domain, 'final_image' : final_image, 'image_url': image_url, 'message': message, } ) try: send_mail(subject, name, message, [recipient] , fail_silently=True, html_message=msg,) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/') else: form = ContactForm(request.POST, request.FILES) return render(request, "email_portal/index.html", {'form': form}) email.html <h5>{{ final_image }}</h5> #missing forward slash <a href="{{ domain }}/{{ image_url.image.url }}">My link</a> #missing forward slash <tr> <td background="{{ final_image }}</td> </tr> I have tried concatenating the host and the file path but for some reason, in the email body it's structured correctly but I can't render it as a background image and when I try to click it a forward slash is … -
Login django automatically with provided http link with username and password
User gets an email with http link to django. I want to provide the username and password in the link so that the user automatically logges in. http://www.test.com/username=testusername%password=testpassword Is this possible ? -
'NoneType' object has no attribute 'username'? What should i do?
I am extending User model of Django by following model models.py class Profile(models.Model): user = models.OneToOneField(User, null=False, on_delete = models.CASCADE) First_name = models.CharField(max_length = 128, null = True) Last_name = models.CharField(max_length = 128, null = True) email = models.CharField(max_length = 200, null = True) phone = models.CharField(max_length = 200, null = True) mod_date = models.DateTimeField(auto_now_add = True, null = True) profile_pic = models.ImageField(null = True, blank = True) def __str__(self): return self.user.username views.py def userprofile(request): form = Profile() if request.method == 'POST': form = Profile(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'cs14/profile.html', context) forms.py class Profile(ModelForm): class Meta: model = Profile fields = ["First_name","Last_name","email", "phone"] When I try to go profile page, it happened error AttributeError at /profile/ 'NoneType' object has no attribute 'username' What is going wrong? -
How to store image file or file temporary using python or django rest_framework without saving in the database? I am new to Django
How to store image file or file temporary using python or django rest_framework without saving in the database? In dajngo rest_framework I did these things in a function based view. temp_file = request.FILES['document_file'] Then, how I store this file temporary without saving in the database? -
module 'hello_world' not found while running the manage.py runserver in django
My site is hosted at centos 7, lamp stack, whm/cpanel. I created a virtual environment mp_env and installed python3.7 and Django in mp_env. This mp_env is created in the same folder where we have public_html folder for main site. In this mp_env folder we have bin and lib. Python3.7 is installed this lib folder and Django was installed in site-packages of this lib. No. I did not do that intentionally. I just installed python and Django in mp-env. They automatically found places. Then I created a project myproject. I could test it with ./manage.py runserver 0.0.0.0:8000. I could change the database to mysql, create users and login to admin from web browser. It was working fine.The project folder is outsite the mp_env. Then I created an app hello_word inside the project directory myproject using this example at https://realpython.com/get-started-with-django-1/ I have followed the steps mentioned there and used everything word by word. Now when I try ./manage.py runserver 0.0.0.0:8000, it gives error - module 'hello_world' could not be found. -
Variable number of inputs with Django
Currently I'm making a platform based on chamilo and I'm stuck because a template´s form for tests. The reason is becasuse I have to adquire de data from the form and organized to send througth the chamilo api rest. Currently This form is made of 6 static hidden inputs, but the real problem is the other inputs that are generate in function of the number of questions. In the forms.py file I defined a class for this form but only with 6 inputs but I don´t know how to handle the variable inputs from the tests answers because the tests have different number of questions and answers class Ejercicios(forms.Form): c_id = forms.CharField() lp_id = forms.CharField() item_id = forms.CharField() item_viewId = forms.CharField() exe_id = forms.CharField() time = forms.CharField() My class in forms.py look like this, how can I add different number of extra forms dynamically? -
'dict' object has no attribute 'coupon' ecommerce/store/views.py, line 254, in add_coupon
I have this e-commerce website I'm creating with django3. and I am getting this problem.AttributeError at /add-coupon/ 'dict' object has no attribute 'coupon' if someone can help please!!! my views def get_coupon(request, code): try: coupon = Coupon.objects.get(code = code) return coupon except ObjectDoesNotExist: messages.info(request, 'This coupon does not exist') return redirect('checkout') def add_coupon(request): data = cartData(request) if request.method == "POST": form = CouponForm(request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = data['order'] order.coupon = get_coupon(request, code) order.save() messages.success(request, 'Successfully added coupon!') return redirect('checkout') except ObjectDoesNotExist: messages.info(request, 'You do not have an active order') return redirect('checkout') return redirect('checkout') my guest order function > `def guestOrder(request, data): name = data['form']['name'] email = data['form']['email'] cookieData = cookieCart(request) items = cookieData['items'] user, created = User.objects.get_or_create( username = name, email=email, ) #user.name = name user.save() order = Order.objects.create( user=user, complete=False, coupon=None, #todelete ) for item in items: product = Product.objects.get(id=item['id']) orderItem = OrderItem.objects.create( product=product, order=order, quantity=item['quantity'], ) return user, order -
Testing coroutine function in async web socket consumers using channels
I am writing test cases for an Async WebSocket Consumer using the django channels. I want to mock a coroutine which I have defined in the connect method of my WebSocketConsumer. Consumer.py class ExampleTestConsumer(AsyncWebSocketConsumer): async def connect(self): await function_to_be_tested(args) await self.accept() Test case class TestExampleTestConsumer: async def test can_connect_to_server(self,settings): communicator = WebsocketCommunicator( application=application, path="/ws/example-test/1", ) connected, _ = await communicator.connect() assert connected is True await communicator.disconnect() I want the mocking of function_to_be_tested in this test case for this test case to work . Any suggestions ? -
How to perform multiple table join with Django?
I have a table like this: ID Parent_ID Name Geo 1 Null City A ABC1 12 1 District 1 ABC002 123 12 Ward 1 ABC002003 2 Null City B XYZ2 25 2 District 5 XYZ004 251 25 Ward 4 XYZ002006 Normally, I got the ID of the ward (third in the hierarchical). I need to to do query to get the GEO of the city (first in the herarchical). In query (PostgreSQL), I would do something like this : SELECT l1.Geo FROM routing.r_location l1 JOIN routing.r_location l2 ON l1.ID= l2.Parent_ID JOIN routing.r_location l3 ON l2.ID= l3.Parent_ID WHERE l3.ID= '123' Since, I am beginner with Django, I literally dont know how to do complex join table like this. Please help -
Django how to log loge page with id
I am new to Django and tried existing answers but did not work for me. I would appreciate your help! I can easily get to the general page when I enter the site, but how do I go to my profile when I log in? def login(request, pk=0): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) try: remember = request.POST['remember_me'] if remember: settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False except: is_private = False settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request, 'invalid credentials') return redirect('login') else: return render(request, 'registration/login.html') urls.py path('profile/<int:pk>/', views.profiles, name='profile'), -
Only friends posts are not showing
I am building a BlogPost Webapp, AND i am stuck on an Error. views.py def friends_posts(request,user_id): posts = Post.objects.filter(post_owner=user_id) profiles = get_object_or_404(Profile,user_id=user_id) p = request.user.profile you = p.user friends = p.friends.all() context = {'posts':posts,'profiles':profiles,'friends':friends} return render(request, 'friends_posts.html', context) urls.py path('friends_posts/<int:user_id>/',views.friends_posts,name='friends_posts'), friends_posts.html {% for user_p in friends %} {{ user_p.friends.posts.all }} {% endfor %} The Problem friends_posts page is not showing Friends post. It is showing all the information of friends but NOT showing the posts of friends. What i am trying to do I am trying to show all the posts of friends of request.user. I don't know what to do. Any help would be appreciated. Thank You in Advance. -
Pytest django url's tests
I saw some people writing url's test like this: def test_sample_url(): path = reverse('url_name', kwargs={'pk': 1}) assert resolve(path).view_name == 'url_name' As for me this test is not checking anything, because if I place 'url_name' in second line then in third it is obviously going to be equal to it. Am I wrong or missing something? -
How to hide certain json data from passing through if it doesn't meet a condition in Django rest framework?
Hello all I want to hide certain json data from passing through if it doesn't meet a condition in django rest framework, like I have a comment model and serializer, and I don't want the replies to pass through as comments since I have another field for replies which is nested along with the respective comments. These are the serializers: class CommentCreateSerializer(serializers.ModelSerializer): content = serializers.CharField() reply_id = serializers.PrimaryKeyRelatedField(source='reply',queryset=Comment.objects.all(), write_only=True, required=False) user = serializers.ReadOnlyField(source="user.username") class Meta: model = Comment fields = ['id', 'user', 'content', 'reply_id', 'timestamp'] class CommentSerializer(serializers.ModelSerializer): content = serializers.CharField() reply_id = serializers.PrimaryKeyRelatedField(source='reply',queryset=Comment.objects.all(), required=False) user = serializers.ReadOnlyField(source="user.username") replies = CommentCreateSerializer(many=True, read_only=True) class Meta: model = Comment fields = ['id', 'user', 'content', 'replies', 'reply_id', 'timestamp'] This is the json response: "count": 5, "next": null, "previous": null, "results": [ { "id": 2, "user": "testuser2", "content": "comment test!", "replies": [ { "id": 3, "user": "testuser3", "content": "ding", "timestamp": "2021-02-09T15:29:38.230933+01:00" } ], "reply_id": null, "timestamp": "2021-02-09T15:24:11.072502+01:00" }, { "id": 6, "user": "testuser2", "content": "Testing again", "replies": [], "reply_id": null, "timestamp": "2021-02-09T17:33:59.227425+01:00" }, { "id": 5, "user": "testuser2", "content": "Testing", "replies": [], "reply_id": null, "timestamp": "2021-02-09T17:28:41.992143+01:00" }, { "id": 3, "user": "testuser3", "content": "ding", "replies": [], "reply_id": 2, "timestamp": "2021-02-09T15:29:38.230933+01:00" }, { "id": 4, "user": … -
Strange error NameError: name '_mysql' is not defined on VSCode
I'm trying to using mysqlclient==2.0.3 for Django==1.11.17 and I am receiving this error when trying to start python manage.py runserver. The error is really strange because on macOS's terminal the commands works and everything is fine while the error appears only when using the same command from VSCode shell. In both I'm using zsh -
How to pass variable from Python API to Django template
I have been trying to work with this Python sports data api, Sportsipy. It’s pretty simple to set up and I can save data to a var and print it to the terminal but when I add it to context go to pass it through my Django template nothing shows up. I tried calling it on the HTML side several different ways but I still haven't been able to figure it out. Screenshot of API endpoint doc def games(request): """ View to return games page """ team_schedule = Schedule('PURDUE') print(team_schedule) for game in team_schedule: away_total_rebounds = game.boxscore.away_total_rebounds print(away_total_rebounds) context = { 'team_schedule': team_schedule, 'away_total_rebounds': away_total_rebounds, } return render(request, 'games/games.html', context) {% for rebound in away_total_rebounds %} <div> <h4 class="white">{{ rebound.away_total_rebounds }}</h4> </div> {% endfor %} -
Django foreign key rest framework
Is there any way to display the name of the user in the "likedBy" section of the view, instead of the user id? Using django rest framework From view I get , ignore comments [ { "id": 3, "title": "ddsa", "content": "dsadsa", "created": "2021-02-10T08:07:42.758400Z", "updated": "2021-02-10T08:07:42.758400Z", "author": 1, "category": [ { "pk": 1, "name": "Life" } ], "likedBy": [ 1 ], "comments": [ { "id": 2, "content": "ghfa", "created": "2021-02-10T08:08:02.407950Z", "post": 3, "author": 1, "likedBy": [ 1 ] } ] } ] Views.py class PostViewSet(FlexFieldsMixin, generics.ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer permit_list_expands = ['category', 'comments'] Models.py class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() category = models.ManyToManyField(Category, related_name='posts') author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) likedBy = models.ManyToManyField(User, related_name='posts', blank=True) class Meta: ordering = ['-created'] Serializers.py class PostSerializer(FlexFieldsModelSerializer): class Meta: model = Post fields = '__all__' expandable_fields = { 'category': ('blogApi.CategorySerializer', {'many': True}), 'comments': ('blogApi.CommentSerializer', {'many': True}), } Any ideas ?????????????????????????????????????????????????????????????????? -
"unhashable type: 'dict'" on saving data to JSONField
I am trying to create an instance to a model named A having a JSONField .but getting an error ` "unhashable type: 'dict'". sample_data = {"name":"test", "countries":[1,2,3]} models.py from django.db.models import JSONField class A(models.Model): name = models.CharField(max_length=100) countries = JSONField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py class AViewSet(viewsets.ModelViewSet): queryset = A.objects.all() pagination_class = StandardResultsSetPagination permission_classes = (IsAuthenticated,) http_method_names = ['get', 'post', 'put', 'delete'] filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ['name'] def create(self, request, *args, **kwargs): serializer = ASerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(APIResponseParser("success", data=self.request.data), status=status.HTTP_200_OK) serializers.py class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = '__all__' Don't know what is wrong...please help -
Modeling and query on many to many models with through
I thought about using the custom through to record the comments that users makes on objects and record the date in addition to the comment text. I tried to build this model but I think it's wrong. It's my first time with M2M rel. class Category(models.Model): name = models.CharField(max_length=30) class Obj(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) desc = models.CharField(max_length=200) name = models.CharField(max_length=64) class User(models.Model): name = models.CharField(max_length=64) comment = models.ManyToManyField(Obj, through='Comments') class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) obj = models.ForeignKey(Obj, on_delete=models.CASCADE) data = models.DateTimeField() text = models.CharField(max_length=500) I would like to make queries based on the object id that can get any comments made on that item, the username and date for each of them. Also doing this query qs=Comments.objects.all() returns empty queryset -
In Django is it possible to send data from a view to itself when a page is refreshed
Is there a way to know which buttons are pressed in a page when returning to a view in Django? I am trying to implement a filter on a list of values in a Django app. The page has a list of checkboxes and 3 buttons to decide which values to show in the list. For example: a list will consist of values: db-productA-1, db-productA-2, db-productB-1, db-productB-2 and db-productC-1, db-productC-2 and the buttons will be: ProductA, ProductB, ProductC When the page is loaded for the 1st time, all buttons are un-pressed and all 6 dbs are listed. I then press button ProductA to filter the list. Pressing the button runs the view and I want to know which buttons were pressed, so I can decide which values to list. If I continue and press ProductB, I'd like to know that both buttons were pressed. Is there a way to retrieve the state of the elements in the page in Django? -
Django login.html and base_generic.html locations
According to: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication and https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Home_page the base_generic.html file should be included in /locallibrary/catalog/templates/ (inside the application folder), but the login.html file should be included in /locallibrary/templates/registration/ (at project root directory level) The login.html use the base_generic.html to extend its code. It is strange (from my beginner point of view), to have the templates base folder "more inside" than the login one. What if we had other applications with different base files? Which base file would the login registration file extend in that case? locallibrary/ # Website folder manage.py # Script to run Django tools for this project (created using django-admin) locallibrary/ # Website/project folder (created using django-admin) catalog/ # Application folder (created using manage.py) templates/ # Application templates folder base_generic.html templates/ # Templates folder registration/ # Registration folder login.html -
Uploading large files using Django and Ajax
I am trying to upload two files (tableFile, and zipFile) in Django using ajax POST. This code works when the zipfile is small. But I need to upload a large zipFile (about 10 GB). Is this possible? As you see I have added enctype="multipart/form-data" to the form, but this does not work. I also tried to define the following parameters in the settings.py DATA_UPLOAD_MAX_MEMORY_SIZE = 9450908240 FILE_UPLOAD_MAX_MEMORY_SIZE = 9450908240 But this also does not work. I get the following error invalid form <ul class="errorlist"><li>zipFile<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Below is my code models.py class Project(models.Model): id = models.AutoField(primary_key=True) from django.core.files.storage import FileSystemStorage from django.conf import settings upload_storage = FileSystemStorage(location=settings.FS_IMAGE_UPLOADS, base_url=settings.FS_IMAGE_URL) # files tableFile = models.FileField(upload_to="..", storage=upload_storage, blank=True, null=True) zipFile = models.FileField(upload_to="..", storage=upload_storage,) forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project fields = [ "id", "tableFile", "zipFile", ] views.py from django.views.decorators.csrf import csrf_protect, csrf_exempt #@csrf_protect @csrf_exempt def CreateProject(request): if request.method == "POST": form = ProjectForm(request.POST, request.FILES) if form.is_valid(): print ('valid form') else: print ('invalid form') print(form.errors) return render(request, "create_project.html", {}) return render(request, "create_project.html", context) html <form id ="form_id" method="post" enctype="multipart/form-data"> {% csrf_token %} <table id="image_list_table" class="table table-condensed"> <tr> <th>tableFile</th> <td><input type="file" id="tableFile" name="tableFile" required /> </td> </tr> <tr> <th>zipFile</th> <td> <input … -
TypeError: static() got an unexpected keyword argument 'document_root' in Django
After review questions before mine and apply changes Im keep receiving this error, as below. I tried to change all recomendations but it doesn't work anyway. I have not issue to recover static images, the problem comes when I attempt catch dinamic image from database. TypeError: static() got an unexpected keyword argument 'document_root' setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static #from django.utils.text import slugify from django.contrib.auth.models import User from django.shortcuts import render from backoffice.views.section import * from backoffice.views.user import * import backoffice.views.home import frontoffice.views urlpatterns = [ path('admin/', admin.site.urls), path('backoffice/', backoffice.views.home.management, name="backoffice"), # all list area path('backoffice/all_sections', SectionListView.as_view(), name="all_section"), path('backoffice/all_users', UserListView.as_view(), name="all_users"), # all frontoffice area path('', frontoffice.views.home, name="home"), path('about/', frontoffice.views.about, name="about"), path('contact/', frontoffice.views.contact, name="contact"), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model class Profile(models.Model): """ Model Profile extending funcionalities from our user model""" user = models.OneToOneField(User, on_delete=models.CASCADE) section = models.ForeignKey(Section, on_delete=models.CASCADE) ceo = models.BooleanField() employee = models.BooleanField() seller = models.BooleanField() guess = models.BooleanField(default=True) photouser = models.ImageField( upload_to='backoffice/static/avatars', default='backoffice/static/avatars/', blank=True, null=True ) cargo = models.CharField(max_length=100) notas = models.TextField(blank=True) def __str__(self): """Returning username.""" return self.user.username html … -
ChainedManyToManyField not working properly in django
I am trying to make dependent drop down in django admin page for models : class ItemCode(models.Model): **Name=models.CharField(max_length=50,blank=True,null=True)** def __str__(self): return self.Name class Vendor(models.Model): first_name = models.CharField(_('first name'), max_length=150, blank=False) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), blank=False) PhoneNo=models.CharField(_('Phone No'),max_length=150, blank=False) # new **Item=models.ForeignKey(ItemCode,on_delete=models.CASCADE,verbose_name="Item** Code",blank=True,null=True) class Offer(models.Model): Auction_id=models.CharField(max_length=20,blank=False,null=False,verbose_name = "Auction ID") Item=models.ForeignKey(ItemCode, on_delete=models.CASCADE,blank=True,null=True,unique=False,related_name='itemcode') Vendor = ChainedManyToManyField( Ven, chained_field="Item", chained_model_field="Name") But Vendor is showing all the vendor instead of filtering Vendor list as per Item.Please help! -
How to add(set) the ES6 59 atom editor? W104 - 'let' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz)
enter image description here How to add(set) the ES6 59 atom editor? -
Django parsing json (from Webhooks)
I am trying to parse some json received from Mailchimp to a Webhook in my Django application. The format will look like this: { "type": "subscribe", "fired_at": "2009-03-26 21:35:57", "data": { "id": "8a25ff1d98", "list_id": "a6b5da1054", "email": "api@mailchimp.com", "email_type": "html", "ip_opt": "10.20.10.30", "ip_signup": "10.20.10.30", "merges": { "EMAIL": "api@mailchimp.com", "FNAME": "Mailchimp", "LNAME": "API", "INTERESTS": "Group1,Group2" } } } I have tried the following: def marketing_email_handler(request): if request.method == 'POST': reqtype = request.body['type'] reqdata = request.body['data'] reqemail = request.body['data']['email'] I received the error 'byte indices must be integers'. I've tried changing this to the below, however this results in an error 'TypeError: 'int' object is not subscriptable'. And doing request.json() also results in an error reqtype = request.body[0]['type'] reqdata = request.body[0]['data'] reqemail = request.body[0]['data']['email']