Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any possible way to implement a drag and drop html editor in the django admin panel
I have a website and there will be some people who I'll give the admin login credentials to but they don't know anything about html, css... I want it so that within the page they could edit it like if it was wordpress. I searched up for it and found something similar named django-cms. Is there any possible way to use a drag-and-drop html editor within the page? Notes: Website is built with django, python3.9 and hosted on heroku. -
How to send emails in django using asyncio?
I'm trying to send emails asynchronously in Django using asyncio but the below code is not working for me. async def new(request): if request.user.profile.role == 'sa' or request.user.profile.role == 'e': if request.method == "GET": raise Http404 elif request.method == "POST": form = TaskForm(request.POST) if form.is_valid(): task =form.save() subject = "New Task" message =render_to_string('new_task_email.html', { 'task' : task }) user =await sync_to_async(User.objects.get)(id = task.assign_to.id) send_mail_async = sync_to_async(user.email_user) asyncio.create_task(send_mail_async(subject, message , EMAIL_HOST_USER)) messages.success(request,"New Task has ceated") else: messages.warning(request,"Please Enter a valid data") return redirect('tasks') else: raise Http404 but whenever a new task is created and then sending mail to the user getting this error. SynchronousOnlyOperation at /work_order_panel/tasks/new/ You cannot call this from an async context - use a thread or sync_to_async. -
How to redirect in django after returning response?
I have a some function that in the end download file and I need to add here redirect to another page. I don't know why I can't use return more than ones. How to redirect after returning response? response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response -
How to have my site in google search results
I've created a property in google search console for my website Oghyanoosedanesh.ir but after about 5 days it still says "Processing data, please check again in a day or so" I just want my site to be indexed by google but can't see anything when search for site:Oghyanoosedanesh.ir My site has sitemap and title and descriptions for pages What should I do if I want to see my site un search results when search for its name I don't know a lot about SEO * -
I am trying to login into admin panel of my Django rest framework project but giving me error not able to login into it using Python DRF [closed]
I am trying to login into admin panel of my Django rest framework project but giving me error- Error is- Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive. I already assigned is-staff,is-active,is-superuser=True but still it showing the same error. i am using Mysql workbench could someone please help me to find the right ans -
Defining a custom Serializer Field for related models gives TypeError
My question is similar to this unanswered question. I'm trying to implement a serializer field to my project. I'm hitting a roadblock where I need to nest other models in a single request, but it throws a TypeError: Object of type ____ is not serializable. Here's what my models.py code's pseudocode looks like: (GameIndexPage has many GameBlogPage has one Game) (I omitted things I think is irrelevant) @register_snippet class Game(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class GameBlogPage(Page): parent_page_type = ['blog.GameIndexPage'] introduction = models.TextField game = models.ForeignKey 'web_api.Game' album_image = models.ForeignKey 'wagtailimages.Image' body = StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) published_date = models.DateTimeField() class GameIndexPage(Page): subpage_types = ['GameBlogPage'] parent_page_type = ['home.HomePage'] introduction = RichTextField image = models.ForeignKey 'wagtailimages.Image' @property def children(self): return self.get_children().specific().public().live() ... api_fields = [ APIField('introduction'), APIField('image'), APIField('children', serializer=GameBlogPageField()) ] Now, here's my implementation of the serializer field in fields.py: class GameBlogPageField(Field): def to_representation(self, queryset): pages = [] for child in queryset: post_dict = { "id": child.id, "title": child.title, "introduction": child.introduction, "game": child.game # where it all goes wrong #"blog_authors": child.blog_authors, #"published_date": child.published_date, #"album_image": child.album_image, } pages.append(post_dict) return pages Removing the game value gives me this result. I commented where I want the nested … -
my problem is template file 'UserAccount' not found, i set the app in the setting and create a directory in app and create html file in directory
from django.shortcuts import render Create your views here. def login(request): context = {} return render(request, 'UserAccount/login.html', context) -
Template to View
I Wanted to pass item id of an object from template to view. The code basically is for linking the comments with specific items what needs to be done to access that item id in view. Below are the images for template and view code :- [enter image description here][1] [enter image description here][2] Template:- [1]: https://i.stack.imgur.com/GfhHh.jpg View:- Comment to save comments [2]: https://i.stack.imgur.com/MQ1jm.jpg -
Django admin field form add css and show/hide password
I have extended a Change password template, but I want to add on all the fields a button for showing/hiding password. How can I do this, below is the template and as well as increasing the height of the input text boxes : {% extends '../base.html' %} {% block content %} <h2>Password change</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">CHANGE MY PASSWORD</button> </form> {% endblock %} This was a Django admin template registration/password_change_form.html but I have overriden it. Below is what I get : -
Failed conversion to JSON for JsonField
I'm trying to convert tuple to JSON and store it in JSONField. I have code like this: class Data(models.Model): status = models.JSONField(null=True) def get_status(self): status_choice = ( ('0', 't'), ('1', 't2'), ('2', 't3'), ) status_dict = [{'id':status[0], 'name':status[1]} for status in status_choice] self.status = json.dumps(status_dict, indent=4) return self But the result is very awful, I get a line like this: "status": "[\n {\n \"id\": \"0\",\n \"name\": \"t\"\n },\n {\n ... Although if I run my function in plain Python, everything looks great. Maybe there's some Django argument I need. -
How do I get Django PK value in a CBV whithout appearing in the URL?
I basically want the PK of the user who has logged in to my website. I don't want it to appear in the URL so I cannot use kwargs. But since the user has logged in already, I think there must be a way to access the user's primary key. Do you have any idea I can do this? I scoured StackOverflow for a long time but I did not get any answer to my query because most of the questions were asking how to get the PK when it is send in the URL. Please help! -
Creating a sitemap class returning URL with two arguments
I have a set of items = [a,b,c] And I have a page that takes in two items and compare them. So the URLs look like this: http://127.0.0.1:8000/compare/a/b http://127.0.0.1:8000/compare/a/c http://127.0.0.1:8000/compare/b/c How could I make a sitemap class to represent all of them? *This is my sitemap class with one argument class ItemsSitemap(Sitemap): changefreq = "monthly" priority = 0.8 def items(self): return Items.objects.order_by('id') def location(self, obj): return '/items/%s' % (obj.id) -
Flask to Django conversion, flask.url_for, flask.request.url
I am following the Google OAuth Guide in Django with a Flask example. But cannot figure some of the code below out. Precisely, how could be flask.url_for, flask.request.url be converted into Django code. # Flask code flask.url_for('oauth2callback', _external=True) # my Django code: just the url??? 'http://localhost:8000/api/oauth2callback' # Flask code authorization_response = flask.request.url # my Django code: but it would not work authorization_response = request.url On flask.request.url I could not find any docs, any information what it returns state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'], state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) # Store the credentials in the session. # ACTION ITEM for developers: # Store user's access and refresh tokens in your data store if # incorporating this code into your real app. credentials = flow.credentials flask.session['credentials'] = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes} -
Django CountrySelectWidget not working when Debug=False
I am using Django Countries and the CountrySelectWidget to show the country flag after the CountryField on my form. This works fine when Debug is set to True and I can see the flag fine. However when Debug is set to False the flag image shows as broken. I have set my static files and media files to be collected and served when DEBUG is False but I don't think that the CountrySelectWidget involves static files. Django Countries is installed on my Django environment and the CountryField is working fine both when Debug is True and when it is False. So I don't know why the Widget doesn't seem to be working properly when Debug is False. My forms.py is as follows: from django import forms from django_countries.widgets import CountrySelectWidget from catalog.models import emaillist class Subscribe(forms.ModelForm): class Meta: model = emaillist fields = "__all__" widgets = {'country': CountrySelectWidget()} And my model is: class EmailList(models.Model): email = models.EmailField() country = CountryField(blank_label='(select country)', default = 'South Africa') def get_absolute_url(self): # new return reverse('download-file') I'm using Django 3.1.7 If you can help me I would be very grateful! Best wishes, Cameron -
Connecting BigQuery to Django and React
I love working with Django as my backend and React as my frontend and I think they make an amazing combination. However, I would like to use BigQuery as my database and I'm having a hard time on thinking about how should i go about building the system flow. What I would like to do is to read data from BigQuery and display on my frontend (React) and also would love to insert data into my BigQuery database through a form in React, which then could be somehow processed in Django and inserted into the BigQuery. I know this should be possible by creating a REST API using Django Rest Framework but I'm currently lost and I could not find any article or video guidance anywhere on the internet. Any reference or help would be highly appreciated. Thank you! -
How to send attachments to a Django webapp using Rest framework?
I have been given this chat app made in Django and asked to add a feature that helps send attachments in the chat like documents and images. I am really new to this and have no idea what to do. I did found the source from where this chat app has been developed: Simple Chat App using Django Rest Framework can anyone please help? -
Better alternative to polling when waiting for a HTTP request in django?
I have a django application that needs to communicate with a backend service. Usually I would do it like this: def my_view(request, id): backend_response = requests.get('http://backend.com/{}/'.format(id)) return HttpResponse(status=backend_response.status_code) Unfortunately the backend service in this case does not work like that. Instead of including the results in the HTTP response it will send them in a separate HTTP request. My current approach is to write the results to the database and wait for them in the original request handler: def my_view(request, id): requests.get('http://backend.com/{}/'.format(id)) while True: sleep(1) try: backend_response = BackendResponse.objects.get(id=id) break except BackendResponse.DoesNotExist: pass return HttpResponse(status=backend_response.status_code) This feels very weird to me. Are there better solutions for this problem? -
RelatedObject does not exist when populating form
I am making django app and i have a problem because i can not populate form with User data from Profile model. I get an error User has no profile, RelatedObject does not exist. views.py def profileView(request): profileData = Profile u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) args = { 'profile': profileData, 'u_form': u_form, 'p_form': p_form} return render(request, 'shop/profile.html', args) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) user_image = models.ImageField(upload_to='pictures', default='pictures/man.png') def __str__(self): return f"{self.user.username} Profile" forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['user_image'] -
Is there any way to prioritize some objects in Django filter?
I've a language model and there is a list of languages in the database. List is like that: [ { "name": "Arabic", "code": "ar" }, { "name": "German", "code": "de" }, { "name": "Turkish", "code": "tr" }, { "name": "English", "code": "en" }, { "name": "French", "code": "fr_FR" } ] I want to order them by their name. But I want to prioritize two of them: English and German. I know in django we order them like: Language.objects.all().order_by("name") But how can I prioritize these two objects? Thanks. -
Using reverse proxy django
hi i've got a django app and i've split the setttings into production,staging and development. How can I use a reverse proxy to differentiate this three domains. For example using apache2, listening at port 80 as an example, and all domains pointing to the same IP) hey this request is for example.com, route it to the wsgi at 3333 (where the wsgi for the dev server lives), hey this request is for example-example.com, route it to the asgi at 3335 (where the asgi for the production server lives. Thanks -
How to only fetch the ArticleImage items that match the author id of Article?
So lets say that User with id "1" created an Article, but User only wants to show the article images in ArticleSerializer that match with the User id "author" of ArticleImage. Now why would I do this? Reason is that another User with id "2" could create an ArticleImage for the same Article that User with id "1" created. How can I do it? class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=40,unique=True,default='undefinedusername') class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) class ArticleImage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.FileField(upload_to='images',null=True,blank=True, validators=[validate_file_extension]) article = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True, related_name='articleimages') author = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True,related_name='articleimages_set') class ArticleSerializer(serializers.ModelSerializer): articleimages_set = ArticleImageSerializer(source='articleimages',required=False,many=True) class Meta: model = Article fields = ('id','author','caption','articleimages_set') -
How to pass parameter to integrate multi interface by Django request?
I want to define the interface below: path('pg', product_group.get_product_group, name='get_product_group'), path('pg/int:pk/', product_group.product_group_detail, name='product_group_detail'), path('pg/name/str:request_name/', product_group.get_product_group_by_name, name='get_product_group_by_name'), path('pg/short_name/str:request_name/', product_group.get_product_group_by_short_name, name='get_product_group_by_short_name'), @api_view(['GET']) def get_product_group(request): How could I integrate them to one or two interface then using parameter to split them in function? -
How Can I get Monthly Income, Expenditure, Net Income and display in django Template using a loop
I am working on Django project with two models; Expenditure and Income. I want to get Total Income, Total Expenditure, and Net Income for each month displaced in a table. The Net Income should be Total Income minus (-) Total Expenditure. And here I have this models (Income and Expenditure are same) are having the same properties as shown below. class Income(models.Model): description = models.CharField(max_length=100, null=False) category = models.CharField(max_length=100, choices=CATEGORY_INCOME, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) amount = models.PositiveIntegerField(null=False) remarks = models.CharField(max_length=120, null=True) date = models.DateField(auto_now_add=False, auto_now=False, null=False) addedDate = models.DateTimeField(auto_now_add=True) Here what I have tried in my views file: def monthly_Income(request): total_monthly_income = Income.objects.annotate(month=TruncMonth('date')).values('month').annotate(total_monthly_income=Sum('amount')) total_monthly_expenses = Expenditure.objects.annotate(month=TruncMonth('date')).values('month').annotate(total_monthly_expenses=Sum('amount')) net_monthly_income = total_monthly_income - total_monthly_expenses context = { 'total_monthly_income': total_monthly_income, 'total_monthly_expenses':total_monthly_expenses, 'net_monthly_income':net_monthly_income' } In my django Template this is how I am trying to display the results. {% for income in total_monthly_income %} {{ income.total_monthly_income | intcomma }} {{ total_monthly_expenses }} {{ net_monthly_income }} {% endfor %} The problem here is that, I am able to get the total monthly income but not able to get the total monthly expenses and net income according to each month of the year. Someone should kindly assist me get the right result accordingly. -
Django how to solve UnicodeEncodeError: 'charmap'?
I am trying make my project multilanguage. I install rosetta. When I write django-admin makemessages -l tr, console gives an error: (myvenv) C:\Users\USER\OneDrive\Documents\GitHub\otc>django-admin makemessages -l tr UnicodeDecodeError: skipped file QuickStartClientCom.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x96 in position 1724: invalid start byte) UnicodeDecodeError: skipped file QuickStartServerCom.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x92 in position 2291: invalid start byte) UnicodeDecodeError: skipped file docindex.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x92 in position 1113: invalid start byte) UnicodeDecodeError: skipped file misc.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x92 in position 407: invalid start byte) UnicodeDecodeError: skipped file package.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x85 in position 2807: invalid start byte) Traceback (most recent call last): File "C:\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\USER\OneDrive\Documents\GitHub\otc\myvenv\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\commands\makemessages.py", line 382, in handle potfiles = self.build_potfiles() File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\commands\makemessages.py", line 424, in build_potfiles self.process_files(file_list) File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\commands\makemessages.py", … -
Supplying remote JSON data for Typeahead / Bloodhound with Django / Python
I'm trying to replicate functionality of this Typeahead remote example, but I can't figure out how to supply the data in the way Typeahead / Bloodhound wants it, nor what datumTokenizer or queryTokenizer are for. In Python / Django views.py I've got: nouns = ['apple', 'banana', 'pear'] return JsonResponse({'results': noun_results}) reaching the site as: {"results": ["apple", "banana", "pear"]} Yet for 'kings' the example returns: [{"year": "1949","value":"All the Kings Men","tokens":["All","the","Kings","Men"]}] Need we return it in this format? If so, how? How can we make a simple replication of the example?