Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django build in error runtime translation
i want to translate Django buildin errors in different languages on runtime. Is it possible to translate django error for requested user according to his region. -
How to request param inside ModelSerializer
I need to return some computed value using request param. It seems that I need to get access to request param from inside ModelSerializer. How can I do this? class PostSerializer(serializers.ModelSerializer): owner = UserSerializer() spot = SpotSerializer() is_login_user_favorite = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' read_only_fields = ('owner',) def get_is_login_user_favorite(self, validated_date): return True # I need change this dynamically class PostListAPIView(generics.ListAPIView): serializer_class = serializers.PostSerializer queryset = Post.objects.all().order_by('-pk') permission_classes = [IsAuthenticated] -
Geo Django GDAL: Unable to open EPSG support file gcs.csv
I recently did a clean window installed. I installed OSGeo4W via: https://trac.osgeo.org/osgeo4w/ I installed GDAL by downloading the pip wheel GDAL-2.3.2-cp36-cp36m-win_amd64.whl I also configured my django settings.py to: if os.name == 'nt': import platform import sys OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] GDAL_LIBRARY_PATH = sys.path[6] + r'\osgeo\gdal203.dll' This configuration worked on my previous machine but when trying to edit a django model with a Point field I would get this error: GDAL_ERROR 4: b'Unable to open EPSG support file gcs.csv. Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.' Error transforming geometry from srid '4326' to srid '3857' (OGR failure.) GDAL_ERROR 4: b'Unable to open EPSG support file gcs.csv. Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.' Internal Server Error: /admin/event/event/31/change/ I followed the same configuration as my previous setup. Same machine but new OS so I'm a bit stomped. How can I configure the GDAL_DATA env variable? I tried the suggestion: https://stackoverflow.com/a/52597276/9469766 setting … -
Which one is better for online market Djnago or Flask?
I and my partner are working on an online market, we want the website to take the customer's information, his order details and send it to us and the supplier company. Basically, we will be the connect between them and the supplier. Which is better for this type of things flask or django? In addition, we may include some AI to help us see what the customer want. -
null entries in databse and when i click them i get TypeError at /admin/users/personal_detail/90/change/ __str__ returned non-string (type NoneType)
this is how my base.html looks like,everything was working fine until i did some changes adding jquery {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type ="text/css" href="{% static 'pmmvyapp/main.css' %}"> <link href="{% static 'js/jquery.js' %}" rel="stylesheet"> {% if title %} <title> PMMVY-{{ title }}</title> {% else %} <title>PMMVY</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4"><img src="{% static 'images/left-logo.png' %}" width="83" height="89" class='d-inline-block' alt=""/> <span style="color:white"> Ministry of Women &amp; Child Development | GoI</span> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> {% if user.is_authenticated %} <a class="btn btn-primary mr-4" href="{% url 'aganwadi' %}">Aganwadi</a> <a class="btn btn-primary mr-4" href="{% url 'applyonline' %}">Apply online</a> {% else %} <div class="navbar-nav mr-auto"> <a class="navbar-brand mr-4"><img src="{% static 'images/emblem-dark.png' %}" width="60" height="80" class='d-inline-block' alt=""/> <span style="color:white" >Pradhan Mantri Matru Vandana Yojana</span> </a> </div> {% endif %} <!-- Navbar Right Side --> <div class="navbar-nav"> {% if user.is_authenticated %} <div class="navbar-nav mr-auto"> <a class="btn btn-primary mr-4" href="{% url 'admin:index' %}"> Admin site … -
Creating user on the basis of schema name
I'm building webapp using django and there are multiple users and each user have their own schema, Each schema contains its auth models. Now I want to create new superuser on the basis of schema name , My main requirements is to create new super user user when ever new tenants is created. Is there any django orm or create new user. Any suggestion would be appreciated. for more info please follow Auto Create new User for new teanants in django I'm looking features somethings like https://github.com/Corvia/django-tenant-users/tree/master/tenant_users/permissions -
How to use custom functions as Django autocomplete_fields
This is my site/app/models.py class Country(models.Model): class Countries(models.IntegerChoices): US = 1, 'United States' IND = 2, 'India' UK = 4, 'United Kingdom' country_name = models.IntegerField(choices=Countries.choices) class Person(models.Model): name = models.CharField(max_length=100) nationalities = models.ManyToManyField(Country) This is my site/app/admin.py from django.contrib import admin from app.models import Country, Person class CountryAdmin(admin.ModelAdmin): search_fields = ['country_name'] class PersonAdmin(admin.ModelAdmin): autocomplete_fields = ['nationalities'] admin.site.register(Country, CountryAdmin) admin.site.register(Person, PersonAdmin) Note: This is minimum sample example which should work. For me similar is working just fine. Question The problem with above approach is that in searchable fields, 'country_name' only searches for integers (off course). The question is, can I use something like get_country_name_type_display to make it more useful? -
Take multiple urls in python using request.GET
I am trying to take multiple URL's separated by comma and put them in list in python. I tried: url = request.GET.get('url').split(',') #accept url seperated by comma data= [] data.append(requests.get(url).content) The above code did not work for obvious reasons. How can I accept multiple url separated by comma using request.GET -
3 Datefield models, 3rd model not accepting input
I have 3 fields with models.DateField, the 2 datefields(start_date & end_date) are saving the date input from the user, but the 3rd (n_date) is not saving the date input by the user, instead saving the current date. Can anyone explain? Models from django.db import models from django.contrib.auth.models import User from datetime import datetime class Client(models.Model): client_name = models.CharField(max_length=300) address = models.CharField(max_length=300) start_date = models.DateField(default=datetime.now, blank=True) end_date = models.DateField(default=datetime.now, blank=True) created = models.DateTimeField(auto_now_add=True) n_date = models.DateField(default=datetime.now, blank=True) ACTIVE = 'ACTIVE' TO_END = 'TO EXPIRE' ENDED = 'CONTRACT ENDED' STATUS_CHOICES = [ (ACTIVE, 'Active'), (TO_END, 'To Expire'), (ENDED, 'Contract Ended'), ] status = models.CharField(max_length=15, choices=STATUS_CHOICES, default=ACTIVE) user = models.ForeignKey(User, on_delete=models.CASCADE) Views ef createclient(request): if request.method == 'GET': return render(request, 'client/createclient.html', {'form': ClientForm()}) else: try: form = ClientForm(request.POST) newclient = form.save(commit=False) newclient.user = request.user newclient.save() return redirect('client') except ValueError: return render(request, 'client/createclient.html', {'form': ClientForm(), 'error': 'Bad data pass in. Try again'}) HTML. <div class="form-group form-check"> <label for="start_date">Contract Start:</label> <input type="date" id="start_date" name="start_date"> </div> <div class="form-group form-check"> <label for="end_date">Contract End:</label> <input type="date" id="end_date" name="end_date"> </div> <div class="form-group form-check"> <label for="n_date">Notification Date:</label> <input type="date" id="n_date" name="n_date"> -
Hosting provider platform design model architecture
I am building an app using Django. The app main focus is to provide hostings. The current architecture which i am following get me stuck with a lot of things. This is the Architecture which I am following Now for develoopment :- User --- Username , Fname, Lname, email profile - foreignkey with user, location, currency, all details. Packages --- ---Stater --- Economy ---Premium Subscriptions---- ---foreignkey to Package ---months ---Price ---description SSL ---name ---Description, slug Like wise Security and Backup OrderSubscription --- ---user ---subscription ----months ---Price OrderSSL --- ---user ---SSL ---months ---Price like wise security and back up. Order ----- ---user ---subscription ---ssl ---security ---Price ---backup ---ordered (Boolean) ---Order Date I am thinking this is not a good Architecture because building with this I am facing a lot of complications. -
Django redirect not working when specifying HTTP or HTTPS
I am not sure why this is happening, but when I specify HTTP or HTTPS as my full URL in a redirect, the part after my domain name is appended to my current domain. For example: if I redirect to https://www.external_site.com/error/page/hi_there.html it will go to https://www.currentdomain.com/error/hi_there/html return redirect('https://www.external_site.com/error/page/hi_there.html') But, when I remove the https: part (but leave the //), the redirect works as expected: return redirect('//www.external_site.com/error/page/hi_there.html') I am using Django v 1.11.23 but also tested it on Django 2. Django runs on Apache on mod_wsgi, and goes through an IIS reverse proxy (the reverse proxy is just a reverse proxy in this instance, no special rules or anything besides to rewrite the external domain to the internal domain.) -
Why when i overriding base.html django-admin has been disable responsive interface?
It seems like all ok for desktop interface but doesn't work correctly for mobile devices. This trouble is appear only when i put my custom base.html. -
Default selected options in SelectMultiple widget
I am passing several forms.SelectMultiple widgets to a view as a shortcut to render them. Is there any way to pass which options need to be checked by default? The source code doesn't seem to allow that: class SelectMultiple(Select): allow_multiple_selected = True def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, name=name) output = [format_html('<select multiple="multiple"{}>', flatatt(final_attrs))] options = self.render_options(choices, value) if options: output.append(options) output.append('</select>') return mark_safe('\n'.join(output)) def value_from_datadict(self, data, files, name): if isinstance(data, (MultiValueDict, MergeDict)): return data.getlist(name) return data.get(name, None) Again, let me repeat I am only using the widget. It is not bound to any form field, so I can't use initial. -
Django Queryset - Can I query at specific positions in a string for a field?
I have a table field with entries such as e.g. 02-65-04-12-88-55. Each position (separated by -) represents something. Users would like to search by the entry's specific position. I am trying to create a queryset to do this but cannot figure it out. I could handle startswith, endswith but the rest - I have no idea. Other thoughs would be to split the string at '-' and then query at each specific part of the field (if this is possible). How can a user search the field's entry at say positions 0-1, 6-7, 10-11 and have the rest wildcarded and returned? Is this possible? I may be approaching this wrong? Thoughts? -
How to use multiple Pagination class in one view in DRF
I want to create a web server that it used by mobile clients and web clients. Web client developer wants limit offset pagination but mobile client developer want page number pagination. In django rest framework seems we can not assign multiple pagination class to one view. so is there any solution in this situation? -
how to override All Auth built-in templates Django
I am using Django all auth to implement password reset functionality but I want to customize the template of password reset,here's below my urls: urls.py from django.conf.urls import url,include from django.urls import path from rest_framework_jwt.views import obtain_jwt_token,refresh_jwt_token from . import views # Registration,Login,Forgot,Profile change urlpatterns=[ url(r'^accounts/', include('allauth.urls')), ] and when I hit this url->http://127.0.0.1:8000/ThiefApp/accounts/password/reset/ I got below template How can I customize the above template or how can I use different template.Any suggestions? -
How can i secure communications from Django to a Flask microservice?
I designed a simple Django service which communicates with a Flask microservice using POST Requests. Basically, the user submits a form with some preferences, those preferences are sent to a Django view, the Django view will send those to Flask, which will perform some operations according to those preferences and then return a response to Django, which will show it to the user or do some other operations. This whole system works for now, the only problem is that i don't know how safe it is. Here is how i'm sending the request: def myview(request): # Some code ... req = requests.post('http://127.0.0.1:5000', json=myDataDict) And here is how my Flask service receives it: @app.route("/", methods=["GET", "POST"]) def receivePost(): data = request.get_json() # some code .. return jsonify(data) Again, this system works locally; i want to make it safer for when i'll deploy it. Here are my concerns: 1) What if a third party reads what's inside the variable myDataDict when the two services are communicating? 2) The Flask service should accept requests ONLY from the Django service. I made some research and found about libraries such as OAuth2, and a token authentication system would be a good way to make this … -
Multiple foreign key to one field
I have two classes; Devices and Connections. I am trying to create a connection between them. Device Class; class Devices(models.Model): device_no = models.IntegerField(primary_key=True) device_name= models.CharField(max_length=512) Connections Class; class Connections(models.Model): connection_id = models.IntegerField(primary_key=True) device_name1 = models.CharField(max_length=512) device_name2 = models.CharField(max_length=512) device_no1= models.ForeignKey(Devices, on_delete=models.CASCADE, db_column="device_no1", related_name="dev1_no") device_no2= models.ForeignKey(Devices, on_delete=models.CASCADE, db_column="device_no2", related_name="dev2_no") I've changed variable names due to security concerns What I am aiming is build a connection between device one to device two. These boths have same specifications. When I use it like this it doesn't return any errors. But when I try to make a query i.e: Connections.objects.filter(device1_no=dev_no) It doesn't return any member of Device class. It only returns Connections class members. I've also tried; Connections.objects.filter(device_no1__device_no=12) Any advice? -
Django - form not validating
I'm new to Django. I'm working on a project of building an online purchasing system. This form for some reason can not be validated. Attached the code below. Please let me know if you need more information: url.py app_name = 'vip' urlpatterns = [ path('create-order/', views.create_vip_order, name='create-vip-order'), path('order/<int:pk>/', views.VipOrderDetailView.as_view(), name='vip-order'), ] models.py class VipOrder(models.Model): ref_number = models.CharField(max_length=15, blank=True, unique=True, verbose_name=_("VIP Order Number")) active = models.BooleanField(default=False, verbose_name=_("VIP Order Active?")) date_created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, verbose_name=_('Your name')) email = models.EmailField(max_length=100, verbose_name=_('Your email')) phone = models.IntegerField(verbose_name=_('Your cell phone number')) address = models.CharField(max_length=30, verbose_name=_('What is your address?')) item_description = models.TextField(verbose_name=_("Describe the item briefly")) item_image1 = models.ImageField(upload_to='vip_order', verbose_name=_("Upload a photo of the item")) item_image2 = models.ImageField(upload_to='vip_order', blank=True, null=True, verbose_name=_("Upload another photo of the item (optional)")) item_image3 = models.ImageField(upload_to='vip_order', blank=True, null=True, verbose_name=_("Upload another photo of the item (optional)")) class Meta(): verbose_name = _('VIP Order') verbose_name_plural = _('VIP Orders') ordering = ['-date_created'] def __str__(self): return "VIP Order No. {}".format(self.ref_number) form.py class VipOrderForm(forms.ModelForm): class Meta: model = VipOrder fields = ['name', 'email', 'phone', 'address', 'item_description', 'item_image1', 'item_image2', 'item_image3'] views.py def create_vip_order(request, **kwargs): if request.method == 'POST': form = VipOrderForm(data=request.POST) print('form filled with POST data') # executed on POST request print(form.is_valid()) # always False here for some reason?? … -
How do I delete/replace a file from an image field
how do I delete/replace an old file when a new file is uploaded. For example, if a user upload profile picture(img1), then if the same user upload a new profile picture(img2), (img1) will be deleted/replace with (img2). But when I try uploading a new picture it duplicate to a new row in database and the picture display multiple times on template. class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) profile_pic = models.ImageField(upload_to='ProfilePicture/', blank=True) def home(request): profile_img = Profile.objects.filter(user=request.user.id) {% for pic in profile_img %} {% if pic.profile_pic %} <img src="{{ pic.profile_pic.url }}"> {% endif %} {% endfor %} -
Django with C++
I have a web application in Django. I need to access the video through a webcamera. The video access through webcamera has been written in C++ language. I need to send the values "Camera ON", "Camera off" to C++ code through django. If I press the "Camera ON" button in html,it should pass values to C++ and enable the camera. If I press "Camera off" button in html it should pass values to C++ and disable the camera. Can anyone suggest how can I do the process? -
Why lose mysql connection after several hours when i configured Django and Nginx in server?
after i configured my Django in Nginx of linux server , i can normally browse my web and connect mysql , but after a while(maybe several hours) ,disaster comes, web shows such infos: 2055: Lost connection to MySQL server at 'localhost:3306', system error: 32 Broken pipe ` Here is complete errors: Request Method: GET Request URL: http://labtine.com/logs/2.html Django Version: 2.0 Exception Type: OperationalError Exception Value: 2055: Lost connection to MySQL server at 'localhost:3306', system error: 32 Broken pipe Exception Location: /usr/local/lib/python3.7/dist-packages/mysql/connector/network.py in send_plain, line 143 Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.6 Python Path: ['.', '', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages', '/home/cg_log/CG_log/firstApp'] Here is the explicit error: ...... usr/local/lib/python3.7/dist-packages/mysql/connector/network.py in send_plain self.sock.sendall(packet) ...... i really don't know why , this problem has puzzled me for a long time , hugely hammered my road to devote to human being . from now on , i have searched for quite a lot in google , but nothing ends well,is it the cause of concurrency of Mysql?or any other issues?i have looked at my error logs but there was nothing indicate such error... -
How make snippets like Google Analytics/Facebook Pixel/Anothers scripts?
I dont know how ask this question. What i want is learn how make snippets scripts to send to my customers. Example: On my site, the customers personalize a widget to use in own website (Widget Purchase Counter). Now, I want this customer copy script on my site and paste the script on you website, like Google Analytics/Facbook pixel do. I Want some like this: <script src="www.mywebsite.com/script.js?UNIQUE_ID_CUSTOMER_EXAMPLE"></script> Google Example: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXX-Y', 'auto'); ga('send', 'pageview'); </script> Im coding in Django my website. -
Django function view to class view
I have a problem transforming the following function-based view to class-based view. I am using AJAX to send data to Django. def create_user(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] User.objects.create( name = name, email = email, password = password ) return HttpResponse("") -
Run reverse Django migration on Heroku after release failure
I have a running Django application on Heroku with migrations auto-run on release. While in most times this works fine sometimes there is a problem when: There are more than one migration in given release (they can be in different apps) Some migration will fail, but not the first one In this case manage.py migrate will fail so Heroku will not finish the release and will not deploy the new code. This means that code is in the old version and the database is in the state "somewhere between old and new". Is there a simple way to autorun Django run reversed migrations in case of the failure of the release command on Heroku? Transactions won't help here as there might be more than one migration (multiple apps) and Django run each migration in seperate transaction.