Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
opencv how to use imdecode imencode and know the image type
is there a way to determine the type of image like jpg, jpeg, png, etc so that I can decode it back to the same format ? For example here, I have a http post on an image file, it creates opencv object with imdecode, and recreates back the object (im not sure if this is right) with imencode. image_obj = request.data['image'] im_cv = cv2.imdecode(np.fromstring(image_obj.read(), np.uint8), cv2.IMREAD_UNCHANGED) ... do something like crop, detection, etc ret, buf_im_cv = cv2.imencode( '.png', im_cv ) <-- in this case I have to specify png, what if its jpg, etc -
Put some models out of the model.py to my created model.py?
In general, we start a app, then the app directory will like this: but, I now have a requirement, I want to add a module directory like this: I want to put the price's model in the price module directory. Whether this is possible? -
Django / PostgreSQL generic relationships with a TextField object_id field
I have a fairly basic looking Django model with a generic relationship: class AttachedMediaItem(models.Model): # Generic relation to another object. parent_content_type = models.ForeignKey( 'contenttypes.ContentType', related_name='attachedmediaitem_parent_set', on_delete=models.CASCADE) parent_object_id = models.TextField(db_index=True) parent_content_object = GenericForeignKey('parent_content_type', 'parent_object_id') (irrelevant fields removed) I inherited this codebase so I cannot fully justify all design decisions, however I believe parent_object_id is a TextField to support non-integer PKs on the related object (e.g. UUIDs). This model tends to relate to a wide variety of other models, so it needs to be very versatile in terms of what PK types it supports. Now, this model: class UnitType(models.Model): media = GenericRelation('media.AttachedMediaItem', content_type_field='parent_content_type', object_id_field='parent_object_id') (irrelevant fields removed). Note that I'm leaving the PK generation up to Django, meaning I'll get an integer PK for this model. Now, if I run this UnitType.objects.filter(media__isnull=True) An SQL error manages to bubble through the ORM: ProgrammingError: operator does not exist: integer = text LINE 1: ...a_attachedmediaitem" ON ("products_unittype"."id" = "media_a... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. My understanding is that this is due to the difference in PK fields. Short of changing the generic object ID field type to an integer field (not … -
Image is not shown
I wrote in urls.py from . import views from django.contrib import admin from django.urls import path,include app_name = "app" urlpatterns = [ path('test1', views.test1,name='test1'), path('test2', views.test2,name='test2'), ] in data.py @login_required def test1(request): return render(request, 'test1.html', {'chart': _test1(request)}) @login_required def _test1(request): results = Data.objects.order_by('id').last() x = results.xlist y = results.ylist font = {'family': 'IPAexGothic'} matplotlib.rc('font', **font) plt.plot(x, y, color="white") jpg_image_buffer = io.BytesIO() plt.savefig(jpg_image_buffer) array = base64.b64encode(jpg_image_buffer.getvalue()) jpg_image_buffer.close() return array views.py is empty. When I call test1 method,image is not shown in test1.html.When I wrote data.py's codes in views.py,image was shown.So I think method of starting with _ causes this error,but really cannot know hot to fix this.What is wrong in my codes?How should I fix this? -
MultipleChoiceField form not displaying user's instance of form
I've implemented a MultipleChoiceField form with a CheckboxSelectMultiple. It works perfectly in that the form is displayed and user selected options are saved to the BaseServicesOffered model as desired. The problem is that when the user goes back to the form, the checkboxes that the user had previously selected/submitted are not selected -- they are all unchecked. I'd imagine that it's a problem with my views.py. Here is my code: models.py class BaseServicesOffered(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) service = models.CharField(max_length=255, default='', null=True, blank=True) def __str__(self): return self.user.username forms.py class BaseServicesOfferedForm(forms.ModelForm): service = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): user = kwargs.pop('user') #this takes in the value of 'user', which is passed from the view function. super(BaseServicesOfferedForm, self).__init__(*args, **kwargs) self.fields['service'].choices = [(t.id, t.service) for t in AllServices.objects.filter(industrycode=user.userprofile.industry)] def save(self, commit=True): instance = super(BaseServicesOfferedForm, self).save(commit=commit) return instance class Meta: exclude = ('user',) model = BaseServicesOffered views.py @login_required(login_url="/accounts/login/") def baseservicesoffered(request): try: base_services_offered = BaseServicesOffered.objects.create(user=request.user) except: pass user = request.user instance = get_object_or_404(BaseServicesOffered, user=user) form = BaseServicesOfferedForm(request.POST or None, user=request.user, instance=instance) if request.method == 'POST': if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('/accounts/profile/') else: context = {'form': form} return render(request, 'accounts/setup8.html', context) context = { 'instance': instance, 'form': form, } return … -
Django is broken after removing all pyc files and adding them in gitignore
So I did this find . -name "*.pyc" -exec git rm -f "{}" \; added *.pyc to gitignore and now I have problem - Django doesn't start it complains on ImportError: No module named *MY_APP_NAME*.apps how can I fix this and get rid of pyc files ? -
Save aditional instance fields when you save the file, in upload_to method
In a Doc model I have a FileField document: document = models.FileField(upload_to=file_upload_to) filename = models.CharField(max_length=255) file_type = models.CharField(max_length=255) At this moment the instance is not saved. I want to add/set in the method file_upload_to the filename and file_type, before the Doc instance/model is saved. Now, I'm doing it in the form: obj.filename = self.cleaned_data[field].name.lower()) obj.file_type = self.cleaned_data[field].content_type.lower() But, for Django Admin, is harder to create a custom inline formset/form, so I try to avoid it. -
How to pass a variable containing graph to a template in django
Suggest an example for passing a python variable containing a simple graph to a template in django -
Whitenoise to serve static files locally
As described in their docs here, I am configured my application to serve static files locally. The only problem I am facing is that I am unable to determine if it is django or whitenoise which is serving static files? Steps which I followed: pip install whitenoise # install whitenoise pip install brotlipy # install brotlipy for compression INSTALLED_APPS = [ # default django apps 'django.contrib.messages', # REMOVE IN PRODUCTION # See: http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', # other apps ] # add white-noise middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', # static files serving 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # other middlewares ] # add staticfiles STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # run collecstatic python manage.py collectstatic # restart the server python manage.py runserver # This gives me following [10/Apr/2018 12:12:40] "GET /static/debug_toolbar/css/print.css HTTP/1.1" 304 0 [10/Apr/2018 12:12:40] "GET /static/chartkick.js HTTP/1.1" 304 0 [10/Apr/2018 12:12:40] "GET /static/debug_toolbar/js/jquery_pre.js HTTP/1.1" 304 0 However, I expect something like this, [10/Apr/2018 12:12:40] "GET /static/debug_toolbar/css/print.636363s6s.css HTTP/1.1" 304 0 [10/Apr/2018 12:12:40] "GET /static/chartkick.2623678s3cdce3.js HTTP/1.1" 304 0 [10/Apr/2018 12:12:40] "GET /static/debug_toolbar/js/jquery_pre.6276gdg3js8j.js HTTP/1.1" 304 0 How can I check if whitenoise is working and that it is serving static files? -
For Loop not working when uploading csv file in django
I am trying to upload csv file to django model, the code works okay but the for loop only read the first row of the csv file instead of looping through all the rows. Here is the code: csv_file = request.FILES["csv_file"] file_data = csv_file.read().decode("utf-8") lines = file_data.split("\n") for line in lines: fields = line.split(",") print(fields) This is the tutorial I followed upload and process csv file in django -
Django Forms: dealing with un-validated request.POST
In short: I have a model with several fields, and on this model is a foreign-key field connecting it to to a User instance. Then, I have a model-form(1) that generates HTML for this model's fields, and that with a custom ModelChoiceField-instance that presents UserProfile-instances instead of User-instances. To validate the submitted information, I have a form (regular form) that validates that a UserProfile-instance was submitted. If it was, I update request.POST (through a copy of it), and validate against a second model-form(2) that exactly mirrors the underlying model. This all means that I first have to pass a request.POST with a lot of un-validated information into a form that only validates part of it, then updated a copy of a partially validated request.POST, edit it, and then finally validate it again. Is all of this safe? Is it considered bad practice/unsafe to pass a request.POST with a lot of information into a form that only validates one part of it? Additionally, is it safe to make a copy of a request.POST that is only partially validated - and then update it? To what degree can you work with objects containing unsafe information, such as request.POST, without it becoming a … -
multi Language menu in django rest frame work
i am new in Django rest frame work.I have a language selection option in my application when i choose English,all navigation table entries should be in English else it should be french. my model class Menu(TreeItemBase): USER_STATUS_CHOICES = ( ('active', 'Active'), ('inactive', 'Inactive'), ) create_date = models.DateField(auto_now_add=True, blank=True, null=True) modified_date=models.DateField(auto_now_add=True, blank=True, null=True) status = models.CharField(max_length=50, choices=USER_STATUS_CHOICES, default='active') how can i implement this successfully?please help -
add fields in meta data using django rest framework
Response given by my application is as below but I also want to add another field next to 'previous' in meta data,how to add IP to meta data without adding fields to pagination {"count": 100, "next": "http://127.0.0.1:8000/users/?page=2", "previous": null, "results": [ {"first_name": "john", "last_name": "a", "mail" : "johnabi@mail.com" } -
Foreign key choosable when create the model instance
I have two models: class Amodel(models.Model): name = models.CharField(max_length=8) desc = models.CharField(max_length=256) class Bmodel(models.Model): name = models.CharField(max_length=8) desc = models.CharField(max_length=256) now I have another model: class Cmodel(models.Model): name = models.CharField(max_length=8) f_model = models.ForeignKey(to='there I want to dynamic refers to Amodle or Bmodel when create the Cmodel instance') I want the Cmodel's f_model is choosable when Create the Cmodel instance, whether this is possible? -
Error in Submitting form in Django
I was working on a project and got stuck really bad. I was trying to create a Edit Profile functionality and created a form for it(by using funciton based views, feels flexible to work with them) I am storing the users in User table which is in django.contrib.auth.models but wanted to store additional info like Phone no, facebook id, twitter id etc. in a different table in which i Created a OneToOne field between the User and their Info. Now during the Submission of Edit Profile form the OneToOne field is giving me some problems. I am sharing the whole code: models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import RegexValidator # Create your models here. class UserInfo(models.Model): userinfo = models.OneToOneField(User, on_delete=models.CASCADE, related_name='info') username = models.CharField(max_length=100, blank=True) profilepic = models.ImageField(blank=True) description = models.CharField(max_length=2000, blank=True) phoneregex = RegexValidator(regex=r'^\+?1?\d{9,15}$') phonenumber = models.CharField(validators=[phoneregex], max_length=13, blank=True) facebook = models.URLField(max_length=200, blank=True) twitter = models.URLField(max_length=200, blank=True) github = models.URLField(max_length=200, blank=True) linkedin = models.URLField(max_length=200, blank=True) address = models.CharField(max_length=1000, blank=True) datejoined = models.DateField(auto_now=True) Skills = models.CharField(max_length=200, blank=True) def __str__(self): return self.username views.py def EditProfileView(request, uid): form = EditProfileForm() user = User.objects.get(id=uid) userinfos = UserInfo() if request.method == 'POST': form = EditProfileForm(request.POST) if form.is_valid(): print("form is … -
Database triggers in unmanaged models
We have a lot of unmanaged models in our Django app (we hand wrote the create, query, insert sql for them). However, for haystack etc, we have written the models to reflect the db tables. What we wanted to do was trigger an email when data changed for a particular attribute in a particular model. Database triggers are a way to achieve this, but I was wondering if django signals (or something else?) can help us here. -
How to do a simple calculation in Djano RestFrameWork
model.py class SaleE(models.Model): qty = models.CharField(max_length=250) rate = models.CharField(max_length=250) tax = models.CharField(max_length=250,null="True") slno= models.CharField(max_length=250) ptype =models.CharField(max_length=250) pdiscription = models.CharField(max_length=250) pname = models.CharField(max_length=250) amount = models.CharField(max_length=10) Serializer.py class SaleESerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SaleE fields = ('id','slno','pname','ptype','pdiscription','qty','rate','tax','amount') Here i want to do a simple calculation for an example if i give a amount 200 in addition result should be like 400 in backend itself it should calculate so how to do that. -
how to check content-type in UnityWebRequest's response?
how to check content-type in UnityWebRequest's response? Is there any attribute that the UnityWebRequest response has for the content-type? I want to make sure that the response I sent from Django server came in a normal Json format. Will not you give me any answers? -
One to many queryset in django
I have 2 tables, Item and UserDetail. In table Item, I have item_id and item_name like this: My UserDetail table like this: I need to get user's username, and their most recent updated(e.g, Tina's education level was BSc on 05/01/2015 and changed to MSc on 05/01/2017. So I have to pick MSc for her education level), email, home phone, cellphone and education information. For any missing info, I leave it as blank. So my result would be: [{'username':John, 'email':'john@abs.com', 'homePhone':'', 'cellPhone':'', 'education':''}, {'username':Jade, 'email': jade@email.com, 'homePhone':111 456-7890, 'cellPhone':'','education':''}, {'username':Tina, 'email':'', 'homePhone':'', 'cellPhone':'211 234-5678', 'education':'Msc'},] Currently, I have queryset like this in my view.py: items=Item.objects.filter(Q(item_id__in=(2, 3, 4, 6))).values('item_name').order_by('item_id') users=[username1, username2, ...] for user in users: users_data = UserDetail.objects.filter(username=username)\ .filter(Q(id__in=(2,3, 4, 6)).values('id','record')\ .order_by('id').latest(DateRecorded) qs1=[user] for item in items: for value in users_data: user_data='' if item['item_id']== value['id']: user_data=value['record'] break qs1.append(data) qs2.append(qs1) This works OK. However, the format of qs2 is not exactly the one I expected. I am getting qs2 like this: [[u'John', u'john@abs.com', u'', u'', u''], [u'Jade', u'jade@email.com', u'111 456-7890',u'',u''], [u'Tina', u'', u'', u'211 234-5678', u'mac'],] Also, it takes more time to get the result back. Does anyone have good suggestion on this? -
Send PDFs by email
I'm using djago easy pdf to show pdfs in my app but now I want to send the file by email using EmailMessage but I don't know how I can do it. This is part of my code to send the html: email_body = render_to_string( 'mails/supplier_receipt_html.html', {'data': data, } ) msg = email_body headers = {'Reply-To': "contacto@comuna18.com"} TO = 'mauricio.munguia@comuna18.com' mail = EmailMessage(subject, msg, 'contacto@comuna18.com', [TO], headers=headers) mail.content_subtype = "html" mail.send() -
JS script load order in Django
I have: a base template, with content block, and block-scripts a page page template with block-scripts and a 'nav' include template the 'nav' include template with block-scripts I'm chasing a JS dependency problem with JQuery (loaded on the base template), where bootstrap is complaining in the console util.js:70 Uncaught TypeError: Cannot read property 'fn' of undefined because jQuery isn't loaded. In the 'nav' include templates block-script I put : <script type="text/javascript" > debugger; </script> to get a snapshot of what state the page is in. The body is not loaded, and I can only see the JS files Placing the same debugger code in the base template after jQuery is declared fails to stop the loading of the page, and is never executed. (it does work before jQuery is declared?) How do I debug the loading of the JS files with nested/inherited/included templates in Django, and/or ensure the proper load ordering of JS files given the hierarchical structure of the templates and includes? -
how to run Django code when click a button?
I'm using Django to write my own Blog site,and design a Like model,when user click the Like button under the post,the button will change color,meanwhile the post's like count will add 1.So my question is,how to run Django code to add Like's count and change the button color meantime?And one more condition,when user click the button,the page SHOULD NOT be reloaded or scrolled,because I want to keep the page position when user click the button.Thanks~ -
app to plugin django cms error
I want to create a plugin on a web page through an app, however, when loading the plugin to the page doesn't load the content of it, but on the page of the app if it loads the content of the application. I think that the problem can be in the code of the definition of the plugin or in the template, I tried with the suggestion in this link http://docs.django-cms.org/en/latest/how_to/custom_plugins.html#handling-relations, but it doesn't work just runs an error. the app is :https://github.com/tomwalker/django_quiz/tree/master/quiz I've been using python 3.4, django 1.8, djangoCMS 3.5 this is how the plugin content is displayed This is how it should look, this is the content of the application this is the code of models.py from django.db import models from cms.models import CMSPlugin from quiz.models import Quiz, Question class QuizPluginModel(CMSPlugin): quiz = models.ForeignKey(Quiz) def __unicode__(self): return self.quiz.question this is the code of cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from quiz_cms_integration.models import QuizPluginModel, QuestionPluginModel from django.utils.translation import gettext as _ @plugin_pool.register_plugin # register the plugin class QuizPluginPublisher(CMSPluginBase): model = QuizPluginModel # model where plugin data are saved module = _("Quiz") name = _("Quiz Plugin") # name of the plugin in the interface render_template = … -
Mysqldb problems copying django site to new server
I'm stuck. I'm trying to replicate my fedora setup on a second server. I've got problems. My environment: - mysql (mariadb) - python3 - django - apache with mod_wsgi I'm getting a 500 Internal server error. When I zoom in on the httpd error_log I see this: [Mon Apr 09 22:44:14.119939 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] mod_wsgi (pid=2728): Exception occurred processing WSGI script '/var/www/html/at/at/wsgi.py'. [Mon Apr 09 22:44:14.120097 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] Traceback (most recent call last): [Mon Apr 09 22:44:14.120178 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] File "/var/www/html/at/at/wsgi.py", line 16, in <module> [Mon Apr 09 22:44:14.120190 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] application = get_wsgi_application() [Mon Apr 09 22:44:14.120206 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] File "/usr/local/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Apr 09 22:44:14.120214 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] django.setup(set_prefix=False) [Mon Apr 09 22:44:14.120228 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] File "/usr/local/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup [Mon Apr 09 22:44:14.120236 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] apps.populate(settings.INSTALLED_APPS) [Mon Apr 09 22:44:14.120250 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] File "/usr/local/lib64/python3.6/site-packages/django/apps/registry.py", line 81, in populate [Mon Apr 09 22:44:14.120258 2018] [wsgi:error] [pid 2728:tid 140190313469696] [client 192.168.1.123:52304] raise … -
Does Django have a method of storage like HTML5's localStorage or sessionStorage?
Does Django have a method of storage like HTML5's localStorage or sessionStorage? I want to use the Django/Django-Rest-Framework as the backend of my project. but whether the Django has a convenient storage method to server my project? if in the HTML5 there are localStorage and sessionStorage, which is very useful.