Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why we need `django-webpack-looader` to serve Vue application through django?
I want to serve my Vue application (as SPA) through django, and I passed across this article. The author use django-webpack-loader to achieve this, but is not adding a simple TemplateView around dist/index.html will do the job: url(r'^app/', TemplateView.as_view(template_name='index.html'), name='app'), also this require altering settings.by as follow: 'DIRS': [ BASE_DIR + "/templates/", BASE_DIR + "/dist/", ] My question is what is the role of django-webpack-loader in the process if the app is already build using vue-cli? -
Image labeling web application using django
I am working on a project where I have to label the points on Image and whenever user will click on that point the label will appear. Is there any dependencies available for performing such kind of operations on Python. My web app will be based on Djnago. Ignore these. type Stats interface { CountUsers() int } var stats Stats func SetStats(s Stats) { stats = s } func GetStats() Stats { return stats -
AJAX POST not actually sending POST data with Django
I want to submit a form to my Django back end using an AJAX post. I have multiple forms on the page but only want the one the user submits to be the one that sends. The form is held in a modal: <div class="modal-body"> <div class='content-section'> <form method="POST" id="form{{ prod.id }}" class="showform" value="{{ prod.id }}" > <input type="hidden" value="{{ prod.id }}" name="prodid"> {% csrf_token %} <fieldset class='form-group'> {{ form|crispy}} </fieldset> </form> </div> </div> <div class="modal-footer"> <div class='form-group'> <button class="btn btn-outline-info submit-form" value={{prod.id}} form="form{{ prod.id }}" >Save To Profile</button> </div> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> When the submit button is pressed, it triggers the following AJAX : $(document).on('click', '.submit-form', function () { var thisButton = $(this)[0] var prodID = $(this).val(); var form = $("form" + prodID); $.ajax({ type: 'post', headers:{ "X-CSRFToken": '{{ csrf_token }}' }, url: '/ajax/validate_showadd/', dataType: 'json', contentType: 'json', data: { 'form': form.serialize(), "prodID":prodID, }, success: function (data) { console.log("sent") }, error: function(data) { console.log("error") } }); return false; }); However, within Django whenever I try access any of these values it just returns 'None' and the QueryDict for the POST request is empty. Thank you -
Python Django - Count objects based on owner that is the user
I have users who listed their textbook. I need to count objects in Textbook model and display total count in the side menu. Here is my Model from django.db import models from django.http import HttpResponse from django.urls import reverse from django.contrib.auth.models import User from django.utils.functional import cached_property class Textbooks(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True) title = models.CharField(max_length=1000) isbn = models.CharField(max_length=20) author = models.CharField(max_length=250) edition = models.CharField(max_length=50) rrp = models.CharField(max_length=30) about = models.TextField(max_length=1000, null=True) textbook_image = models.FileField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('textbooks:detail', kwargs={'pk': self.pk}) def __str__(self): return self.title I used Custom template tag class CustomTag(template.Node): def render(self, context): context['my_custom_tag_context'] = Textbooks.objects.filter(owner=self.user.request).count() return '' @register.tag(name='get_custom_tag') def get_custom_tag(parser, token): return CustomTag() enter image description here AttributeError at / 'CustomTag' object has no attribute 'user'. It seems that i cant use filter in template tag. is there any other way i can filter them and show the count by owner who is logged in? Here is what i intend to have. enter image description here -
Get Order_id and save to OrderItem
Tell me how I can get the order_id in order to add the product to the model OrderItem on page view detail order. I open the order page and I see the goods in the order and also on this page I have to add goods to the order. The product is stored in the database, but the order id does not accept and does not save. How to do it? views.py #saving product to order def ajax_add_own_product(request): data = dict() if request.method == 'POST': form = OwnOrderItem(request.POST) if form.is_valid(): data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = OwnOrderItem() context = {'form': form} data['html_form'] = render_to_string('include/order_container.html', context, request=request ) return JsonResponse(data) forms.py class OwnOrderItem(ModelForm): class Meta: model = OrderItem fields = ('sku', 'product_name', 'qty', 'price') model.py class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items', null=True) product_name = models.CharField(max_length=255, null=True) qty = models.PositiveIntegerField(default=1) price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) discount_price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) final_price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) total_price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) outsource_id = models.ForeignKey(Outsource, on_delete=models.PROTECT, null=True) technology_id = models.ForeignKey(Technology, on_delete=models.PROTECT, null=True) shipment_status_id = models.ForeignKey(ShipmentStatus, on_delete=models.PROTECT, null=True) sku = models.CharField(max_length=70, null=True) -
DJANGO/MAPBOX (mysql querey using js and returning to template which is mapbox)
Im looking for some help. I have a simple html template that displays a map using mapbox. The template calls a .js (app.js) which should query my remote MySQL DB and return the data and then plot it on the map. Error is 'data' is not defined. 1st question am I going about this in the right way? If not looking for advice. 2nd question how do I fix the error and will fixing it achieve what I want to do? app.js below; console.log("Starting..."); define(function (require){ var mysql = require(['node_modules/mysql']); var con = mysql.createConnection({ host: "connection details", user: "connection details", password: "" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); con.query("SELECT * FROM MCC_234", function (err, result, fields){ if (err) throw err; console.log(result); }); }); }) var data = [{ type:'scattermapbox', lat:['45.5017'], lon:['-73.5673'], mode:'markers', marker: { size:14 }, text:['Montreal'] }] var layout = { autosize: true, hovermode:'closest', mapbox: { bearing:0, center: { lat:45, lon:-73 }, pitch:0, zoom:5 }, } Plotly.setPlotConfig({ mapboxAccessToken: "access token" }) Plotly.newPlot('myDiv', data, layout) map3.html below; <html> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <script src="https://requirejs.org/docs/release/2.3.1/minified/require.js"></script> <title>Harry's Map</title> <style> .modebar { display: none !important; } </style> </head> <body> <div id='myDiv'></div> <script> src="js/app.js" </script> </body> </html> Still learning so any help greatly … -
how to extract the banks that were closed on 25th october 2019 from this dataset?
please The links is here for the dataset ='http://www.fdic.gov/bank/individual/failed/banklist.html' -
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 …