Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When posting a form using FormMixin in Detail View in django, it does not post data
I am trying to write comments on a post and which is in DetailView using FormMixin. When iI try to post the comment, it does not post it but just gives the CSRF data in the url bar. here is my View class PostDetailView(LoginRequiredMixin, FormMixin, DetailView): model = Post form_class = CommentCreationForm def get_success_url(self): return reverse('post-detail', kwargs={'pk' : self.object.id}) def get_context_data(self, **kwargs): print("********************") print("Context taken") print("********************") context = super().get_context_data(**kwargs) context['form'] = CommentCreationForm(initial={ 'post': self.object }) return context def post(self, request, *args, **kwargs): print("********************") print("Post taken") print("********************") self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): print("********************") print("Valid taken") print("********************") form.instance.author = self.request.user form.save() return super(PostDetailView, self).form_valid(form) this is what i get in url bar http://localhost:8000/blog/post/29/?csrfmiddlewaretoken=MFUjN61oQRLHOoBDKwfpc5vuklTW3nnhmtRXFlflOGeFyhEim1H8OBMsEnmZ6YaT&content=asdafdsf -
How to import node package in django template?
I want to add the wallet connect functionality in my project and there is only npm package for wallet connect and I don't know how can i import that and use that. right now i am getting error: Uncaught SyntaxError: Cannot use import statement outside a module , my node_modules file is inside the static folder right now. *both imports are not happening in following code. import WalletConnect from "static/node_modules/@walletconnect/client/dist/umd/index.min.js"; import QRCodeModal from "@walletconnect/qrcode-modal"; // Create a connector const connector = new WalletConnect({ bridge: "https://bridge.walletconnect.org", // Required qrcodeModal: QRCodeModal, }); // Check if connection is already established if (!connector.connected) { // create new session connector.createSession(); } if more information is required then tell me in comment section, I'll update my question with that information. Thank you! -
Django Error: 'ManyToManyDescriptor' object has no attribute 'all'
i am getting this error. i am trying to loop through posts to display the posts that are part of the collection. relevant info: models.py class Collection(models.Model): posts = models.ManyToManyField(Post, related_name='collection_posts', null=True, blank=True) views.py def collection_detail_view(request, pk): collection = Collection.objects.get(id=pk) posts = Collection.posts.all() #this is the error context = { 'collection': collection, 'posts': posts } return render(request, 'collection_detail.html', context) -
Product filter for Django categories and subcategories
There is a problem, confused in several things. Made some filter for categories, but it filters only for subcategories. When you click on the parent category, it's just a blank page, when you click on the child, everything is filtered well. And I got confused in the url, how do I output both the parent url and the child? I will be very grateful. Sorry for the Russian When i click on parent category pic, When I click on child category pic models.py class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField('Название', max_length=255) slug = models.SlugField('Ссылка', unique=True) def get_absolute_url(self): return reverse('jewel:category_detail', args=[ self.slug]) views.py def cat(request, cat_slug): products = Product.objects.all() main_categories = Category.objects.filter(parent=None) sliders = Slider.objects.all() cats = 0 if cat_slug: category_s = get_object_or_404(Category, slug=cat_slug) products = products.filter(category=category_s) context = { 'products': products, 'main_categories': main_categories, 'category_s': category_s, 'sliders': sliders, } return render(request, 'jewel/category_detail.html', context) urls.py path('category/<slug:cat_slug>/', views.cat, name='category_detail'), -
Perform google search then get result save in django database
i am learning Django tutorial, could you pls advise me how to edit cod to get search result to put into database? Below are my cod and sure that the rest of cod in this tutorial i did correctly and test complete, many thanks class HomeListView(ListView): """Renders the home page, with a list of all messages.""" model = LogMessage def get_context_data(self, **kwargs): context = super(HomeListView, self).get_context_data(**kwargs) return context def log_message(request): form = LogMessageForm(request.POST or None) if request.method == "POST": if form.is_valid(): query = form.save(commit=False) for j in search(query, tbs='qdr:h', num=10, start=0, stop=10, pause=2.0): message = j message.log_date = datetime.now() message.save() return redirect("home") else: return render(request, "hello/log_message.html", {"form": form}) -
Passing context to another view (returns None)
I have two views function and want to pass context to another view. def view_1(request): # code of view_1 context = {'a': a,'b': b} return render(request, view_1.html, context) view_1.html <p>{{ a }}</p> <p>{{ b }}</p> I can see the values in view_1.html def view_2(request): a = request.GET.get('a') b = request.GET.get('b') context = {'a': a, 'b': b} return render(request, view_2.html, context) view_2.html returns all context values as None. How to transfer the context into another view? -
How to get request.user.username in django logger?
I am trying to get the login username in Django logger but no luck and not able to figure out where I am doing a mistake. Please find my code: a)code in settings.py import logging import logging.config LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, #########formatter######################### 'formatters': { 'verbose': { 'format': '%(levelname)s - %(asctime)s-- %(module)s - %(process)d - %(thread)d - %(message)s' }, 'simple': { 'format': '[%(asctime)s] : %(levelname)5s : %(message)s:' }, }, #########################Handlers ################################## 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'abc.log', 'formatter': 'simple' }, 'console': { "class": "logging.StreamHandler", "level": "DEBUG", }, }, #################### Loggers ###############(A single Logger can have multiple handler ) 'loggers': { 'django': { 'handlers': ['file','console'], 'level': 'DEBUG', 'propagate': True, 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG') }, }, } b)code in views.py import logging logger = logging.getLogger("django") c)function in view.py where I am trying to show username. def retrievects1_view(request): if request.user.is_authenticated: logger.info('CTADashboard Page is opened!',request.user.username) logger.debug('My message with %s', 'args', extra={'user': request.user}) print(request.user.username) response = HttpResponse(content_type='application/ms-excel') -----Continue---- **O/p in the log file:** [2021-01-07 18:47:32,780] : INFO : "GET /exportctatot_data/? HTTP/1.1" 200 9728: [2021-01-07 18:47:45,202] : INFO : "GET /gensall/ HTTP/1.1" 200 82259: [2021-01-07 18:47:46,145] : INFO : Home Page is opened!: #**here username is not … -
saving audio file in django
How to save audio file but I'm not using form.py only views, HTML, models? models.py class Message(models.Model): messager_id = models.AutoField(primary_key=True) message_text = models.CharField(max_length=2000) message_title = models.CharField(max_length=2000, blank=True) sender = models.ForeignKey(Doctor, related_name='sender_doctor',on_delete=models.CASCADE) receiver = models.ForeignKey(Doctor, related_name='reciever_doctor',on_delete=models.CASCADE) send_message = models.DateTimeField(blank= True) read_message = models.DateTimeField(blank= True, null=True) mark_as_read = models.BooleanField(default=False) recording = models.FileField(upload_to='audio/', blank= True, null=True) views.py def writemessage(request, id): print("Please Write Message") docid = Doctor.objects.filter(doctor_id = id) print(docid) writemessage = Doctor.objects.exclude(doctor_id = id) cnt = {'writemessage':writemessage, 'docid':docid} if request.method == "POST": message_text = request.POST['message_text'] message_title = request.POST['message_title'] docotname = request.POST['receiver'] receiver = Doctor.objects.get(doctor_id=docotname) sender = Doctor.objects.get(doctor_id=id) send_message = timezone.now() # read_message = timezone.now() recording = request.POST['recording'] message = Message(message_text=message_text, message_title=message_title , receiver=receiver, sender=sender, send_message=send_message) message.save() return render(request, 'message.html') return render(request, 'writemessage.html', cnt) My error is: MultiValueDictKeyError at /message/writemessage/2 'recording' -
How to pass request object to serializer in django rest framework unit test
#model.py file class FileModel(models.Model): file = models.FileField(verbose_name=_('File')) title = models.CharField(max_length=255, verbose_name=_('Title')) start_time_to_creating = models.DateTimeField(verbose_name=_('Start Time To Creating')) created_time = models.DateTimeField(auto_now_add=True, verbose_name=_('Created Time')) time_to_deleting = models.DateTimeField(null=True, blank=True, verbose_name=_('when_it_will_be_deleted')) page_count = models.PositiveIntegerField(null=True, blank=True, verbose_name=_('Page Count')) row_count = models.PositiveIntegerField(null=True, blank=True, verbose_name=_('Row Count')) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('User')) #serializers.py file class FileSerializer(serializers.ModelSerializer): class Meta: model = FileModel fields = ['id', 'file', 'title', 'start_time_to_creating', 'created_time', 'time_to_deleting', 'page_count', 'row_count'] #views.py file class FileListByUserView(generics.ListAPIView): queryset = FileModel.objects.all() serializer_class = FileSerializer filter_backends = (DjangoFilterBackend, OrderingFilter) filterset_class = FileFilter ordering_fields = ['created_time', 'title'] ordering = ['-created_time'] def get_queryset(self): user_id = self.kwargs.get('user_id') return super().get_queryset().filter(user=user_id) #urls.py file urlpatterns = [ url(r'^list/(?P<user_id>[0-9]+)/?$', FileListByUserView.as_view(), name='file-list-by-user') ] I serialize my FileModel model with FileSerializer and get it as a response. I want to test this. but I could not give the request object to the FileSerializer serializer that I used in unit test. So the file url does not match the data in the response because I cannot make the absolute url and it falls into error. from rest_framework.test import APIClient class TestBase(TransactionTestCase): reset_sequences = True def setUp(self): super().setUp() self.client = APIClient() def test_list_by_user(self): response = self.client.get(reverse('file-list-by-user', kwargs={'user_id': 1})) self.assertEqual(response.status_code, 200) file_models = FileModel.objects.all() file_serializer_data = FileSerializer(instance=file_models, many=True, context={'request': }).data content = str(response.content, encoding="utf8") … -
Is it possible to implement websockets in DjangoRestFramework?
Is it the right practice to use WebSockets in DjangoRestFramework and if not which technology or framework could be used to do so ? Thanks in advance. -
Access session variables from render funcition of the plugins in Django Cms
I have a view called create_pdf(request), which takes a json from the body of the httprequest, and I have some plugins defined in a page (/input_url). After rendering the page, I save it to pdf in here: pdfkit.from_url(input_url, output) Being the output the folder I want the pdf in. I want to fill the plugins with the info contained in the json, but the only way to access it is by saving the json in a folder and open the file in each of the plugins. Is there anyway to save globally the instance of the json by session and access it from the render function of the plugins? I know I can save the info in a session variable from the view, but I don't know the way to access to it from the render function of the plugin. Thanks for helping. -
Django, how to display comments on a blog post in post template only for login user
Django, how to display comments on a blog post in post template only for login user , i made these below mentioned models & views. Now my comments are successfully storing in database with name of user but the problem is its not shown on post . so far only count is displaying to see how many comments posted so far! def get_comments(self): return self.comments.all().order_by('-timestamp') class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) commentfield = models.TextField() post = models.ForeignKey(Blogpost, related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.user.username **My Forms** from django import forms from .models import Blogpost, Comment class CommentForm(forms.ModelForm): commentfield = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Type your comment', 'id': 'usercomment', 'rows': '4' })) class Meta: model = Comment fields = ("commentfield",) **My Blog Post Views** def blogpost(request, year, month, day, post): category_count= get_category_count() latest = Blogpost.objects.order_by('-publish')[0:4] post = get_object_or_404(Blogpost, slug= post) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() return redirect('.') context = {'post':post, 'latest': latest, 'category_count': category_count, 'form': form, } return render(request, 'blog/blogpost.html', context) **My Templates** <div class="post-comments"> <header> <h3 class="h6">Post Comments<span class="no-of-comments"> ({{ post.comments.count }})</span></h3> </header> {% for comment in post.get_comments %} <div class="comment"> <div class="comment-header d-flex justify-content-between"> … -
How do I use a different EMAIL_BACKEND for certain emails in django
I'm trying to send emails from 2 different backends. Most emails are being sent via AWS SES but I want a few from Outlook365 (because these will actually be stored/reviewed). So within settings.py I have EMAIL_BACKEND = 'django_ses.SESBackend' to use the AWS SES backend. I'm then trying to create a new connection when I want to send from Outlook as follows: with get_connection( backend = 'django.core.mail.backends.smtp.EmailBackend', host = 'smtp.outlook.office365.com', port = 587, user = 'myuser@mydomain.co.uk', password = 'password!', use_tls = True, ) as connection: email = EmailMultiAlternatives( subject=context['subject'], body=text_message, from_email='myuser@mydomain.co.uk', to=[user.email], connection=connection ) email.attach_alternative(html_message, "text/html") email.send() This generates the error: smtplib.SMTPSenderRefused: (530, b'5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [LO2P265CA0076.GBRP265.PROD.OUTLOOK.COM]', 'myuser@mydomain.co.uk') However, if I set these within settings.py (instead of using AWS) it will work (but means all other emails also go from here). Why isn't my get_connection working and how do I fix it? -
How can I refer to other urls' captured values in Django?
So, I am writing code with Python and Django (and other web dev requirements). from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path('wiki/<str:name>/', views.info, name="info"), path("create", views.create, name="create"), path("results", views.search, name="search"), path("wiki/<str:name>/edit", views.edit, name="edit") ] The problem I am facing is that in path("wiki/<str:name>/edit", views.edit, name="edit"), I get an error: NoReverseMatch at /wiki/Django/> Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['wiki/(?P[^/]+)/edit$']> And I want to refer to the url in path('wiki/<str:name>/', views.info, name="info") Please help me fix the error -
why compressing this less file doesn't work?
Story is that I got to work in old Django project. I did some changes to models, and only models. But now I get error when compressing less file using django-compressor. What is odd: I can compress files locally, but server pipeline fails. The command that fails is: python manage.py compress --force error I get is: CommandError: An error occurred during rendering /code/app/portal/templates/portal/presentation_company.html: ParseError: Unrecognized input. Possibly missing '(' in mixin call. in /var/www/mojksiegowy24.pl/static/less/presentation.less on line 239, column 32: 238 background: #00AFBE; 239 .transition; 240 } whole part of less file: .print-button { text-align: right; margin-bottom: 20px; margin-top: 20px; a { .fa { padding-right: 10px; } text-decoration: none; font-size: 12px; line-height: 30px; display: inline-block; color: #fff; background: #C2C2C2; border-radius: 2px; padding-left: 10px; padding-right: 20px; &:hover { background: #00AFBE; .transition; } } } I checked linux / windows end line chars and it is ok. Please help. I'm stuck, .less noob with no idea what to do. My biggest problem is that reverting changes done to models doesn't solve problem! And I'm not sure if that's important: Server uses GitLab Pipelines to deploy Dockerized Django app. -
Django tests logs Bad or Unauthorized requests
I recently upgraded from django 1.11 to django 3.0. Currently, when i launch python manage.py test, django logs any bad or unauthorized requests from my tests, the fact is : it did not log such while on 1.11 Exemple : .2021-01-06 18:04:20,374 Unauthorized: /api/image/create ..2021-01-06 18:04:20,426 Bad Request: /api/image/transfer/create .2021-01-06 18:04:20,436 Bad Request: /api/image/transfer/create ... ---------------------------------------------------------------------- Ran 3 tests in 0.008s OK Preserving test database for alias 'default'... Did i miss something while reading django changelog ? I'd like some light because i do not want to make a distribution without knowing if it's only warning or real error. -
Python crash course 19-5 object has no attribute 'owner'
learning python through the python crash course book. Having this issue where somehow it says that there is no attribute 'owner' for each blogpost when there seems to be one? Would appreciate any guidance, cheers all! Added to the very bottom of settings.py #MY SETTINGS LOGIN_URL = 'users:login' models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=50) text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title This is the code when i run django shell to see the owner associated with each blogpost from blogs.models import BlogPost for a in BlogPost.objects.all(): print(a, a.owner) My first post! aaaaaa ll_admin Second blog post ll_admin No season 2 in product ll_admin ll_admin is this the tutle ll_admin ssd ll_admin ssaaa ll_admin views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import BlogPost from .forms import BlogPostForm # Create your views here. def index(request): """The home page for blogs""" return render(request, 'blogs/index.html') @login_required def posts(request): """Show all blogposts""" posts = BlogPost.objects.filter(owner=request.owner).order_by('date_added') context = {'posts': posts} return render(request, 'blogs/posts.html', context) @login_required def new_post(request): """Add a new blogpost""" if request.method != 'POST': #No data submitted; create a blank … -
can't install. pip install -r requirements.txt
ERROR: Command errored out with exit status 1: 'e:\django-pos-master\venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Use rs\asada\AppData\Local\Temp\pip-install-82_9dan8\pillow_f761b25e426a43f6891c453cc664459a\setup.py'"'"'; file='"'"'C:\Users\asada\AppData\Local\Te mp\pip-install-82_9dan8\pillow_f761b25e426a43f6891c453cc664459a\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"' r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\asada\AppData\Local\Temp\pip-record-lt_0q0si\install- record.txt' --single-version-externally-managed --compile --install-headers 'e:\django-pos-master\venv\include\site\python3.9\Pillow' Check the logs for full com mand output. -
Update entry with file instance DRF, Vue.js 3
I have a table that has a models.FileField in it. I'm able to create the file from a Vue.js website POST request, but when I want to update the instance I have to upload the file again. The problem is not from Vue.js, because I can't update even using the DRF pre-built page. How can I update the instance without having to upload the document again? -
is there any way to use variables like {{ ct{{ forloop.counter }} }} in HTML File in django?
views.py: for i in range(1, 4): params[f"ct{i}"] = '<h1>ct'+i+ '</h1>' index.html: <h1>{{ct{{forloop.counter}} }}</h1> Is there any way to use <h1>{{ct{{forloop.counter}} }}</h1> in My HTML File? -
How to save django manytomany field without through table
I face a vicious cycle that I cannot break out of; Lets say I have a following model: class AgregatorProductCoupon(models.Model): AgregatorProductId = models.ManyToManyField(Product, related_name="coupons", db_column='AgregatorProductId', verbose_name=_("Agregator Product Id")) class Meta: managed = True db_table = 'AgregatorProductCoupon' when I try to save an instance, I get an integrity error stating "<AgregatorProductCoupon: AgregatorProductCoupon object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. but when I try to save without the m2m rel, I obviously get an error for a required field missing. Cannot insert the value NULL into column 'AgregatorProductId', table 'test_dbo.dbo.AgregatorProductCoupon'; column does not allow nulls. INSERT fails. I cannot redesign the tables as they are bound to other places too. How to go about it? Any help would be much appreciated. -
PostgreSQL and Django Query for report not working
I am using Python Django and PostgreSQL to build our report app. I am using below mention query to find some details. the query mention below is running fine in PostgreSQL command line and giving result in 2 sc for 2 million cards but when i i am try the same in Django application it is taking too much of time and the web page is expired while running this query. can anyone help how to make query faster in Django? Or help me in correcting this query to be used in Django rows = M_Assign.objects.raw(''' select C.id,M."merchant_name",C."MERCHANT_ID",S."store_id" Owning_Store_ID ,S."store_name" Owning_Store_Name,F."franchisee_name" Owning_Group,C."ACCOUNT_NUMBER",C."STORE_ID",C."GIFT_LIST_REF" FROM vdaccount_card_assign C INNER JOIN vd_merchant_master M ON C."MERCHANT_ID"=M."merchant_id" AND C."MERCHANT_ID"='003561002966107' INNER JOIN vd_store_master S ON S."store_id"=C."GIFT_LIST_REF" OR C."GIFT_LIST_REF"='' INNER JOIN vd_franchisee F ON S."franchisee_id"=F."franchisee_id" ''') Regards Sachin -
xhtml2pdf not converting css properly django
hey guys so i have been using this library for a while now and i just encounter this error that by using this library its not converting my css of my html properly to pdf, i used this library to generate voucher internet for my client, does anybody now how can i fix this? thanks, here's my code voucher.html <!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> * { box-sizing: border-box; } .row { display: flex; margin-left:-5px; margin-right:-5px; } .column { flex: 50%; padding: 5px; } table { border-collapse: collapse; border-spacing: 0; width: 100%; border: 1px solid #ddd; } th, td { text-align: left; padding: 16px; text-align: center; } tr:nth-child(even) { background-color: #f2f2f2; } @page { size: letter landscape; margin: 2cm; } </style> </head> <body> <div class="row"> {% for data in akun %} <div class="column"> <table> <tr> <th colspan="2">Voucher Internet 1 Hari</th> </tr> <tr> <td>Username</td> <td>{{akun.username}}</td> </tr> <tr> <td>Password</td> <td>{{akun.password}}</td> </tr> <tr> <td>Harga</td> <td>{{akun.harga}}</td> </tr> <tr> <td colspan="2">Mikadmin.net</td> </tr> </table> </div> {% endfor %} </div> </body> </html> view.py def voucher_profile(request): mikrotik_session = request.session.get("mikadmin") template = get_template('voucher.html') host = mikrotik_session.get("host") username = mikrotik_session.get("username") password = mikrotik_session.get("password") con = routeros_api.RouterOsApiPool(host=host,username=username,password=password,plaintext_login=True) api = con.get_api() content = api.get_resource('ip/hotspot/user/profile') content_user = api.get_resource('ip/hotspot/user') username_paket_profile = request.POST['name-profile'] valid … -
Which approach would be better to build a application?
First Approach: Building a application in a traditional way that is when we want data from database connect to database and fetch it. Second Approach: Another way is to build a web service/API and hit that endpoint and it returns data. I want to build both web and mobile application.So, I thought to build a web service/API and utilize it in web and mobile application. First of all,What I am telling is it correct? If Yes, Whether this approach is correct? Or I should build using first approach? Is there any advantage and disadvantages of both? -
Django PWA session is not maintained
I have created an application using Django and PWA and everything works good except for the session. When I enter into the application after a couple of hours It asks me to login in again. However, if I use the web instead of the app my session is maintained forever. How can I solve It and maintain the pwa user session maintained? Thank you!