Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Existing Django site implementation of wagtail. How to get RichTextField to show in admin?
I have added wagtail to an existing Django site. I wish to change the content part of the model to a RealTextField. What I had and what I have altered is shown below: class Post(models.Model): content = models.TextField() class Meta: ordering = ['-date_added'] def __str__(self): return self.title Post(models.Model): content = RichTextField() class Meta: ordering = ['-date_added'] content_panels = Page.content_panels + [ FieldPanel('content', classname="full"), ] def __str__(self): return self.title class Meta: ordering = ['-date_added'] content_panels = Page.content_panels + [ FieldPanel('content', classname="full"), ] def __str__(self): return self.title -
Why does javascript create spurious images using ajax?
Firstly I must apologise for the length of the code in this question. It is based on Django and javascript and I have stripped out as much as I can to give a working example The challenge is to create a composite image using a random number of rooks - all black rooks on the top row and all red rooks on the bottom row This works perfectly when the page is first loaded, but if I click on the New Board button, then randomly red rooks might appear in the top row, or black in the bottom (The image was downloaded from here) html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> </head> <body> {% block content %} <div style="display:none;" id="pieceImages"></div> <p>Red:<span id="red-count"></span> Black:<span id="black-count"></span></p> <canvas id="top-image" style="background-color:#ffff00;"></canvas> <p><button id="new-board">New Board</button> {% endblock content %} <script type="text/javascript" src="{% static 'js/test.js' %}"></script> </body> </html> urls.py #pages/urls.py from django.urls import path from .views import HomePageView, NewBoard urlpatterns = [ path('', HomePageView.as_view()), path('new-board', NewBoard.as_view(), name= 'new-board'), ] views.py # pages/views.py import os import io import random import base64 from PIL import Image as PilImage from django.views.generic import View from django.shortcuts import render from django.http import JsonResponse … -
Circles not showing up in webpage when created via JavaScript (Django, Python)
I have made a page in my Django webapp that displays an image and allows the user to click on the image and should place a circle on top of the image where the user clicked. The following code is able to get the location of the mouse click on the image, and adds a tag to the html in the right place, but it won't actually show up on the page. If I hard code a circle into the html, it shows up just fine. It also seems like the mouse is on a different coordinate system than the SVG element... I have tried event.x, event.pageX, and event.clientX but noticed no difference. Even if I hard code the position of the circle, it won't show up on the click html: {% extends 'main/base.html' %} {% block head_content %} {% load static %} <script type="text/javascript" src="{% static 'js/click.js' %}"></script> {% endblock %} {% block content %} <div class="my-div"> <div> <h1>The Page!</h1> </div> <form enctype="multipart/form-data" method="POST" action="/mysite/nextpage/"> {% csrf_token %} <svg id="svg"> <image href="data:image/png;base64,{{ my_img }}"/> <!-- Placing a circle manually works just fine! --> <circle cx='50' cy='150' r='50' fill='red'/> </svg> <input type="submit" name="submit" class="submit-btn"></input> </form> </div> {% endblock %} Javascript: … -
get the name of the qs lookup instead of the value
I am trying to display the total number of tickets created in a day and have them show up as a dashboard feature . it only gives me the "0" for resolved and "p" for paused instead of the actual "Paused" or "Open". So I am guessing the values being looked at in "Status" of my model Support Tickets is not being called right but i have no idea how to call the values I need @admin.register(TicketSummary) class TicketSummaryAdmin(ModelAdmin): change_list_template = 'admin/Webapp/ZoomAccount/ticket_summary_change_list.html' date_hierarchy = 'Created_At' def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'total': Count('Ticket_Number'), 'total_tickets': Count('Ticket_Number'), } response.context_data['summary'] = list( qs .values('Status') .annotate(**metrics) .order_by('-total_tickets') ) response.context_data['summary_total'] = dict( qs.aggregate(**metrics)) return response -
How to use loop for requesting from html template in Django
From html template say "createlist" I want to add link which actually request server to get one more object of image form to the "createlist" page. But when I run the code it actually happens only one time but I want maximum of 5 times this should be accepted. So here how I can use loop in html template so that it will get the request again and again up to the limit say 5. here is the template code - {% if morepicform %} {{ morepicform }} {% endif %} Want to add more pics? <a href="{% url 'createlist' 'morepic' %}" role="button"> <img src="static/auctions/plus-circle-solid.svg" height="20px" width="20px"></a> views function def morepic(request, morepic=''): return render(request, "auctions/createlist.html",{ "morepicform" : PictureForm(), "picform" : PictureForm(), "listform" : ListingForm() }) url pattern path function - path("createlist/<str:morepic>", views.morepic, name="createlist") Now how can I add the functionality of requesting "morepicform"? -
Cannot get Django to connect to MySQL within Dockerfile
I have been trying to get a Django project to connect to a MySQL database on my local computer using a Dockerfile. I would like to be able to do this so that I can use a container to host a website on AWS, so ideally I would like to use a Dockerfile only (not docker compose) as it makes installing it onto Elastic Beanstalk and Lightsail easy. I have created a repository on GitHub in the following location: https://github.com/MarkyMark1000/PYTHON_MySQL_Django_Docker I have tried all kinds of things such as using 'RUN apk update && apk add py3-mysqlclient' or trying to install python mysql connector, but I have no luck at present. If you could let me know what I need to do, I would be very grateful. Many thanks Mark -
Django: can't read urlopen responses's file as binary
I have a problem with file requesting. python 3.9.1, django 3.1.7 What i do: response = request.urlopen('some_good_address') response.class == <class 'django.core.files.base.File'> response.file.class == <class '_io.TextIOWrapper'> After that i need to read response as binary: base64.b64encode(response.read()) On 2.7 it was OK. -
Email automation for Amazon Orders - MWS API/SP API
I am trying to create a tool for sending automatic follow up ( review request, feedback request) for the Amazon order and I am using Amazon SES for the email service. I successfully connected marketplaces via login with Amazon and fetched user order, buyer email etc and sending emails to those buyer emails. SES shows they are delivered on the buyer email but I can't find them inside seller-buyer messages in amazon seller central. After playing around a bit I added my email as a verified sender on my own account then it sends the email and I can also see inside buyer-seller central. Now the problem is how can I verify my email as a verified email for other sellers who registered on my website via login with Amazon. Thanks in advance for the help. -
Django project is missing migrations, prodcution and development has different migrations
So I started working on a project that is right now on production but the preovious dev kinda made a mess with migrations (or maybe I am wrong), the migrations in developement and in production are not the same (he gitignored them) and I can not start working because there are missing migrations in development so the database is no fully migrated. Im thinking I can just delete all migrations in development, reset them but I don't think that is a good idea in production. What should I do? -
can't get Primary Key from kwargs
i have this views.py class AddToCartView(APIView): def post(self, request, *args, **kwargs): pk = self.kwargs.get('pk') print(pk) if pk is None: return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST) item = get_object_or_404(items, pk=pk) i am getting None from print(pk), what am i doing wrong? -
Python 3.8 DJANGO GCLOUD issue
Strange and frustrating issue. Have two django apps which require to be hosted on Google Cloud. The first app is currently active and being served, the second app will not give in. The situation is as following; Two python 3.8 django apps Two different cloud project with each dedicated MySQL 8.0 instances When runserver app one locally with glcoud first project activated and CLoud_sql_proxy to be listening for connections. It correctly connects to the Google MySQL insctance. (Development) D:\Development>Cloud_sql_proxy.exe -instances="someinstance:europe-west2:somename"=tcp:3306 2021/04/29 13:42:08 Listening on 127.0.0.1:3306 for someinstance:europe-west2:somenam 2021/04/29 13:42:08 Ready for new connections Now I am doing the same thing for the second app (not simultaneously), correct project activated and CLoud_sql_proxy to be listening for connections based on connection to the second Google MySQL instance. It will not connect to the MySQL instance, instead local is being used. if os.getenv('GAE_APPLICATION', None): is always true. Has anyone some tips? Maybe someone has experienced the same? Two apps work along the same lines, and cloud configuration is the same. Setting.py # https://docs.djangoproject.com/en/3.2/ref/settings/#databases import pymysql # noqa: 402 pymysql.version_info = (1, 4, 6, 'final', 0) # change mysqlclient version pymysql.install_as_MySQLdb() # Local development mode 24/04/2020 if os.getenv('GAE_APPLICATION', None): # Running on production App … -
Error 404 Nginx can't find media files. +Django
I was setting up basic Django site with nginx. When i navigate to the url of the file i get error 404 Not Found nginx/1.18.0 (Ubuntu) This is the conf file upstream django { server unix:///home/jo/testproject/testproject.sock; } # configuration of the server server { listen 80; server_name _; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media/ { alias /home/jo/testproject/media/; } location /static { alias /home/jo/testproject/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/jo/testproject/uwsgi_params; } } the media folder is in /home/jo/testproject/media and inside it i have media.gif, but ip/media/media.gif doesnt work when i write the ip in the browser i get Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. I think everything else i setup correctly -
How to use variable column name in filter in Django ORM?
I have two tables BloodBank(id, name, phone, address) and BloodStock(id, a_pos, b_pos, a_neg, b_neg, bloodbank_id). I want to fetch all the columns from two tables where the variable column name (say bloodgroup) which have values like a_pos or a_neg... like that and their value should be greater than 0. How can I write ORM for the same? SQL query is written like this to get the required results. sql="select * from public.bloodbank_bloodbank as bb, public.bloodbank_bloodstock as bs where bs."+blood+">0 and bb.id=bs.bloodbank_id order by bs."+blood+" desc;" cursor = connection.cursor() cursor.execute(sql) bloodbanks = cursor.fetchall() -
Implement Django SetPasswordForm
The Django documentation https://docs.djangoproject.com/en/3.2/topics/auth/default/#module-django.contrib.auth.forms I'm getting an error in my code below. tuple' object has no attribute 'get' def password_reset(request): if request.method == 'POST': form = SetPasswordForm(request.user) #Form.is_valid() is returning an error if form.is_valid(): #Do this else: return (request, 'home/reset_password.html', {'form': form}) form = SetPasswordForm(request.user) return render(request, 'home/reset_password.html', {'form': form}) -
Resend verification email in Django using Django-Verify-Email
I am using Django-Verify-Email 1.0.6 in order to verify my email address. I verified my email using this function: send_verification_email(request, form) if the user verifies its email then it fine. The problem arises when the email link gets expired and the user needs to verify email by resending the email. This package contain a function resend_verification_email(request, encoded_email, encoded_token) the description of the function says to pass encoded_email and encoded_token which was generated previously. I don't think whether our system has that encoded_token and encoded_email save in DB. Can anyone help me with how to solve this issue? -
Getting assertion error when trying to save a new field called location inside a post method
I want to save a field called location and pass it to data from the latitude and longitude like in this program. but getting an assertion error AssertionError at /api/customer When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation. You should either call `.is_valid()` first, or access `.initial_data` instead. class CustomerView(APIView): def get(self, request, format=None): query = CustomerProfile.objects.all() serializer = CustomerSerializer(query, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = CustomerSerializer(data=request.data) lat = serializer.data.get('latitude',None) lon=serializer.data.get('longitude',None) lat_1=float(lat) lon_1=float(lon) if serializer.is_valid(): s=serializer.save(commit=False) s.location=Point((lat_1,lon_1),srid=4326) s.save() return Response({"message":"Customer Profile Updated Successfully","data":serializer.data}, status=200) return Response({"message":"Customer registration failed!!","data":serializer.data}, status=400) -
Django templates if function
i want to check if there is and object in 2d list in djnago template i have object of person and list of emails where key is person and value is email address. I'd like to achieve something like this: {% for person in personList%} {% if person in emailList.person %} exist {% endif %} {% endfor %} -
Add PRIMARY KEY constraint to existing table
I backed up and recovered 2 weeks ago and all primary keys and foreign keys were disabled. How can I change it? I'm using Django btw. Unfortunately, I have no idea about DB. -
django simple metatages getting error when try to logout
info: i want to use django-simple-metatages . Everythis is working fine when i add something in database via metatage form. problem: when i try to logout from django admin dashboard i'm getting error because of i'm django simple metatage. if remove metatages from setting.py file then the logout is working fine if i add again metatages apps in setting.py list it's getting error. i don't know how can i solve this problem? I would be grateful for any help. -
AttributeError when returning Response with data that comes from a model property?
Full error I get is this one. Got AttributeError when attempting to get a value for field `name` on serializer `AccountSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Ledger` instance. Original exception text was: 'Ledger' object has no attribute 'name'. This is the property on the model I am trying to use @property def balance(self): return Ledger.objects.filter(account=self.pk).aggregate(models.Sum('amount'))['amount__sum'] or '0' This is my serializer class. class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = '__all__' And here is the view method. class Transactions(APIView): def get(self, request, pk): account = Account.objects.get(pk=pk) transactions = account.transfers serializer = AccountSerializer(transactions, many=True) return Response(serializer.data) Not really understanding why this returns an error but if I put the account variable in the AccountSerializer it works fine. -
Try to search the forecast of cities with space in the name. Openweathermap API Django Python
I'm try to resolve the problem of the cities that have space in the name. I look around a bit but i couldn't find anything that match my case. This is the code: def search(request): if request.method == 'POST': city = request.POST['city'] source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+ city +'&units=metric&appid=API_KEY').read() list_of_data = json.loads(source) # print(list_of_data) wind_speed = list_of_data['wind']['speed'] wind_gust = list_of_data['wind']['gust'] #function for convert the wind speed in knot def wind_converter(w,g): knots = 2 kt = (int(w)) + (int(g))* knots return kt wind_response = wind_converter(wind_speed,wind_gust) #function for convert deg in cardinal direction wind_direction = list_of_data['wind']['deg'] def degrees_to_cardinal(d): dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'] ix = round(d / (360. / len(dirs))) return dirs[ix % len(dirs)] wind_direction = degrees_to_cardinal(wind_direction) data = { "country_code": str(list_of_data['sys']['country']), "coordinate": str(list_of_data['coord']['lon']) + ', ' + str(list_of_data['coord']['lat']), "temp": str(list_of_data['main']['temp']) + ' °C', "pressure": str(list_of_data['main']['pressure']), "humidity": str(list_of_data['main']['humidity']), 'main': str(list_of_data['weather'][0]['main']), 'description': str(list_of_data['weather'][0]['description']), 'icon': list_of_data['weather'][0]['icon'], 'wind_speed':list_of_data['wind']['speed'], 'direction':list_of_data['wind']['deg'], 'wind_gust':list_of_data['wind']['gust'], 'wind_response':wind_response, 'wind_direction':wind_direction, } print(data) else: data = {} return render(request, "WindApp/wind_search.html", data) If anyone know how to resolve this problem will be great. I'd like also understand why the URL can't handle the space in the city name. Thank you very much. -
Django StreamingHttpResponse stops work when usind django channels
I stream images from cv2 using the following code: views.py def generate(): while True: (flag, encodedImage) = cv2.imencode(".jpg", s_manager.acquire_image()) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n\r\n') def main_stream(request): return StreamingHttpResponse(generate(), content_type="multipart/x-mixed-replace;boundary=frame", ) stream.html {% block stream %} <div class="stream-container"> <img src="{% url 'stream:stream' %}" id="img-stream" draggable='false' ondragstart="return false;"></img> </div> {% endblock %} once I added Django channels into my project the StreamingHttpResponse stoped working settings.py: ASGI_APPLICATION = 'photon.asgi.application' asgi.py application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)) }) I need a solution that will allow me to stream images from cv2 and in the same time use django channels or something Similar. Thanks you all! -
generate line automatically in urls (django)
I would like to know how to create a row in the urlpatterns array automatically from the forms file. example: in the forms file we have : phone = forms.ModelChoiceField(queryset=Phone.objects.all()) then we will create in urls this line : path('phone', views.phone, name='phone') -
NOT NULL constraint failed: product_product.seller_detail_id
I am getting this error when i am going to add the new product in the django website with the help of form The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "E:\#1 ecommerce pro\new projects\enw\shop\shop\vendor\views.py", line 48, in add_product product.save() File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\base.py", line 906, in _do_insert return manager._insert( File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\models\sql\compiler.py", line 1410, in execute_sql cursor.execute(sql, params) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "E:\#1 ecommerce pro\new projects\enw\shop\env_of_project\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File … -
ow to optimize properly queryset with multiple OR conditions?
Here I am trying to filer all the menus having at least one status True belonging to the current user. This below query works fine for now but query looks bit longer and has multiple OR conditions. I want to optimize my queryset. How can I do it here ? models class Menu(CommonInfo): name = models.CharField(max_length=200, unique=True) code = models.CharField(max_length=50, unique=True) class Right(CommonInfo): menu = models.OneToOneField(Menu, on_delete=models.CASCADE, related_name='right') user = models.ForeignKey(User, on_delete=models.PROTECT, null=True, related_name='user_rights') create = models.BooleanField(default=False) update = models.BooleanField(default=False) view = models.BooleanField(default=False) delete = models.BooleanField(default=False) approve = models.BooleanField(default=False) class Group(CommonInfo): name = models.CharField(max_length=200, unique=True) users = models.ManyToManyField(User, blank=True, related_name='user_roles') menus = models.ManyToManyField(Menu, blank=True, related_name='menu_roles') query def get_queryset(self): filtersets = Q(right__create=True) | Q(right__update=True) | Q(right__delete=True) | Q( right__view=True) | Q(right__archive=True) qs = Menu.objects.filter(right__user=self.request.user).filter(filtersets) return qs