Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django problem with shared memcache nodes
i have two django instances running on two servers and i am using memcached to cache some data in my applicationa. each server have it's own memcached installed, i want to both of my applications have access to both caches but i cant't. when i set a values from one application in cache other application cant access it my memcached instances are running as root, also i have tried memcache and other users but it didn't fix the problem. for testing i used django shell, import cache class: from django.core.cache import cache set a value in cache : cache.set('foo', 'bar', 3000) and tried to get value from my other dajngo instance : cache.get('foo') but it returns nothing! here is my settings.py file : CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': [ 'first app server ip:port', 'second app server ip:port'] } } and my memcached.conf(comments deletede): -d logfile /var/log/memcache/memcached.log # -v -vv -m 512 -p 11211 -u root -l 192.168.174.160 # -c 1024 # -k # -M # -r -P /var/run/memcached/memcached.pid -
Django MultiValueKeyDictError in forms.py while filtering queryset
I am trying to filter a queryset in forms.py such that a specific author (1:1 relationship with the built in django User) can only view characters 'owned' by them. When I try to filter by anything other than the author, everything works fine. When I filter by author, the form initially loads correctly but upon POST I get a MultiValueKeyDictError. Here's the error text: MultiValueDictKeyError at /rmi/1/post/new 'cur_author' Request Method: POST Request URL: http://127.0.0.1:8000/rmi/1/post/new Django Version: 3.0.dev20190323160439 Exception Type: MultiValueDictKeyError Exception Value: 'cur_author' Exception Location: c:\users\user\desktop\learnpython\django\django\utils\datastructures.py in __getitem__, line 78 Python Executable: C:\.virtualenvs\djangodev\Scripts\python.exe Python Version: 3.7.2 Python Path: ['C:\\Users\\USER\\Desktop\\rmi', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\.virtualenvs\\djangodev', 'C:\\.virtualenvs\\djangodev\\lib\\site-packages', 'c:\\users\\user\\desktop\\learnpython\\django'] views.py @login_required def create_thread(request, board_id): board_style = 'css/board' + str(board_id) + '.css' cur_author = get_object_or_404(Author, user=request.user) if request.method == "POST": form = CreatePost(request.POST) if form.is_valid(): post = form.save(commit = False) post.board = get_object_or_404(Board, pk=board_id) post.created_at = timezone.now() post.parent = None post.save() return redirect('board', board_id) else: data ={ 'cur_author': cur_author, } form = CreatePost(data) context ={ 'form': form, 'board_id': board_id, 'board_style': board_style, } return render(request, 'rmi/create_post.html', context) and this is forms.py: class CreatePost(forms.ModelForm): class Meta: model = Post fields = ['character', 'title', 'content', 'parent'] widgets = {'parent': forms.HiddenInput()} def __init__(self,cur_author): super(CreatePost, self).__init__(cur_author) self.fields['character'].queryset = Character.objects.filter(author=cur_author['cur_author']) … -
Django 404: No object instance found matching the query
I'm trying to create a detail view for specific car instances in my project. I've just created a slug that passes each car's unique UUID into the url, but Django raises a 404 Error. It can't find the specific instance, but the urls are accurate and the url accurately matches the id. Also, I'm clicking in from the ListView which works fine. Error screenshot in browser ID confirmation from object admin page models.py class CarInstance(models.Model): .... id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this car") ... class Meta: ordering = ['date_added'] def __str__(self): return f'{self.manufacturer} {self.car_model}' def get_absolute_url(self): return reverse('showroom:car-detail', args=[str(self.pk)]) urls.py urlpatterns = [ ... path('car/<slug:car_detail>/', views.CarDetailView.as_view(), name='car-detail') ] views.py class CarDetailView(generic.DetailView): model = CarInstance template_name = 'car_detail' slug_field = 'car_model' slug_url_kwarg = 'car_detail' def get_queryset(self): return CarInstance.objects.all() -
TokenAuthentication object has no attribute 'get_user'
I'm trying to authenticate a user with an Authorization header containing a token generated by django-rest-knox. I also have two other authentication backends. To do this, I call the authenticate() method defined in knox.auth. However, it returns this error and fails to authenticate the user: WrappedAttributeError at /login/ 'TokenAuthentication' object has no attribute 'get_user' I need to define a get_user method to fix this. Is there something I can fix so that I don't have to implement a custom TokenAuthetication class with a get_user method? views.py from django.contrib.auth.models import User from rest_framework.response import Response from knox.views import LoginView as KnoxLoginView from knox.auth import TokenAuthentication class GetAuthToken(KnoxLoginView): permission_classes = [AllowAny] def post(self, request,*args, **kwargs): user = TokenAuthentication().authenticate(request=request) if user: return Response(status=200) else: requestToken = request.data.get('requestToken') if not requestToken: return Response({'result': 'error'}) user = User.objects.all().first() if user is None: return super().post(request, format=None) else: login(request, user, backend='knox.auth.TokenAuthentication') return super().post(request, format=None) return super().post(request, format=None) settings.py 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'adminutil', 'advisory', 'knox', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'knox.auth.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' : [ 'knox.auth.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ] } These are the server logs: Traceback (most recent call last): … -
Unable to understand errors when i run the command 'python manage.py migrate'
I have been following Django girls tutorial to learn Django web framework. https://tutorial-extensions.djangogirls.org/en/optional_postgresql_installation/ I have reached this part of the tutorial. Now I am completely stuck when I run the command python manage.py migrate. I cannot even run my server on the local host anymore, runserver brings the same error. All these errors started coming up since I changed my settings.py file to accommodate the Postgres database. I am in dire need of some help. I had postgres installed from before(version 11.4). Seeing these errors I removed it, and then downloaded it again, following the directions of the aforementioned tutorial. It was a useless effort, as the same problem came up. Traceback (most recent call last): File "/home/jpsofficedev/Documents/coding_for_girls/djangogirls/myvenv/lib64/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/jpsofficedev/Documents/coding_for_girls/djangogirls/myvenv/lib64/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/jpsofficedev/Documents/coding_for_girls/djangogirls/myvenv/lib64/python3.7/site-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/home/jpsofficedev/Documents/coding_for_girls/djangogirls/myvenv/lib64/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: Ident authentication failed for user "jpsofficedev" My experience in Postgres is null. Suggestions for some tutorial, documentation will also be appreciated. -
How to do model level custom field validation in django?
I have this model: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) and have this model form: class StudentIeltsForm(ModelForm): class Meta: model = StudentIelts exclude = ('student') def clean(self): cleaned_data = super().clean() has_ielts = cleaned_data.get("has_ielts") if has_ielts: msg = "Please enter your score." for field in self.fields: if not self.cleaned_data.get(str(field)): self.add_error(str(field), msg) else: for field in self.fields: self.cleaned_data[str(field)] = None self.cleaned_data['has_ielts'] = False return cleaned_data As you see, if a student has ielts, then he/she has to specify his/her scores in the model form. I now want to do this on the database level. So I need to customize my model save method, I guess. How should I do this? Will my StudentIeltsForm behavior be the same as before if I change it as below? class StudentIeltsForm(ModelForm): class Meta: model = StudentIelts exclude = ('student') I read this: https://docs.djangoproject.com/en/2.2/ref/models/instances/#validating-objects and this: https://kite.com/python/docs/django.db.models.Model.clean and I know that to iterate over model field I have to use for field in self._meta.fields: But I have not yet reached to … -
Why can't I get images from my S3 bucket when all public access blocked? 403 Forbidden
My Django website allows users to upload photos. When the s3 bucket is on public the media content loads fine on the site. However once i block all public access the content no longer loads and a 403 forbidden error is shown. In my code I have added the values needed to allow for authenticate requests. There are no bucket policy's or any CORS configurations. I have tried several different suggestions from blogs and tutorials but nothing seems to work. I have a user which has programmatic access and set the secret variables in the heroku environment and still get 403 error. I have tried hard setting the secret variables and still no success. settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } MEDIA_LOCATION = 'MediaStorage' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIA_LOCATION) MEDIA_FILE_STORAGE = 'MediaStorage' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_LOCATION = 'static' STATICFILES_LOCATION = 'StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATIC_LOCATION) django_heroku.settings(locals()) storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIA_FILE_STORAGE file_overwrite = False I expect the files to load when displaying them in the view web page. … -
Django Haystack - No module named 'haystack.backends.elasticsearch5_backend'
Im following the install instructions as per the haystack documentation http://docs.haystacksearch.org/en/master/tutorial.html#installation and the search engine installation https://django-haystack.readthedocs.io/en/master/installing_search_engines.html#elasticsearch I have installed Elasticsearch 5.1.16 which is listed as compatible and have put the settings in, the installation guide only has examples for Elasticsearch versions 1 and 2 but states that 5 is supported. so I changed to version 5 in the settings 'default': { 'ENGINE': 'haystack.backends.elasticsearch5_backend.Elasticsearch5SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, } I have also gone through the repo and can see that version 5 is in there but when I start my server I receive the error: return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'haystack.backends.elasticsearch5_backend' but then when I traverse the folder structure it hasn't installed the version 5 files root@4c1197e002e8:/myapp/# ls /usr/local/lib/python3.6/site-packages/haystack/backends/ __init__.py __pycache__/ elasticsearch2_backend.py elasticsearch_backend.py simple_backend.py solr_backend.py whoosh_backend.py and im using the same version as the git repo that has the 5 backend in it? root@4c1197e002e8:/myapp/# pip freeze | grep hay django-haystack==2.8.1 anyone help me out whats missing here? Thanks -
Django - Elasticsearch Highlighting
I have implemented elasticsearch into my Django website, now I'm trying to add highlighting and got stuck. What I want essentially, is to highlight the result everywhere on search page. Here is my documents.py: from django_elasticsearch_dsl import Document, Index from news.models import Article articles = Index('articles') @articles.document class ArticleDocument(Document): class Django: model = Article fields = [ 'title', 'description', ] I went through the docs and found: GET /_search { "query" : { "match": { "content": "kimchy" } }, "highlight" : { "fields" : { "content" : {} } } } How would I do what I want ? Where can I include these settings ? Thank you ! -
How to handle each object of v-for in vue?
I'm trying to build a like function using django rest api and vue. In the vue file, posts are rendered by v-for loop. And I want to change each Like Button Image whether a user has liked it or not dynamically. this is the API response. { "id": 48, "title": "Test post", "owner": { "username": "admin" }, "likes_count": 0, "user_has_liked": false }, { "id": 49, "title": "Second test post", "owner": { "username": "admin" }, "likes_count": 1, "user_has_liked": true }, and vue file. <b-card-group deck v-for="post in posts" :key="post.id" :post="post" class="border dashboard-card-container"> <b-card-header class="w-100 bg-white"> <span class="ml-3">{{ post.owner.username }}</span> </b-card-header> <b-card-footer class="w-100 bg-white"> <b-link v-on:click="postLike(post.id)"> <b-img v-if="post.user_has_liked" thumbnail :src="likeIcon" class="dashboard-icon" /> <b-img v-else thumbnail :src="notLikeIcon" class="dashboard-icon" /> </b-link> import { apiService } from "@/common/api_service"; export default { name: "home", data() { return { posts: [], notLikeIcon: require("@/assets/notlike.png"), likeIcon: require("@/assets/like.png") } }, methods: { getDashboardPosts() { let endpoint = "/api/dashboard/"; apiService(endpoint).then(data => { this.posts.push(...data); } }) }, postLike: function(pk) { let endpoint = "/api/posts/"+pk+"/like/"; let method = "POST"; apiService(endpoint, method).then(data => { }) } }, created() { this.getDashboardPosts() } }; Communication with API works fine. So, I'm wondering how to handle each post object. For example, In the post list page, if … -
Multiply two fields in django form and populate third filed with the result
I am creating a form in my django app like this: views.py @method_decorator([login_required, client_required], name='dispatch') class MaterialRequestFormView(CreateView): model = MaterialRequest template_name = 'packsapp/client/materialRequestForm.html' fields = "__all__" def form_valid (self, form): product = form.save(commit=False) product.save() messages.success(self.request, 'The material request was created with success!') return redirect('client:mat_req_table') models.py class MaterialRequest(models.Model): owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_sales') flow = models.ForeignKey(Flow, on_delete=models.CASCADE, related_name='flow') kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='kit') quantity = models.IntegerField(default=0) is_allocated = models.BooleanField(default=False) quantity_p1 = models.IntegerField(default=0) quantity_p2 = models.IntegerField(default=0) quantity_p3 = models.IntegerField(default=0) quantity_p4 = models.IntegerField(default=0) quantity_p5 = models.IntegerField(default=0) html <h2>Material Request Form</h2> <div class="row"> <div class="col-md-6 col-sm-8 col-12"> <form method="post" id="MaterialRequestForm" data-kit-url="{% url 'employee:ajax_load_kit' %}" data-product-url="{% url 'employee:ajax_load_product' %}" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit">Save</button> </form> </div> </div> <div id="products-table"> </div> <script> $("#id_flow").change(function () { console.log("function running"); var url = $("#MaterialRequestForm").attr("data-kit-url"); var flowId = $(this).val(); $.ajax({ url: url, data: { 'flow': flowId }, success: function (data) { $("#id_kit").html(data); console.log(data); } }); }); </script> <script> $("#id_kit").change(function () { console.log("function running"); var url = $("#MaterialRequestForm").attr("data-product-url"); var kitId = $(this).val(); $.ajax({ url: url, data: { 'kit': kitId }, success: function (data) { $("#products-table").html(data); } }); }); </script> The ajax is to get the table. Can I change it such that when I enter the quantity … -
Get results of the model only if child with Foreign key has records
I have two models as follows: class Tutorial(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) class Video(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING, blank=False, null=False) I want to get all Tutorials where there is at least one video in Video model Something as follows: results = Tutorial.objects.filter(id__in=Video.objects.filter....) Any idea how to do that? -
How to allow user access to the django-constance admin?
I have added CONSTANCE_SUPERUSER_ONLY=False to the settings file as django-constance manual recommends. But the constance.change_config line has not appeared in the user's rights list. What did I miss? -
Save checkbox values from csv django
I have CSV file in this formate I can get data into this field dynamically. How Can I save this data into database so that I can show easily as form of check boxes .And save data into model using this csv. My model is something like this restaurant = models.OneToOneField(User, on_delete=models.CASCADE) ArticleName = models.CharField(max_length=50, null=False, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2) Category = models.CharField(max_length=50, null=False, blank=False) Pickuptax = models.FloatField(null=True, blank=True, default=None) Ingredient = models.CharField(max_length=100) //As I can't assign static choice fields here. -
Django: Cannot load static image file with specific name?
I have .jpg file with name google_adsense, so I load it, like every other file from same folder with {% static 'core/images/google_adsense.jpg' %} but it doesn't appear, status from Network tab in browser is blocked:other If I change name to google_adsens for example or any other name it works fine. Also check for chars limit, but abvabv_abvabva works fine also. -
How to incorporate select2 in django forms for selecting multiple answers?
I'm trying to get multi-selecting in a dropdown list (pillbox or anything is fine). But I'm not been able to do it since I can't figure out how to install and import and use it. I've tried almost all answers here but cannot understand any of them. Currently, I'm using multiselect but I don't want checkboxes. My code: forms.py: from django import forms from django.forms import ModelForm from charts.models import HomeForm1 #Import the model from models.py class HomeForm(ModelForm): CHOICES = (("address1","address1"), ("address2","address2")) plot11=select2.fields.ChoiceField(choices=CHOICES,overlay="Choose an author...") class Meta: model = HomeForm1 fields = '__all__' models.py: #Importing Model from django.db import models from multiselectfield import MultiSelectField from survey import analysis #Backend coding module import ast global f1 f1=analysis.getQuestion() #get all the questions and their possible answers with a count in a string from f1=ast.literal_eval(f1)[0] #Convert it into a dictionary for key in f1.keys(): #Convert the values of dictionary in a nested dictionary f1[key]=f1[key][0] class HomeForm1(models.Model): ##################get the questions for the plot data########################################## choices1=tuple(map(lambda f: (f,f),list(f1.keys())[7:])) ###################get type of plot########################################################## choices_plot_types=((None,None),('bar','bar'),('horizontalBar','horizontalBar'),('line','line')) #Take dict_values and convert them into tuples eg.:('a','a') ###################assign the filters####################################################### for k in list(f1.keys())[:6]: q=list(f1[k].keys()) q.sort() choices=tuple(map(lambda f: (f,f),q)) locals()[k]=MultiSelectField(max_length=1000,choices=choices,blank=True) #Take the keys for filtering the data ###################assign the plot types … -
Configure multisite template loads
The current templates layout: A second site will soon be created, on a different domain. The logic of both sites is the same. The names of the templates are the same. It is need that when entering from the first domain, its templates are loaded, when entering from the second domain - its templates. If there are no such templates, load some common template. Make copies of templates not necessary. apps app1 templates folder_with_templates_1 index.html admin index.html app2 templates folder_with_templates_2 index.html admin index.html templates admin index.html 404.html 500.html What are the painless solution options? Write some crutch template loader? Did not work out. I can lay out the code, if necessary. Crutch Middleware, which will determine the website and load the appropriate templates? Configure dirs in the settings of each site? Found django-multisite, but failed to configure it. If necessary, I will show my settings. https://github.com/ecometrica/django-multisite Settings of first site: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '..', 'apps', 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # Project context processors 'apps.landing.context_processors.landing_settings', 'apps.landing.context_processors.page404_context', 'apps.landing.context_processors.user_token_data', ], }, }, ] -
Validation in Modelviewset
I have to validate image. I have tried add validator to field in models.py, but python cannot migrate validator depending on class. How can I add validation in this case in views.py validators.py class ValidateImageSize: ... views.py class EpisodeView(viewsets.ModelViewSet): serializer_class = EpisodeSerializer permission_classes = [BasicAuthorizationPermissions] queryset = Episode.objects.all() def create(self, request, story_id=None, *args, **kwargs): try: story = Story.objects.get(pk=story_id) except Story.DoesNotExist: raise NotFound kwargs = { 'story': story, 'title': request.data.get('title'), 'cover': request.data.get('cover'), } episode = Episode.objects.create(**kwargs) for image in dict(request.data.lists())['images']: EpisodeImage.objects.create(episode=episode, image=image) return Response({'episode_id': episode.id}, status=201) -
translate angular variables in django template
In my django project I can easily translate any string by the tag below: {% trans "any string" %} but there is a drop-down list in a page. I used angularjs to get the drop-down values as like below: <select class="form-control btn-bar-select" ng-model="selectedDivision" ng-change="changeDivision()" ng-options="division as division.name for division in divisions"> <option value="">{% trans "Select Division" %}</option> </select> I want to translate the drop-down list. Here division.name is responsible for the drop-down list values. Can I bring this under trans tag of django or any other way? -
Django Aggregate on related field with filter
Following problem: I have product groups containing products. These products can be visible in the frontend or not. I determine their visibility with the method frontend() (which contains a filter) like so: product_groups.first().products.frontend() Now I want to determine if I want to put a link for the product group on the homepage only if there are four or more products in it. With annotations I would do: product_groups.annotate(num_products=Count('products')).filter(num_products__gte=4) But this gives me of cause the count of all products and not the count of products visible in the frontend. So how do I put the additional filter frontend() into my query? To be clear, I want the Count() not on 'products' but on products.frontend(). -
How to stop SELECT before INSERT with Django REST Framework
I've used Django REST Framework to expose an API which is only used by another service to POST new data. It basically just takes json and inserts it in the DB. That's all. It's quite a high volume data source (sometimes more than 100 records/second), so I need to tune it a bit. So I was logging the (PostgreSQL) queries that are run, and I see that every POST gives 3 queries: 2019-10-01 11:09:03.320 CEST [23983] postgres@thedb LOG: statement: SET TIME ZONE 'UTC' 2019-10-01 11:09:03.322 CEST [23983] postgres@thedb LOG: statement: SELECT (1) AS "a" FROM "thetable" WHERE "thetable"."id" = 'a7f74e5c-7cad-4983-a909-49857481239b'::uuid LIMIT 1 2019-10-01 11:09:03.363 CEST [23983] postgres@thedb LOG: statement: INSERT INTO "thetable" ("id", "version", "timestamp", "sensor", [and 10 more fields...]) VALUES ('a7f74e5c-7cad-4983-a909-49857481239b'::uuid, '1', '2019-10-01T11:09:03.313690+02:00'::timestamptz, 'ABC123', [and 10 more fields...]) I tuned the DB for INSERTs to be fast, but SELECTs are slow. So I would like to remove the SELECT from the system. I added this line to the Serializer: id = serializers.UUIDField(validators=[]) But it still does a SELECT. Does anybody know how I can prevent the SELECT from happening? All tips are welcome! For complete info; the full Serializer now looks like this: import logging from rest_framework import serializers … -
Can't edit the image properties on django-ckeditor
I have an instance of django-ckeditor installed with the settings/models etc below. Although it allows me to upload images and save them within the RichTextUploadingField, it is not allowing me to alter their sizes. Within image properties, I cannot enter any of the input or drop down fields. I can only click the buttons. I do not know if the following has an impact and if I need to do something additional but I am loading the form through ajax as a bootstrap3 modal when a button is clicked which allows me to load the relevant form. Any thoughts on why the input boxes are not editable would be appreciated settings.py CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/" CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', #'toolbar': None, 'height': '100%', 'width': '100%', } } models.py class study(models.Model): researcher = models.ForeignKey("auth.user") # Researcher's name name = models.CharField(max_length = 51) # Study name instrument = models.ForeignKey("instrument") # Instrument associated with study #waiver = models.TextField(blank = True) # IRB Waiver of documentation for study or any additional instructions provided to participant waiver = RichTextUploadingField(blank = True) forms.py class RenameStudyForm(BetterModelForm): name = forms.CharField(label='Study Name', max_length=51, required=False) # Update study name #waiver = forms.CharField(widget=forms.Textarea, label='Waiver of Documentation', … -
How to do customize Model save method instead of form clean method and is it advisable?
I have this model: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) and have this model form: class StudentIeltsForm(ModelForm): class Meta: model = StudentIelts exclude = ('student') def clean(self): cleaned_data = super().clean() has_ielts = cleaned_data.get("has_ielts") if has_ielts: msg = "Please enter your score." for field in self.fields: if not self.cleaned_data.get(str(field)): self.add_error(str(field), msg) else: for field in self.fields: self.cleaned_data[str(field)] = None self.cleaned_data['has_ielts'] = False return cleaned_data As you see, if a student has ielts, then he/she has to specify his/her scores in the model form. I now want to do this on the database level. So I need to customize my model save method, I guess. How should I do this? Will my modelform behavior be the same as before? -
django model creation connecting to mssql
I am connecting to a legacy mysql database in cloud using my django project. i need to fetch data and insert data if required in DB table. do i need to write model for the tables which are already present in the db? if so there are 90 plus tables. so what happens if i create model for single table? how do i talk to database other than creating models and migrating? is there any better way in django? or model is the better way? when i create model what happens in the backend? does it create those tables again in the same database? -
Django Saleor installing Dashboard 2.0 on windows
I am trying to install Saleor Dashboard 2.0 on my Windows 10 machine for a dev environment. So far I have git cloned the git clone dashboard into the same folder as the Saleor project Then cd saleor/dashboard and ran npm i The instructions were not really clear on how to configure the API_URI to http://localhost:8000/graphql/. It is not in the settings.py and the instructions were not clear on where this is.