Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best Way to set min/max values in Django Model field
I'm trying to get a field called WipID in my model to have the following: - Primary Key - and to have numbers between 000000001 and 999999999 Basically I want the field to always have 9 numbers. I don't care about auto-increment or not. I've tried a number variations, but right now I have this: WipID = models.BigAutoField(primary_key=True, validators=[MinValueValidator(000000001), MaxValueValidator(999999999)]) I've tried BigIntegerField and PositiveIntegerfield and those haven't worked either. What's the best way to accomplish this? Any help is greatly appreciated on this. -
django rest framework: how generate schema from serializer types?
I added the django-rest-swagger to my django-rest-framework project, following the instructions. The GUI looks fine, but the request description, which seems to be automatically generated from the APIViews get_serializer field has some issues. Specifically nested objects are ignored, and shows as {} all string types are just listed as string, ignoring the openapi format field So, for example, for this serializer class NestedSerializer(Serializer): firstname = StringField() class RequestSerializer(Serializer): name = NestedSerializer() date = DateField() choice = ChoiceField(['aa', 'bb', 'cc']) the GUI shows the request as name: {} date: string choice: string Am I missing something, or the project really doesn't support more specific types? -
Django project: within AJAX, parsererror SyntaxError: Unexpected end of JSON input
I am working on building a Django project. Once the button is clicked, the form will be submitted and some tasks will be performed based on the information from the form. However, in my case, the task can be done properly while there is always error pop up saying: "parsererror SyntaxError: Unexpected end of JSON input". Here is my AJAX function: $(document).on('submit', '#productForm', function(e){ e.preventDefault(); $.ajax({ method: 'POST', dataType: 'json', url: 'product/', data: { region: $("#Region-choice").val(), country: $("#Country-choice").val(), product: $("#Product-choice").val(), dvn: $("#dvn").val(), reship: $("#reshipCheckbox").val(), reshipId: $("#reshipTextfield").val(), validator: $("#Validator").val()} }) .done(function(){ alert("Product Created!"); }) .fail(function(req, textStatus, errorThrown) { alert("Something went wrong!:" + textStatus + ' ' + errorThrown ); }); alert("Submitted!"); }); -
Django 1.8 QuerySet: .extra syntax in Q object
I have several complex SQL Statements which are used to filter a django Queryset using .extra(). qs.extra(where=["my_jsonb_field-->'my_key'::text LIKE %s"], params=["myValue"]) Since these are queries on json fields, there is no possibility to get rid of these statements (at least not with django 1.8). Is it possible to use Q() objects with the .extra() syntax? # Q has no .extra Q().extra(...) # Q has no .raw Q().raw(...) -
AttributeError: 'function' object has no attribute 'get_extra_actions'
I defined this routing in my urls.py: from django.contrib import admin from django.urls import path from api import views from rest_framework import routers from django.conf.urls import url, include router = routers.SimpleRouter() router.register(r'country', views.get_country, base_name="Country") router.register(r'city', views.get_city, base_name="City") router.register(r'state', views.get_state, base_name="state") urlpatterns = [ path('admin/', admin.site.urls), url(r'^', include(router.urls)) ] But when I run it I get the following error: AttributeError: 'function' object has no attribute 'get_extra_actions' -
Category based list View in django
I have two model 1 is category, 2nd is details and I want make a view where i can click on a category and the link should take me to the list only for the current category what i clicked. my models are given: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class FoodCategory(models.Model): categoryname = models.CharField(max_length=100) categorydetails = models.CharField(max_length=1000) categoryimage = models.ImageField(default='cat_def.jpg', upload_to='catimg') class Meta: verbose_name = 'Food Category' def __str__(self): return self.categoryname class FoodDetails(models.Model): fromcategory = models.ForeignKey(FoodCategory, on_delete=models.CASCADE) foodname = models.CharField(max_length=100) fooddetails = models.CharField(max_length=1000) foodimage = models.ImageField(default='food_def.jpg', upload_to='fodimg') armodel = models.CharField(default='andy.sfb', max_length=50) additiondate = models.DateTimeField(default=timezone.now) addedby = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name = 'Food Detail' def __str__(self): return self.fromcategory.categoryname + \ ' - ' + self.foodname + \ ' - ' + 'added by' + \ ' - ' + self.addedby.username def get_absolute_url(self): return reverse('food-details', kwargs={'pk': self.pk}) -
Django with Peewee Connection Pooling MySQL disconnect
I'm running a Django project with Peewee in Python 3.6 and trying to track down what's wrong with the connection pooling. I keep getting the following error on the development server (for some reason I never experience this issue on my local machine): Lost connection to MySQL server during query The repro steps are reliable and are: Restart Apache on the instance. Go to my Django page and press a button which triggers a DB operation. Works fine. Wait exactly 10 minutes (I've tested enough to get the exact number). Press another button to trigger another DB operation. Get the lost connection error above. The code is structured such that I have all the DB operations inside an independent Python module which is imported into the Django module. In the main class constructor I'm setting up the DB as such: from playhouse.pool import PooledMySQLDatabase def __init__(self, host, database, user, password, stale_timeout=300): self.mysql_db = PooledMySQLDatabase(host=host, database=database, user=user, password=password) db_proxy.initialize(self.mysql_db) Every call which needs to make calls out to the DB are done like this: def get_user_by_id(self, user_id): db_proxy.connect(reuse_if_open=True) user = (User.get(User.user_id == user_id)) db_proxy.close() I looked at the wait_timeout value on the MySQL instance and its value is 3600 so that … -
I have two models and they are connected through ForiegnKey in my Django Project
#Models.py class Appname(models.Model): name=models.CharField(max_length=150,blank=False,null=False) def __str__(self): return self.name class placement(models.Model): user=models.ForeignKey(User,related_name='placeid', null=True, default=None,on_delete=models.CASCADE) name=models.ForeignKey(Appname,related_name='appname',null=True,default=None,on_delete=models.CASCADE,editable=False) ad_space=models.CharField(max_length=150,blank=False,null=False) PID_TYPE = ( ('FN','FORMAT_NATIVE'), ('FNB','FORMAT_NATIVE_BANNER'), ('FI','FORMAT_INTERSTITIAL'), ('FB','FORMAT_BANNER'), ('FMR','FORMAT_MEDIUM,RECT'), ('FRV','FORMAT_REWARDED_VIDEO'), ) format = models.CharField(max_length=3,choices = PID_TYPE,default = 'FN',blank=False, null=False) pid=models.CharField( max_length=50,default='',blank=False, null=False) cpm=models.IntegerField(default=0,blank=False, null=False) ADS_TYPE=( ('FB','FACEBOOK'), ('G','GOOGLE'), ) source=models.CharField(max_length=2,choices=ADS_TYPE,default='FB',blank=False, null=False) comments=models.TextField(default='',blank=False, null=False) objects=models.Manager() def __str__(self): return self.ad_space def get_absolute_url(self): return reverse("dashapp:view") Here is the Ques. I save my first model through form using generic view now i have used ForeignKey in my 2nd model . I want that when i fill my second Form the name variable gets autofill with the first model value . can i do that?? -
Django cms - Plugin in Plugin relation
i am using django cms 3.5.x. I try to create a new plugin that contains other plugins, but not over the "normal" way (allow_child=True). I would like to say PluginBox should contain two PluginText and a other plugin PluginContainer should contain 4 PluginText. I also want to render the first PluginText of box inside a div and the second one inside a span. For example: class Box(CMSPlugin): text1 = TextPlugin text2 = TextPlugin <div class="box"> <div> {% redner text1 } </div> <span> {% redner text2 } </span> </div> -
Google Calendar API using "events.update()" function doesn't send notification to the "attendees", after "import" of a calendar using iCalUID
FYI - old_event is a "service.events().get() response instance" captured from an event in a different mail address abc@gmail.com. new_event = old_event.copy() imported_event = new_service.events().import_(calendarId='primary',body=new_event).execute() updated_event_body = imported_event.copy() updated_event_body['summary'] = 'New Summary' updated_event = new_service.events().update(calendarId='primary', eventId=updated_event_body['id'], sendNotifications = True, body=updated_event_body).execute() -
Is it possible to disable the generation of related objects when deleting an object via Django admin?
I'm currently maintaining a legacy system while a new system is brought up. I noticed recently that I get a timeout when trying to delete certain objects from a specific model. I've tracked this down to being related to the following question which has an accepted answer: Django admin hangs (until timeout error) for a specific model when trying to edit/create The problem I'm having is that the objects that are related are not directly related from my model in question. For example I have the following models (generically named to remain vague due to IP at my company): ModelA which is the model I'm seeing the issue with when deleting from the Django Admin site ModelB which contains a ForeignKey field to ModelA ModelC which contains a ForeignKey field to ModelB ModelD which contains a ForeignKey field to ModelC ModelE which contains a ForeignKey field to ModelD Model details: ModelE can contain tens/hundreds/thousands of entries for any entry of ModelC. Additionally ModelC can contain tens/hundreds/thousands of entries for any entry of ModelB Currently when I try to delete ModelA Django attempts to generate all the associated objects all the way down to ModelE which is causing a timeout in … -
Wagtail: Filter Pages by a ForeignKey
Using Wagtail I want to get a QuerySet of Pages whose specific subclass have a certain ForeignKey to a Snippet. from django.db import models from wagtail.core.models import Page from wagtail.snippets.models import register_snippet @register_snippet class Organization(models.Model): name = models.CharField(max_length=255, blank=False) class ArticlePage(Page): organization = models.ForeignKey( 'Organization', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) So, how would I get a QuerySet of all Pages whose associated ArticlePage has an Organisation with an id of 1? -
CSRF Failure On AJAX POST Request After Deploy Django Application With Nginx
I use Nginx and Gunicorn to deploy my Django blog on VPS. When i push some data to Django backend via Jquery AJAX, then i got 403 CSRF error. I googled a lot but still can't figure out how to fix this problem. I tried to deploy them on my local computer with same configuration files, and everything is okay. I've copied the AJAX sample code from Django document: // get csrftoken via JavaScript function getCookie(name) { let cookieValue = null if (document.cookie && document.cookie !== '') { let cookies = document.cookie.split(';') for (let i = 0; i < cookies.length; i++) { let cookie = jQuery.trim(cookies[i]) // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)) break } } } return cookieValue } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)) } $.ajaxSetup({ beforeSend: (xhr, settings) => { let $captchaMassage = $('#captcha-message') let csrftoken = getCookie('csrftoken') console.debug('csrftoken: ' + csrftoken) if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken) } if ($captchaMassage) { $captchaMassage.text('please wait...') } } }) and this is my AJAX: $.ajax({ async: true, method: 'POST', url: '{% … -
How to add and update data into foreign key field in django model
I have two models which is related to a forignkey. class BikeModel(models.Model): City = models.ForeignKey(CityForBike, on_delete=models.CASCADE) BikeModels = models.CharField(default='', max_length=50) Image = models.ImageField(upload_to='bike_images', blank=True, null=True, default='https://www.urbandrive.co.in/Admin/API/UploadedFiles/CarImage/44b150b3-f61a-41b5-afd8-34ded18fa980.png') class Meta: verbose_name_plural = 'BikeModels' def __str__(self): return self.BikeModels class CityForBike(models.Model): CityForCars = models.CharField(default="",max_length=50) class Meta: verbose_name_plural = 'CityForBikes' def __str__(self): return self.CityForCars and i want to insert data to BikeModel. but it gives me error. AssertionError: You cannot call `.save()` on a serializer with invalid data. I want to know how to insert data to forign key field. if request.method == 'POST': import pdb; pdb.set_trace() input_data = json.loads(request.read().decode('utf-8')) print(input_data) serializer = serializers.BikeModelSerializer(data=input_data) if serializer.is_valid(): serializer.save() return render(request, "bike_model_add.html", {'car_city': car_city}, status=200) And this is the data i am sending. {'City': 'testo', 'BikeModels': 'ds'} -
Set conditions to a field in Django Model
This is my Models: class UserModel(models.Model): name = models.CharField(max_length=200) role = models.CharField(max_length=200) class TestModel(models.Model): field1 = models.TextField() field2 = models.TextField() owner = models.ForeinkeyField(UserModel, on_delete=models.CASCADE) Let the role field can have values role1, role2, and role3 and I want to restrict the TestModel having owner with role=role3 -
django admin access rights: edit_user vs. assign access rights
In Django Admin: If you add the access right to "edit users" to a user this user can: edit any user's profile edit all access rights of the user (thus making this user de-facto a superuser) Is there a way to limit a user to only update another users personal information: email, first_name, last_name, etc? -
vuejs - without any node mentioned
I am working on Django (Python based Web Framework) project with Vue.js as my front-end choice. Almost all articles about Vuejs mention Node - at least to start development server. I am looking for some good read which talks only about Vue.js and architecture part of the application. How to and where to create those store, components, routes files? What should be ideal location/directory structure to start Vuejs - without bothering about Node part of it. thank you -
Django app not loading CSS background-image, but image loads with inline styling. Is there a fix for this?
As the title states. I've run into an interesting problem. This is related to css background images. I am loading the app names and their models in a sidebar menu, and for some reason the images just won't load. I added the images in the static folder for the app. The code in the css file is the following: /* App Buttons and Icons */ #servers_icon { background-image: url("/static/bootstrap_admin/img/icon_servers_copy.png") no-repeat; } #sensors_icon { background-image: url("/static/bootstrap_admin/img/icon_sensors_copy.png") no-repeat; } Note the path. For some reason, django is refusing the load these files. The css file is being loaded and actively used by the app. The ID names are correct. However, the images just will not load. However, if I put them inline in the HTML file: <li style="background-image: url('/static/bootstrap_admin/img/icon_{{ app.app_label }}_copy.png'); background-repeat: no-repeat;" {% if app.app_url == current_url %}class="active"{% endif %}> <a href="{{ app.app_url }}" class="section" title="Models in the {{ name }} application"> {{ app.name }} </a> </li> Then the images load. Note that the path is the same. {{app.app_label}} is part of the in-template for loop that populates the menu. The label name and file name matches. In fact, the file name was renamed to match the app label name. Anyway, … -
django selection field value
i have created a selection field in django model , but when i try to call onchange in html the ajax code is not working. here is the code.. when i click on the match_recipient in this form i need value on the ajax but now i didnt get the value . There is showing undefined value models.py type = ( ('catchall' , 'Catch All'), ('match_recipient','Match Recipient'), ('match_header','Match Header'), ) class Routes(models.Model): expression_type = models.CharField(max_length=10,choices=type,default='catchall') actions = models.CharField(max_length=100) recipient = models.CharField(max_length=50) header_name = models.CharField(max_length=50) header_value = models.CharField(max_length=50) priority = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) form.py type = ( ('catchall' , 'Catch All'), ('match_recipient','Match Recipient'), ('match_header','Match Header'), ) class RouteForm(forms.ModelForm): expression_type = forms.ChoiceField(choices=type,widget=forms.Select(), required=True) actions = forms.CharField(help_text='Required', widget=forms.TextInput(attrs={'placeholder': 'address@example.com'})) recipient = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'recipient@example.com'})) header_name = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'X-Header-Name'})) header_value = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Header Value'})) priority = forms.IntegerField(initial=0) class Meta: model = Routes fields = ('expression_type','actions','recipient','header_name','header_value','priority',) template.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#recipient").hide(); $("#header_name").hide(); $("#header_value").hide(); $("#expression_type").change(function() { alert("ededde"); var a = $(this.text()); console.log(a); alert(a); if($(this).val() == "match_recipient"){ $("#recipient").show(); }else if($(this).val() == "match_header"){ $("#header_name").show(); $("#header_value").show(); } }); }); </script> </head> <form action="{% url 'route' %}" method="POST"> {% csrf_token %} <div class="field has-addons"> <div class="form-group row" id="expression_type"> <label class="col-sm-2 col-form-label">Expression Type</label> <div class="col-sm-10"> … -
STATIC_ROOT in Django not working correctly
Trying to get static root set properly, Went through the tango with Django tutorial and stuck on this part. Basically this is my setting files, and the static folder is linked below in the tree. C:. ├───media │ └───locations │ └───2018 │ └───11 │ └───11 │ └───20 │ └───18 ├───Space │ └───__pycache__ ├───Spaces │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───static │ ├───admin │ │ ├───css │ │ │ └───vendor │ │ │ └───select2 │ │ ├───fonts │ │ ├───img │ │ │ └───gis │ │ └───js │ │ ├───admin │ │ └───vendor │ │ ├───jquery │ │ ├───select2 │ │ │ └───i18n │ │ └───xregexp │ ├───css │ └───images │ └───parralax │ └───home ├───templates │ ├───registration │ └───Spaces └───users ├───migrations │ └───__pycache__ └───__pycache__ and below you can see the settings i'm using for this . """ Django settings for Space project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') # Quick-start development settings - … -
Multiple Queries For Inline instances Django admin
I have created a custom Admin for one of my model. And added a Relational table as one of its inline. 1). Now the thing is that Inline has over a 100 rows. And the inline further has a foreign key object to some other model. 2).Whenever i load the model form it takes a whole lot of time to Load. 3).I debugged and checked the code and number of queries. No query was duplicated and the count was nominal. 4).I have overridden the query set for the inline instance to prefetch its foreign key instance. 5).I went on and raised a random validation error in the formset's clean. 6).What i found out that when the error was raised it had a different query for every inline instance. Say if it has a 100 rows then the query was duplicated 100 times for that inline. 7).Is there any way to prefetch or optimize this scenario as its causing way too lag in my application Please help -
How to create an inline formset with manytomany relation in Django
I want to create an inline formset between Preorder model and Product model. The scenario is that the user will be able to select one or more than one products when he decides to create a preorder. On the other hand a product might be found in one or more than one preorders. With that in mind i created a manytomany relationship. models.py class Preorder(models.Model): client = models.ForeignKey(Client,verbose_name=u'Client') invoice_date = models.DateField("Invoice date",null=True, blank=True, default=datetime.date.today) preorder_has_products = models.ManyToManyField(Product, blank=True) def get_absolute_url(self): return reverse('preorder_edit', kwargs={'pk': self.pk}) class Product(models.Model): name = models.CharField("Name",max_length=200) price = models.DecimalField("Price", max_digits=7, decimal_places=2, default=0) barcode = models.CharField(max_length=16, blank=True, default="") eopyy = models.CharField("Code eoppy",max_length=10, blank=True, default="") fpa = models.ForeignKey(FPA, null=True, blank=True, verbose_name=u'Fpa Scale') forms.py class PreorderForm(ModelForm): class Meta: model = Preorder exclude = ('client','preorder_has_products',) def __init__(self, *args, **kwargs): super(PreorderForm, self).__init__(*args,**kwargs) self.fields['invoice_date'].widget = MyDateInput(attrs={'class':'date'}) class ProductForm(ModelForm): #name = ModelChoiceField(required=True,queryset=Product.objects.all(),widget=autocomplete.ModelSelect2(url='name-autocomplete')) class Meta: model=Product fields = '__all__' def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['name'].label="Name" self.fields['price'].label="Price" and finally the inline formset: PreorderProductFormSet = inlineformset_factory(Preorder, Product, form=ProductForm, extra=1) After run I face up the issue:ValueError at / 'intranet.Product' has no ForeignKey to 'intranet.Preorder' Why this happening since I created a manytomany relation? One solution is to create a foreign key relationship between Preorder and … -
how to make a list of posts titles in django
I am creating a blog web app with django where i want to make a list which contains only titles of the posts. i wanna make two lists namely Latest posts All posts In Latest posts , i wanna list out titles of the posts created recently.Means post created at last should be in first place of the list. simple In All Posts , i want to list out titles of all posts in ascending order. Here is my code goes..... views.py from django.shortcuts import render , redirect from django.views.generic import TemplateView , ListView , DetailView from .models import home_blog_model from .forms import create_post class home_view(ListView): model = home_blog_model template_name = "home.html" context_object_name = "posts" def detail_view(request , pk): obj = home_blog_model.objects.get(id=pk) context = {"obj":obj} return render(request , "detail.html" , context) def create_post_view(request): if request.method == "POST": form = create_post(request.POST) if form.is_valid(): form.save() return redirect("/home/") else: form = create_post() return render(request , "create_post.html" , {"form":form}) home.html {% extends "base.html" %} {% load static %} {% block body %} <img src="{% static 'hori.jpg' %}" style="margin-top: 50px;margin-left: 250px;width: 60%"> <div class="row" style="margin-top: 40px;margin-left: 320px;margin-right: 20px"> {% for post in posts %} <div class="col-sm-6 mb-4"> <div class="container" style="width: 300px;box-shadow: 0 4px 8px 0 … -
Elasticsearch in Django - sort alphabetically
I have a following doc: @brand.doc_type class BrandDocument(DocType): class Meta: model = Brand id = IntegerField() name = StringField( fields={ 'raw': { 'type': 'keyword', 'fielddata': True, } }, ) lookup_name = StringField( fields={ 'raw': { 'type': 'string', } }, ) and I try to make a lookup using this: BrandDocument.search().sort({ 'name.keyword': order, }) The problem is that I'm getting results sorted in a case sensitive way, which means that instead of 'a', 'A', 'ab', 'AB' I get 'A', 'AB', 'a', 'ab'. How can this be fixed? -
React + Django form input with images and text
I want to have a 'post' model in Django that contains both images and text in the body of the post, but I am not sure how I should go about it. On the frontend React side, I'd like to have a content input form (along with title, etc.) that would allow users to type the text they want, and then insert photos to upload at any spot they choose in the text. On the backend Django side, I'd like the images to go to s3, but that seems like an issue I can work out once the actual uploading POSTing to the db is functional. Can I use a JSON field for the content from from django.contrib.postgres.fields import JSONField Would the json field be able to handle text interrupted by image urls? What would my frontend axios post request look like? The only other option I saw was wagtail with their StreamField, but if possible I'd like to avoid using a content management system. I'm open to any ideas at this point!