Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Dockerfile Customization for Google Cloud Run with Nginx and uWSGI
I'm trying to migrate a Django application from Google Kubernetes Engine to Google Cloud Run, which is fully managed. Basically, with Cloud Run, you containerize your application into a single Dockerfile and Google does the rest. I have a Dockerfile which at one point does call a bash script via ENTRYPOINT But I need to start Nginx and start Gunicorn. The Google Cloud Run documentation suggest starting Gunicorn like this: CMD gunicorn -b :$PORT foo.wsgi (let's sat my Django app is named "foo") But I also need to start Nginx via: CMD ["nginx", "-g", "daemon off;"] And since only one CMD is allowed per Dockerfile, I'm not sure how to combine them. To try to get around some of these difficulties, I was looking into using a Dockerfile to build from that already has both working and I came across this one: https://github.com/tiangolo/meinheld-gunicorn-docker But the paths don't quite match mine. Quoting from the documentation of that repo: You don't need to clone the GitHub repo. You can use this image as a base image for other images, using this in your Dockerfile: FROM tiangolo/meinheld-gunicorn:python3.7 COPY ./app /app It will expect a file at /app/app/main.py. And will expect it to contain … -
How to check existence of a record in a model from current authenticated user in Django template?
Code below checks whether a user added a product in cart or not. If it is added to cart by this current user it should show remove from cart button else it should show a simple form to add product in cart. {% for ordereditem in item.ordereditems_set.all %} {% if ordereditem.quantity > 0 and ordereditem.user.username == user.username %} <a href="{{ item.get_remove_from_cart_url }}">Remove from cart</a> {% elif not ordereditem %} # here! <!-- else if there is no record of 'ordereditem' from current user show this form to add it to cart--> <form class="d-flex justify-content-left" method="POST" action="{{ item.get_add_to_cart_url }}"> {% csrf_token %} <input type="number" name="number" value="1"> <input type="submit" value="Add to cart"> </form> {% endif %} {% endfor %} the problem lies here {% elif not ordereditem %} it seems like my current if statement doesn't meet the condition I expect. I tried using {% else %} but it still shows the form even after adding product to cart. This is how models look like: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='Discount', null=True, blank=True) image = models.ImageField(upload_to='products/%Y/%m/%d/') image_cover = models.ImageField(upload_to='products/%Y/%m/%d/') description = models.TextField() slug = models.SlugField(max_length=150, blank=True, null=True) category = models.CharField(max_length=15, choices=CATEGORY_CHOICE) label = models.CharField(max_length=10, choices=LABEL_CHOICE) … -
Django management commands when using AWS Fargate
I have deployed a Django application using the AWS Fargate service. It is so far working good, but I am wondering if there is any quick / easy way to interact with the Django management commands? What would be the best way to achieve this? Thanks -
How to get a single model object with a relation to the template in Django
I am working on this project that I can add two or more forms in a template. I am able to get the two forms in the template but when I submit the form, I get the objects for the rentalproperty model and not the contract model. I have created two different solution but the two doesn't solve the problem. The first solution below display both objects multiple times in the detailview but what I want is to display the two model objects just once. The second solution display the rentalproperty object once but the contract objects multiple times. Could someone point me in the right direction? Thanks. First solution: views.py class DetailView(generic.DetailView): model = RentalProperty template_name = 'rental/detail.html' context_object_name = 'property' def new_rental(request, pk): if request.method == 'POST': rental_form = NewRentalPropertyForm(request.POST, request.FILES, prefix = "rentals") contract_form = NewContractForm(request.POST, prefix = "contracts") if rental_form.is_valid() and contract_form.is_valid(): print ("all validation passed") rentalproperty = rental_form.save() contract_form.cleaned_data["rentalproperty"] = rentalproperty print(contract_form) contract = contract_form.save(commit=False) contract.rentalproperty = rentalproperty contract = contract_form.save() return HttpResponseRedirect(reverse("home")) else: messages.error(request, "Error") contract = Contract.objects.get(pk=pk) else: rental_form = NewRentalPropertyForm(prefix = "rentals") contract_form = NewContractForm(prefix = "contracts") contract = Contract.objects.get(pk=pk) return render(request, 'rental/new_rental.html', { #'rentalproperty': rentalproperty, 'rental_form': rental_form, 'contract_form': contract_form, 'contract': contract, … -
Get Django ALLOWED_HOSTS env. variable formated right in settings.py
I'm facing the following issue. My .env files contains a line like: export SERVERNAMES="localhost domain1 domain2 domain3" <- exactly this kind of format But the variable called "SERVERNAMES" is used multiple times at multiple locations of my deployment so i can't declare this as compatible list of strings that settings.py can use imidiatly. beside I don't like to set multiple variables of .env for basically the same thing. So my question is how can I format my ALLOWED_HOSTS to be compatible with my settings.py. Something like this does not seem to work it seems: ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(',') Thanks and kind regards -
How to save three related models in one DRF endpoint?
I have 4 related models and I need to implement the functionality to consistently create instances of these models in a database in one post query. For this I use override of the APIView class post method. models class VendorContacts(models.Model): contact_id = models.AutoField(primary_key=True) vendor = models.ForeignKey('Vendors', on_delete=models.CASCADE) contact_name = models.CharField(max_length=45, blank=True) phone = models.CharField(max_length=45, blank=True) email = models.CharField(max_length=80, blank=True, unique=True) class Meta: db_table = 'vendor_contacts' class VendorModuleNames(models.Model): vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE, primary_key=True) module = models.ForeignKey(Modules, models.DO_NOTHING) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'vendor_module_names' unique_together = (('vendor', 'module'),) class Vendors(models.Model): COUNTRY_CHOICES = tuple(COUNTRIES) vendorid = models.AutoField(primary_key=True) vendor_name = models.CharField(max_length=45, unique=True) country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) nda = models.DateField(blank=True, null=True) user_id = models.ForeignKey('c_users.CustomUser', on_delete=models.PROTECT) timestamp = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'vendors' unique_together = (('vendorid', 'timestamp'),) class Modules(models.Model): MODULES_NAME =tuple(MODULES) mid = models.AutoField(primary_key=True) module_name = models.CharField(max_length=50, choices=MODULES_NAME) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'modules' unique_together = (('mid', 'timestamp'),) serializer.py class VendorsSerializer(serializers.ModelSerializer): class Meta: model = Vendors fields = ('vendor_name', 'country', 'nda',) class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( 'contact_name', 'phone', 'email',) class VendorModulSerializer(serializers.ModelSerializer): class Meta: model = VendorModuleNames fields = ('module',) class ModulesSerializer(serializers.ModelSerializer): class Meta: model = Modules fields = ('module_name', ) views.py class VendorsCreateView(APIView): …