Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CreateView test fail
My configuration below (django 3.02): Models: class Assets(models.Model): assettag = models.CharField() ... class Item(models.Model): asset = models.OneToOneField('Assets') ... def __str__(self): return (f"{self.rfid_tag}" + " - " + f"{self.asset.assettag}") class Comments(models.Model): # I know, it should not be plural. item = models.ForeignKey('Item', default=None, null=True, on_delete=models.CASCADE, ) text = models.TextField() ... Form: class ItemInsertForm(forms.ModelForm): rfid_tag = forms.CharField(label='RFID Tag', widget=forms.TextInput(attrs={"placeholder":"96 bit EPC code", "pattern":"^[a-fA-F0-9]{24}$", "size":"25", "id":"rfid_tag", } ) ) asset = forms.CharField(label='AssetTag', widget=forms.TextInput(attrs={"placeholder":"Item Inventory Tag", "pattern":"{some regex}", "size":"25", "id":"asset", } ) ) comments = forms.CharField(label='Comments', required=False, widget=forms.Textarea(attrs={"rows":5, "cols":50, "id":"comments", } ) ) class Meta: model = Item fields = [ 'rfid_tag', 'asset', 'image', 'date', ] def clean_rfid_tag(self, *args, **kwargs): return self.cleaned_data.get("rfid_tag").lower() def clean_asset(self, *args, **kwargs): AssetTag = self.cleaned_data.get("asset") try: _asset = Assets.objects.get(assettag = AssetTag) except Assets.DoesNotExist: raise forms.ValidationError("Asset does not exist !") self.Asset = _asset return self.Asset View: class InsertView(SuccessMessageMixin, AuditMixin, generic.CreateView): template_name = '{some template}' success_message = "Item succesfully created" form_class = ItemInsertForm def form_valid(self, form): item = form.save(commit=False) _comment = form.cleaned_data.get('comments') item = form.save() if _comment: item.comments_set.create(text =_comment) self.log_insert(item) return super().form_valid(form) Test: class TestViews(TestCase): @classmethod def setUpTestData(cls) -> None: # create dummy assets cls.asset = Assets.objects.create(assettag="{some assettag #1}",) cls.asset2 = Assets.objects.create(assettag="{some assettag #2}") # create dummy item cls.item = Item.objects.create(rfid_tag='abcdef012345678900000000', asset=cls.asset) … -
Calling function from request function in views Django
I have simple html template with link, that starts script, in views that retrieves data to the page,in views file I have two functions: render function def output(request):(it retrieves data to the page) and another function def summoner(): that makes postgres quires in cycle and appends results to the list. Separately each of them work fine, but I have to call second function from render function and retrieve the data to the page, but now when I do that all I am getting is empty list. enter image description here template: <html> <head> <title> Python script </title> </head> <body> <a href="{% url 'script' %}">Execute Script</a> <hr> {% if data %} {{ data }} {% endif %} </body> </html> views: from django.shortcuts import render import pandas as pd import psycopg2 import os, glob conn = psycopg2.connect(host='127.0.0.1', database='db', user='user', password='pass') cur = conn.cursor() def insert_data_as_is(file_name): cur.execute('truncate table test_inv.start_tbl') with open(file_name, 'r') as file: cur.execute("insert into test_inv.start_tbl values {0}".format(file.read())) conn.commit() def insert_data_to_be(file_name): cur.execute('truncate table test_inv.res_calc_ratios_t') with open(file_name, 'r') as file: cur.execute('insert into test_inv.res_calc_ratios_t (test_no, test_name, hcode_id, ' 'hcode_name, hcode_' 'unit_name,' ' org_id, dor_kod, duch_id, nod_id, date_type_id, metric_type_id, cargo_type_id, val_type_id,' ' unit_id, dt, value, ss, dir_id, kato_id, vids_id) values {0}'.format(file.read())) conn.commit() path_start = 'files/csv_s/as_is/' … -
What is the proper way to use MVT?
I've just started using Django and I now face a conception problem : How do I use MVT properly ? More specifically, how do I manage multiple classes from a single function ? Usually, using MVC I would do something like that : models.py: class House: def __init__(kitchen, living_room): self.kitchen = kitchen self.living_room = living_room class Kitchen: def __init__(size): self.size = size class LivingRoom: def __init__(remark) self.remark = remark and some controller would do this: def build_house(kitchensize: str="big", tidyness: str="tidy"): my_kitchen = Kitchen(kitchensize) my_living_room = LivingRoom(tidyness) my_house = House(big_kitchen, tidy_living_room) return my_house I am confused about where to place build_house ; it has nothing to do in the views because I would need to rewrite it in each views using it. It also has nothing to do in the models because usually models should not instantiate other models, right? So what I have done yet is to create a controllers.py file which contains all the controller logic (in this example, the build_house function) i.e. managing models, parsing files... and a utils folder containing all the classes that are not saved in the database. This helps me keeping both my models and my views as tidy and reusable as possible. It … -
Django: FILE_UPLOAD_MAX_MEMORY vs DATA_UPLOAD_MAX_MEMORY
I am working with Django 2.2 and got stuck with file upload size validation. I have read django documentation: DATA_UPLOAD_MAX_MEMORY_SIZE FILE_UPLOAD_MAX_MEMORY_SIZE I only set DATA_UPLOAD_MAX_MEMORY (to 20 MB), as mentioned in documentation: "The check is done when accessing request.body or request.POST and is calculated against the total request size excluding any file upload data." But in my project it also checks my uploading file size in request.FILES. Can someone explain differences between FILE_UPLOAD_MAX_MEMORY and DATA_UPLOAD_MAX_MEMORY? And how to use them properly? -
Django like button for unregistered user
I am trying to create a like button for post. How to allow unregistered user to like the post and how to identify the user for uniqueness. Should I use cookies or ip address. -
is there any plugin for video marker?
i'm new on django framework. Currently I creating LMS where student can upload assignment in the form of video and teacher can view and play the student assignment. Now all things I've done but one issue is that i want to create the functionality in my LMS where teacher can mark corrections in video, so which plugin or how can i implement this functionality? -
search doesn't work when you enter an email
when you enter an email in the search bar, the data is not loaded and the user is not searched, but an error is thrown that such a user will not find it. It's already been rechecked. Can, I that the not see? all head broke, maybe someone has certain conclusions and sees what I do not see?thank you in advance! endpoints.py class UsersSearchEndpoint(AbsLoginRequiredAPIView): serializer_class = SearchSerializer def post(self, request, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) search_text = serializer.validated_data.get('search_text') user_profiles = self._get_user_profiles_by_unp(search_text, self.request.user.pk) if serializer.validated_data.get('as_unp') \ else self._get_user_profiles_by_company_name(search_text, self.request.user.pk) if user_profiles.count() > 5: user_profiles = user_profiles[:5] return Response(UserProfileSerializer(user_profiles, many=True).data) @staticmethod def _get_user_profiles_by_unp(search_text, self_pk): return UserProfile.objects.filter(Q(unp__icontains=search_text)).exclude(user__pk=self_pk) @staticmethod def _get_user_profiles_by_company_name(search_text, self_pk): return UserProfile.objects.filter(Q(company_name__icontains=search_text) | Q(user__email=search_text)).exclude( user__pk=self_pk) serializers.py class SearchSerializer(serializers.Serializer): search_text = serializers.CharField(required=False, allow_blank=True) as_unp = serializers.BooleanField(required=False) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email',) class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserProfile fields = ('company_name', 'unp', 'user', 'is_primary_contract', 'get_full_fio') -
How to update two models using one django form
I am facing one issue with django forms Here is my model : class User(models.Model): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class UserProfile(AuditFields): user = models.ForeignKey(User, on_delete=models.CASCADE) designation = models.CharField(max_length=200, blank=True) contact_number = models.CharField(max_length=20, blank=True) team = models.CharField(max_length=200, blank=True) manager = models.CharField(max_length=200, blank=True) joining_date = models.DateField(default=datetime.now) I need to create a form for editing profile details of the current user This is my form. But it is a model Form so only getting the detauls from the User Profile table only class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ['user'] How can I get first_name , last_name from User table and save it -
how to TestCase filefield upload for video in django?
I want to make TestCase filrfield upload and TestCase URLField for video in django. I can make a test case for Imagefile, but the filrfield and URLField I don't know what to do? my models.py video class Video(models.Model): image = models.ImageField(upload_to="images") cropping = ImageRatioField("image", "600x340") video_file = models.FileField(upload_to="videos/", blank=True) video_link = models.URLField(blank=True) my tests.py from django.core.files.images import ImageFile from django.test import TestCase from django_dynamic_fixture import G from .models import Video class VideoTestCase(TestCase): def test_video(self): with open("staticfiles/img/test.jpg", "rb") as f: for i in range(10): G(Video, image=ImageFile(f)) What should I do? Thanks. -
"name".sock file is not being created
I am trying to configure Gunicorn and Ngnix my Ngnix is configured correctly but Gunicorn is not. I am not able to create "name".sock file. [Unit] Description=gunicorn daemon Requires=gunicorn.socket After= network.target [Service] User=dexter dexter=www-data WorkingDirectory=/home/dexter/Documents/cpg_ad_tech/cpg_ad_tech ExecStart=/home/dexter/Documents/cpg_ad_tech/cpg_ad_tech_env/bin/gunicorn --access-logfile - \ --workers 3 \ --bind unix:/home/dexter/Documents/cpg_ad_tech/cpg_ad_tech/cpg_ad_tech.sock \ cpg_ad_tech.wsgi:application [Install] WantedBy=multi-user.target -
How to fetch the credit limit of User using Sendgrid Api in Python?
I am using Sendgrid for send mails from my project This is the configuration I have done in my settings.py: # Twilio SendGrid SENDGRID_API_KEY='apikey' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'sendgrid_username' EMAIL_HOST_PASSWORD = 'sendgrid_password' DEFAULT_FROM_EMAIL = 'myemail@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' There is no problem in sending emails from my project but I also want to show the user how much credits is left for them to send email(means how many more emails he can make). I am unable to fetch the credit limit from sendgrid using the api.. Does anybody know how to do it?Also I am very new to API so facing such difficulties. Thank you -
aggregate() + distinct(fields) not implemented
I have this code in my views.py, i just want to get the Average per Grading Categories gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories').aggregate(Sum('Grade'))['Grade__sum'] admin-site please click me to understand what i mean -
django - models - Meta class verbose_name translation
I used the standard gettext_lazy to translate verbose_name in models Meta class, hoping to translate the model name showing in admin page, failing... Anyone can help? models.py from django.utils.translation import gettext_lazy as _ class Profile(models.Model): ... class Meta(): verbose_name = _('Profile') verbose_name_plural = _('Profiles') And then terminal commands: $ django-admin makemessages -l ru -i venv $ django-admin compilemessages Everything else on the page is translated but the model names. -
Django Webpack loader for static libraries
We have a django app and want to collect all our static javascript libraries via npm and webpack instead of loading them via cdn. This is our package.json for the management of the libraries and installation. { "name": "test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "./node_modules/.bin/webpack --config webpack.config.js --mode production" }, "author": "Florian Eichin", "devDependencies": { "@babel/core": "^7.8.4", "@babel/preset-env": "^7.8.4", "babel": "^6.23.0", "babel-core": "^6.26.3", "babel-loader": "^8.0.6", "babel-preset-es2015": "^6.24.1", "bower": "^1.8.8", "css-loader": "^3.4.2", "file-loader": "^5.1.0", "style-loader": "^1.1.3", "webpack": "^4.41.6", "webpack-bundle-tracker": "^1.0.0-alpha.0", "webpack-cli": "^3.3.11" }, "dependencies": { "bootstrap": "^3.3.7", "jquery": "^3.4.1", "jquery-form": "^4.2.2", "jquery-ui": "^1.12.1", "js-cookie": "^1.5.0", "popper.js": "^1.16.1", "select2": "^4.0.13", } } We hav an index.js where we import all the dependencies like that: global.$ = require("jquery"); global.jQuery = require("jquery"); import('jquery/dist/jquery.min.js') import('jquery-form/dist/jquery.form.min.js') import('jquery-ui') import('js-cookie/src/js.cookie.js') import('select2/dist/js/select2.full.min.js') import('select2/dist/js/i18n/de.js') import('popper.js/dist/popper.min.js') import('bootstrap/dist/js/bootstrap.min.js') All of the files are then collected via webpack . The config for that looks like the following: const webpack = require('webpack'); const path = require('path'); const BundleTracker = require('webpack-bundle-tracker'); module.exports = { entry: {index: './assets/js/index.js'}, stats: { entrypoints: true }, output: { path: path.resolve('./assets/bundles/'), publicPath: 'http://localhost:8000/static/bundles/', filename: '[name]-[hash].js', chunkFilename: "[name]-[hash].js" }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", }), new BundleTracker({ path: __dirname, filename: './webpack-stats.json' }), ], module: … -
How to increase CharField by 1 in django?
Here I have some field like idnumber in my Profile model.Which will be the mix of integer, text and -. Everytime new profile registers I want to keep the - and text same but want to increase integer by 1. How can I achieve that ? user = get_object_or_404(get_user_model(), pk=pk) if request.method == 'POST': user_type = request.POST.get('type') user.profile.is_approved=True user.profile.save() if user_type == 'Some Type': # i got stuck here latest_profile = Profile.objects.filter(user_type='Some Type').last() user.profile.idnumber = latest_profile.idnumber + 1 #this will probably raise the error user.profile.save() My model field for id number is like this idnumber = models.Charfield(max_length=255,default="ABTX-123") ABTX- will be same but want to increase 123 to 124 if new profile registers -
Django CRM module not showing the Navigation Menu bar correctly
I am installing Django CRM from Micropyramid. I was able to compile and run the server successfully, however, the navigation menu is not showing correctly. Attaching screen shot. Thanks With Regards Ganesh. S enter image description here -
Django, updating DB column, rest_framework
A bit stuck at updating column in DB. I am sending put request to update a column. But an error returns. assert isinstance(response, HttpResponseBase), ( AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> here is the front end. sending request. updateInvoceProject(id, company_name){ return axios.put(API_HANDLER.database_api + "api/v1/update-project", {id, company_name}) }, serializer.py class InvocesSerializer(serializers.ModelSerializer): class Meta: model = Invoces fields = ("__all__") view @csrf_exempt @api_view(["PUT"]) def update(request): if request.method == "PUT": serializer = InvocesSerializer(data=request.data) if serializer.is_valid(): invoce = Invoces.objects.get(id=serializer.data["id"]) invoce.company_name = serializer.data["company_name"] invoce.save() return Response(serializer.data) urls urlpatterns = [ # path("api/v1/update-project", invocesView.update, name="update-project"), # ] But in the end, the error I mentioned above is popping. Am I missing something here? -
SUM columns in Django
I have a simple model that collects data (specifically integers) to display an election results in a table. I have 2 regions (more of course but let's say two for now) where data will be coming from. I want to display each regions and the total for each region and then display the SUM at the bottom of the table My base model is as follows; class Results(models.Model) region_number = models.Foreignkey(Regions) region_name = models.Charfield() polling_station = models.Charfield() party1 = models.IntegerField() party2 = models.IntegerField() party3 = models.IntegerField() Then I have two class inheritance class GeneralElections(Results) pass class RegionalElections(Results) pass And I want the printed output in my template to look something like this --------------------------------- regions party1 party2 party3 --------------------------------- 1 20 40 60 2 20 80 100 --------------------------------- Total 80 120 160 <------- More Importantly This! --------------------------------- Additionally I want to be able to have summary page that shows General Elections ----------------------- party1 party2 party3 ----------------------- 80 120 160 Regional Elections ----------------------- party1 party2 party3 ----------------------- 50 85 210 Up to this point I have been able to accomplish everything, except being able to print the SUM of each column at the bottom of the table Everywhere I've looked it said … -
django - python 3.8 any url obfuscate packages available?
Working with django and Python 3.8 for url obfuscation, however no python packages available for the same. The following py packages are not supported by python 3.8: url-obfuscate # link: https://pypi.org/project/url-obfuscate/ django-unfriendly # link: django-unfriendly Please suggest any url obfuscation packages. -
How to create custom list field in serializer, which contains another serializer(model), django rest framework?
I need to use a list of one model serializer in another, I have tried use SerializerMethodField() but didn't succeed. So i have following codes: models.py class TyresGroup(models.Model): code = models.CharField("Наименование группы колес", max_length=50) brand = models.CharField("Бренд", max_length=50) class Meta: verbose_name = "Группа колёс" verbose_name_plural = "Группы колёс" def get_image_filename(instance, filename): code = instance.tyres_group.code slug = slugify(code) return "post_images/%s-%s" % (slug, filename) class Images(models.Model): tyres_group = models.ForeignKey(TyresGroup, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_filename, verbose_name='Image') class Meta: verbose_name = "Фотография" verbose_name_plural = "Фотографии" class Tyre(models.Model): group = models.ForeignKey(TyresGroup, blank=True, on_delete=models.CASCADE) images = models.ManyToManyField(Images, related_name='tyresgroup', blank=True) type = models.CharField("Тип колеса", max_length=2, choices=TYRE_TYPES) code = models.CharField("Код протектора", max_length=10) title = models.CharField("Название", max_length=30) width = models.CharField('Ширина', max_length=5, choices=WIDTH) height = models.CharField('Высота', max_length=5, choices=HEIGHT) radius = models.CharField('Радиус', max_length=5, choices=RADIUS) speed_index = models.IntegerField('Индекс скорости') tread_depth = models.IntegerField('Глубина протектора') standard = models.FloatField('Какой-то стандарт') oa_dia = models.IntegerField("OA DIA") max_pressure = models.IntegerField('Максимальное давление(КРА/PSI)') certificate = models.CharField('Сертификат качества', max_length=5) distance = models.IntegerField("Преодолимая дистанция колёс") max_loading = models.IntegerField("Максимальная нагрузка") class Meta: verbose_name = "Колесо" verbose_name_plural = "Колёса" and serializers.py: class TyreSerializer(serializers.ModelSerializer): images = ImagesSerializer(many=True) class Meta: model = Tyre fields = '__all__' class TyresGroupSerializer(serializers.ModelSerializer): # tyres = serializers.SerializerMethodField() # def get_tyres(self, Tyre): # queryset = Tyre.objects.all() # return queryset.values() class Meta: model … -
I need help in creating a form for Django that Admin only can create
Hi I need some help in creating a Form that Admin can create. I'm still trying to work with the Forms page and I already created a form however it's giving me and Error. (1048, "Column 'user_type' cannot be null") How can I create a form when during creation I can choose which "user_type" I can assign the user. I tried the basic user creation and it's fine but I want it to be streamlined and more customized for future admin users. Here's my models.py: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, username, password=None, user_type=None, is_tester=False, is_senior_test_manager=False, is_superuser=False, is_pqa=False, is_staff=False, is_admin=False, is_test_lead=False, is_test_manager=False, is_active=True): if not username: raise ValueError("User must have a Username!") if not password: raise ValueError("User must have a Password!") user_obj = self.model( username=self.normalize_email(username) ) user_obj.set_password(password) user_obj.user_type = user_type user_obj.ad = is_admin user_obj.tm = is_test_manager user_obj.pqa = is_pqa user_obj.ts = is_staff user_obj.tl = is_test_lead user_obj.stm = is_senior_test_manager user_obj.superuser = is_superuser user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_pqa(self, username, password=None): user = self.create_user( username, password=password, is_pqa=True, user_type=1 ) return user def create_tester(self, username, password=None): user = self.create_user( username, password=password, is_staff=True, user_type=2 ) return user … -
How to override call_wrapper method in Django 1.9?
I am using Django 1.9 to expose SOAP 1.1 API with Spyne version 2.12.16 I need to implement logging for every request XML and response XML in my platform. Django urls.py is url(r'^your_data/', DjangoView.as_view( name="YourDataService", services=[YourDataService], tns='http://127.0.0.1:8000/', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())) views.py: from spyne.decorator import rpc from spyne.model.primitive import String, AnyDict from spyne.service import ServiceBase class YourDataService(ServiceBase): @rpc(String, String, String, _returns=AnyDict) def call_this_method(self, a, b, c): return {'aa': 'OK','bb': 'Great','cc': 'Perfect'} I read somewhere, overriding call_wrapper method of Spyne ServiceBase class can log request and response XML data for that service. But implementing the same resulted in weird logging etc issues: class ServiceBaseAbstract(ServiceBase): def call_wrapper(cls, ctx): try: return ctx.service_class.call_wrapper(ctx) except Exception as err: print err It gives an error: No handlers could be found for logger "spyne.application.server" API works fine without overriding call_wrapper. I am really confused and can't find a way out of this. Your help will be much appreciated. Thank you -
What language(s) should I use for my backend?
When I do research on the backend, I always see that there are multiple parts to it, such as the database, application, server... and see recommendations for different languages such as SQL or python. But do I really need different languages for the backend? For example, can Django(or any other backend language/library) handle all the main parts of the backend? And is PHP worth learning in 2020... -
adjust Data-table horizontal length in django template
I am using a Data-Table in my django template with zero configuration See here: Data-Table But it shrinks the table horizontally according to the content, I want it to keep it as the same size as the screen but unable to find any solution. Here's an image to simplify the question: Template: <script> $(document).ready(function () { $('#table_id').DataTable( ); }); </script> -
how to prevent html page reload in django
<html> <head> </head> <br> <body> <h2><center>Choose your pose</center></h2> <div><center> <datalist id="languages"> <option value="dancers-pose"> <option value="mountain-pose"> <option value="pranamasana"> <option value="tree-pose"> <option value="triangle-pose"> <option value="warrior-pose"> </datalist> <input type="text" id = "abc" list="languages"> <br> <br> </center> </div> <div> <center> <h2>Upload your image</h2> <form method='POST' enctype="multipart/form-data"> {% csrf_token %} <input type = "file" name="document"> <br> <button type = "submit">upload file</button> </center> </form> </div> <div> <center> <button type="button" onClick = "myFun()">Get Results</button> </center> </div> <script> function myFun(){ var try_pose = document.getElementById("abc").value; console.log(try_pose); try_pose1 = try_pose + ".jpg"; console.log(try_pose1); </script> </body> </html> Above is my html file def full(request): if(request.method == 'POST'): files = glob.glob('media/*') for f in files: os.remove(f) uploaded_file = request.FILES['document'] fs = FileSystemStorage() # uploaded_file.name = 'temp.jpg' fs.save(uploaded_file.name, uploaded_file) path = "media" + "/" + uploaded_file.name # im = Image.open("media/temp.jpg") im = Image.open(path) im = im.resize((620,620)) width, height = im.size im= im.save("media/temp.jpg") return render(request,'full.html') Above code is present in my views.py . When the image is submitted the data present in the textbox is lost may be because the page is reloaded. I request for a solution which might be a small change in the above code which would not reload the page so I can access the value of the textbox later …