Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Obtaining information from Requests POST Method
I am using the requests library with python 3. My goal is a two-step process: Send post request from python program to my Django app. Process that post request by creating a new database entry with the information sent in said Django app. I think the first part has been set-up properly, the development server registers the POST requests. However, I am having two-problems with step two: The development server is saying that what I am doing is forbidden: Forbidden (CSRF cookie not set) I am not really sure how to handle the request sent from the python program in Django. The information I have come across online assume that a form is used to POST information and that an another view has to be created. I just one to create a single data-base entry with the string sent by a python program using the requests library. -
Django ORM Issue
I am learning RestAPI and When I try to post data to update my database columns the modified_on column should automatically populated to current date and time but it is not updating. I am currently using django cassandra engine ORM where there is no functionality like auto_add_now() or auto_now(). Can any one give a suggestion where am I going wrong? Model Class: class Mydb(DjangoCassandraModel): id = columns.UUID(primary_key=True, default=uuid.uuid4()) user_name = columns.Text() user_email = columns.Text(default=None) user_password = columns.Text() description = columns.Text() creation_date = columns.DateTime(default=datetime.datetime.today(), static=True) modified_on = columns.DateTime(default=datetime.datetime.today()) My Serialization class: class TaskSerializer(serializers.Serializer): # id = serializers.UUIDField(default=uuid.uuid4) USER_ID = serializers.UUIDField(default= uuid.uuid4(),source='id') # user_name = serializers.CharField(max_length=50) USER_NAME_FIELD = serializers.CharField(max_length=50, source='user_name') USER_EMAIL = serializers.CharField(source='user_email') USER_PASSWORD = serializers.CharField(max_length=20, source='user_password') EXPLANATION = serializers.CharField(max_length=100, source='description') MODIFIED_AT = serializers.DateTimeField(default=datetime.datetime.today(), source='modified_on') CREATED_ON = serializers.DateTimeField(default=datetime.datetime.today(), source='creation_date') def create(self, validated_data): return Mydb.objects.create(**validated_data) def update(self, instance, validated_data): # instance.id = validated_data.get('id', instance.id) instance.user_name = validated_data.get('user_name', instance.user_name) instance.user_email = validated_data.get('user_email', instance.user_email) instance.user_password = validated_data.get('user_password', instance.user_password) instance.description = validated_data.get('description',instance.description) instance.modified_on = validated_data.get('modified_on', instance.modified_on) instance.save() # instance.creation_date = validated_data.get('creation_date', instance.creation_date) -
ajax get nested dict from django views.py. How can i access the nested data?
I use to ajax get nested dict from django views.py. How can i access the nested data? In views.py class Dash(): def get(self, request, format=None): data = {'index':{'a':[1,2], 'b':[2,3]}, 'value':{'a':[2,3], 'b':[3,4]}} return Response(data) In urls.py url(r'^api/chart/data/Dash$', Dash.as_view()) In Dash.html ` var endpoint = '/api/chart/data/Dash' var index = [] var value = [] $.ajax({ method: "GET", url: endpoint, success: function (data) { index = data.index value = data.value setChart() }, error: function (error_data) { console.log("error") console.log(error_data) } }) function setChart() { var rbline = echarts.init(document.getElementById('rb-line')); rbline.setOption({ xAxis: [{ type: 'category', data: index['a'] }], series: [{ name: 'data', type: 'line', data: value['a'] }] });` No chart shows. I am new to Jquery, can somebody help me? -
Django - Exclude a value from a .value_list
Greeting everyone, I trying to filter a specific value list from my model below is my code : employee_name = WorkOrder.objects.filter( project_id=48 ).values_list( 'assign_to__official_name', flat=True ).distinct() print(employee_name) and this is the output I receive <QuerySet ['JOHN', 'GEOFF', 'KYLE', 'NONE', 'BRUCE', 'CLARK',]> How can I exclude the value 'NONE' from this queryset based on its value and not its ID? Anyhelp is much appreciated thanks -
502 Bad Gateway | nginx/1.10.3 (Ubuntu). server not working
I followed this article https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04 in AWS EC2 ubuntu 16.04 image and getting 502 Bad Gateway | nginx/1.10.3 (Ubuntu) on my webserver. What went wrong? -
Django model datas as preset for creating other model
I'm actually writing an application for a BioTech laboratory. The idea is to prepare environments with preset list of products. There is also a need to handle the stock of products. I tried the following structure but I have no idea how to handle the presets... #models.py class products(models.Model): nutrients = models.CharField(max_length=10) globalQuantity = models.FloatField() rcvdate = models.DateTimeField() user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) lot = models.CharField(max_length=50) class environments(models.Model): lot = models.CharField(max_length=25, unique=True) date = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.SET_NULL) initvolume = models.FloatField() preparation = ? class presets(models.Model): name = models.CharField(max_length=25) product = models.ForeignKey('products', on_delete=models.SET_NULL) quantity = models.FloatField() The idea is then to populate preset like following : 1. name = preset1 | product = NH4 | quantity = 50 2. name = preset1 | product = SO4 | quantity = 25 3. name = preset2 | product = NaCl | quantity = 40 4. name = preset2 | product = Mn | quantity = 30 Where a "recipe" (like preset1 and preset2) contains different products. It must be dynamic because users needs to be able to add "recipes" if they want. The problem is : " How to add a preparation to an environment using one preset defined in the … -
Build a website can perform excel functions like match and index with python
do not laugh at my beginner questions, but I am new to coding (python mostly). I use excel a lot in my daily work. Basically, making a spreadsheet that allows people select the product configuration then return its part number to place order.enter image description here As per in the screen shot click "Y" or "N" to select the configuration and return the part number. Behind the scene there is a sheet contains all the part numbers (a few thousands) match the configuration and many excel function to lookup the Part number. Due to version difference and I update the part number frequently, distributing the excel file to different people is a nightmare. So I want to make a website contain all these functionality, so I do not need to worry people use excel 2007 or use the spreadsheet 4 months ago. So the question is what python skill I need to accomplish this task? Note that is not to put the whole excel file on the website and use python to manipulate the excel functions. It is to create a "excel alternative" web app but can achieve those excel functions. They are not some advanced excel functions but just … -
which technology or programming language to use?
For a side project with a colleague, i have to create an engine that will be used by the end users. I attached a image to explain further: Architecture To give more details the Java engine of my colleague will send on new event json objects to me using post or using akka api. My engine has to listen for these new json objects. When a new object arrives it has to be stored in a mongoDB. After that some sentiment analysis has to be done on a part of the content. The end user would browse to a page to see statistics and other information. When this works i will probably add a required login with OAuth but thats in a later stage. Now my questions is what do you experts recommend to use as the Unknown Engine? I was thinking of python with the Django Framework (i like programming in python) NodeJS with jquery Something else For criteria's i'm thinking of the following: Rapid development in producion LightWeight for better response time Documentation available I'm eager what you have for experts ideas on this matter. Kind regards, Didier -
Import CSV to Postgresql
I am working on Django based web application. I am going to import csv to postgresql database, which has over 100,000 lines, and use it as a database for Django application. Here, I've faced two problems. The field name includes special characters like this: %oil, %gas, up/down, CAPEX/Cash-flow, D&C Cape,... 1st, How should I define the field name of Postgresql database to import csv? 2nd, After import, I am going to get data through django model. Then how can I define the Django model variable name that includes special characters? Of course, It's possible if I change the column name of the csv, but I don't want to change it. I want to import original csv without any changes. Is there any solution to solve this problem? -
Get all records data to a Widget without making a new Query in the database
I have 2 Models Product and Category with - ManyToMany Relation Product-Category and self ForeignKey for Category class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) class Product(models.Model): categories = models.ManyToManyField(Category) name = models.CharField(max_length=255) and the Product creation form: class ProductModelForm(ModelForm): class Meta: model = Product fields = ['categories', 'name', 'short_description', 'description'] widgets = { 'categories': MyWidget, } By default ManyToMany becomes ModelMultipleChoiceField and coresponds to SelectMultiple Widget. I'm creating a new widget inheriting from SelectMultiple. My issue is that in all widgets by default Django send from the record just the value defined inside def __str__ on the Model. In case of Select also pk. (None, [{'name': 'categories', 'value': 7, 'label': 'Category 2', 'selected': True, 'index': '1', 'attrs': {'selected': True}, 'type': 'select', 'template_name': 'django/forms/widgets/select_option.html'}] I need to have in the Widget also other information like the parent value. Off course I can make another query and get the data from the database, but that means I have 2 queries one done by me and one by Django. Is there any way to make Django To send all record data to the widget instead of just what was defined in __str__ ? Changing __str__ is not an option because … -
I am using django tables 2 and wanted to add some extra javascript and css to filter and export data to a csv but it is not working for some reason
the div tag for adding the scroll bar is working for the table but the css and javascripts are not working how to include these in the table <div style="width: 2500px; height: 600px; overflow-y: scroll;"> {% block extracss %} <link ref="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"> <link ref="stylesheet" type="text/css" href= https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css> {% endblock %} {% render_table table %} {% block extrajs %} <script type ="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script> <script type ="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script type ="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script> <script type ="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.flash.min.js"></script> <script type ="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script> <script type="text/javascript"> $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copy' ] } ); </script> {% endblock %} {% endblock %} -
How do I save the foreign key?
I want to upload multiple images. class IssuePanel(models.Model): issue = models.ForeignKey(ComicIssue, on_delete=models.CASCADE) panel = models.FileField(upload_to='comic_issues_files/panels/') date_uploaded = models.DateTimeField(auto_now_add=True) After following the examples on django-multiupload's repository on github, I have this on forms.py class PanelsForm(forms.ModelForm): class Meta: model = ComicIssue fields = ('issue', 'issue_title', 'issue_cover', 'issue_description', 'issue_cover', 'issue_file') panels = MultiFileField(min_num=1, max_num=20, max_file_size=2048*2048*5) def save(self, commit=False): instance = super(PanelsForm, self).save() for each in self.cleaned_data['panels']: IssuePanel.objects.create(panel=each, issue=instance) return instance views.py class ComicIssueCreate(LoginRequiredMixin, CreateView): model = ComicIssue slug_field = 'comicseries_id' form_class = PanelsForm def form_valid(self, form): obj = form.save(commit=False) obj.title = ComicSeries.objects.get(id=self.kwargs['pk']) obj.user = self.request.user obj.save() return redirect('comics:series_detail', pk=obj.title.id, slug=obj.title.slug) However, I get this error IntegrityError at /comic/issue/21/add/ NOT NULL constraint failed: comics_comicissue.title_id Could this function in the ComicIssue model be a problem since it is also highlighted on the error page: def save(self, commit=False, *args, **kwargs): self.issue_slug = slugify(self.issue_title) super(ComicIssue, self).save(*args, **kwargs) I am passing the title_id from the url. It is working on other models just not this one. How do I save the foreign key? -
Python: Requests to local server not working
I am using the python library requests to attempt to send a post request to my local server. I have successfully installed and imported requests--I just can't seem to post or get data from my local server. Both the server and my python program are on the same machine, the server is currently Django's development server. What I am trying: domain = 'localhost:8000' user = 'username' password = 'password' data = 'some data to be sent' r = requests.post(domain, data auth=(user,password)) Exception raised: raise InvalidSchema("No connection adapters were found for '%s'" % url) requests.exceptions.InvalidSchema: No connection adapters were found for 'localhost:8000' I have done all the basic things like ensuring that the server was up and running. I have also tried to substitue localhost with 127.0.0.1:8000. -
I configured the media directory, but I can not access the image under the media directory
I configured the media directory, but I can not access the image under the media directory: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/images/datadictionary/zfb.png This is the setting in my settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') My directories in project, you see there is a zfb.png there: My DataDictionary model is bellow: class DataDictionary(models.Model): appmodelfield = models.CharField(max_length=64, null=True) # app_model_field name = models.CharField(max_length=16, help_text="总的名称") content = models.CharField(max_length=32, help_text="内容") image = models.ImageField(upload_to="images/datadictionary/", null=True, help_text="图标") parentlevel = models.CharField(max_length=16, null=True, help_text="父级") You can see my ImageField, and I also pip installed the pillow. And the django rest framework web browser response data is: [ { "id": 5, "appmodelfield": null, "name": "支付类型", "content": "支付宝", "image": "http://127.0.0.1:8000/media/images/datadictionary/zfb.png", "parentlevel": null } ] You see the image field, it is indeed the directory image you see upper. But I can not get the image in my browser. -
Running Django with sudo can't find installed homebrew packages
I have a Django project that I want to run at port 80 with manage.py runserver. In my project I use the Wand library and I have installed freetype and imagemagick using homebrew: brew install freetype imagemagick To run Django at port 80 runserver is required to be run with sudo, but when I run runserver with sudo it doesn't seem to find imagemagick: $ sudo ~/.pyenv/versions/myproject/bin/python manage.py runserver 0.0.0.0:80 Password: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x11068c840> Traceback (most recent call last): File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/wand/api.py", line 180, in <module> libraries = load_library() File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/wand/api.py", line 135, in load_library raise IOError('cannot find library; tried paths: ' + repr(tried_paths)) OSError: cannot find library; tried paths: [] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/Oskar/.pyenv/versions/myproject/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File … -
In an UpdateView with the form_valid over-written, how does django know where to redirect to?
In a generic FormView, the docs say that upon success, it will redirect to the success_url attribute. If I happen to have an UpdateView, and rewrite the form_valid like so: class PreferenceUpdateView(LoginRequiredMixin, UpdateView): form_class = ProfileUpdateForm model = Profile template_name = 'profile.html' def form_valid(self, form): return super(PreferenceUpdateView, self).form_valid(form) returning simply super(PreferenceUpdateView, self).form_valid(form) instead of something like return HttpResponseRedirect(self.get_success_url()) , how does the view know where to redirect to? When should I and when do I not have to specify the redirect? -
save() method in UserChangeForm with custom field?
I have UserChangeForm with custom field (user_role) which use RadioSelect widget. Also in that form I have user_permissions field from User Model. user_permissions field is visible only when user select second checkbox (Moderator) of user_role field. The problem with user_permissions field. It dont save data from this field after select. I think maybe the problem cause of save() method. Do you have any ideas? Whats wrong? forms.py: class UserEditForm(UserChangeForm): user_role = forms.ChoiceField( widget=forms.RadioSelect, choices=((0, _('Admin')), (1, _('Moderator')), (2, _('Simple User'))), ) class Meta: model = User exclude = ('groups',) def save(self, commit=True): form = super(UserEditForm, self).save(commit=False) if "0" in self.cleaned_data['user_role']: form.is_superuser=True for permission in Permission.objects.all(): form.user_permissions.add(permission) elif "1" in self.cleaned_data['user_role']: form.is_staff=True elif "2" in self.cleaned_data['user_role']: form.is_superuser=False form.is_staff=False form.user_permissions.clear() if commit: form.save() return form views.py: def form_valid(self, form): form.save() *** -
Display Django Model as a table
I am using Django 1.11 and I need some advice as to the best method to display a Model as a table in a template using Class Based Views. I'd like to be able to filter and sort the table as well. Any advice is much appreciated! -
Django values_list return list of dict
I tried to return my querset objects as list of unique items using , return qs.values_list(distinct_val, flat=True) if i print above query it gives ['val1','val2', etc] values as a list. but when i suppose to return my output look like this, [ {}, { "name": null, "id": null }, {}, {}, {}, {}, {}, {} ] required output is, ['Fredrick', 'Mohi', ] instead, [ {'name': 'Fredrick'} ] where i made mistake? -
How to get the last 10 item data in django?
I have a Person model, and I want to query out the last 10 items. I can easily query 10 items from front by slice: Person.objects.all()[:10] But I can not query 10 row data backwards. I tried use Person.objects.all()[-10:], but failed. -
how to integrate a django project to a cloud storage like google drive , onedrive etc
I have a running Django application running on webfaction server. I want to integrate my django project with a cloud storage system. How can I Integrate that ? -
Line Breaks in docstring (Django Admin Documentation)
After activating admindocs in Django app, the following comment is added in an object: """ Maintains ABC Object definitions. Each ABC has one or more PQR. See Also :model:`myapp.PQR` and :model:`myapp.XYZ`. """ In Django Admin Documentation, it is rendered as a single line: Maintains ABC Object definitions. Each ABC has one or more PQR. See Also: myapp.PQR and myapp.XYZ. Is there a way to apply line breaks in comments. I'm new to python/ django. -
Django signals How to perform post_save method with multiple senders and multiple instances?
I have two models Profile and Company models.py class Profile(models.Model): user = models.OneToOneField(User) company = models.ForeignKey('company.Company', null=True) phone = models.CharField(max_length=10, blank=True) @receiver(post_save, sender=User) @receiver(post_save, sender=Company) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Profile.objects.create(company=instance) instance.profile.save() As you can see Profile is an user_model extension. I have got that working when sending only one instance. models.py class Company(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=10, blank=True, unique=True) phone = models.CharField(max_length=10, blank=True) Company is created successfully. I want to save the name field in the Company to The Profile when a company is created. views.py def form_valid(self, form): company = form.save(commit=False) user = self.request.user name=form.cleaned_data['name'] phone=form.cleaned_data['phone'] company.name = name company.phone = phone company.user = user company.save() Profile.refresh_from_db() Profile.company = name Profile.save() return super(CompanyCreateView, self).form_valid(form) -
Does an SQL has a Django's "get_FOO_display()" like analog?
For example I have a field status in one of my models: CHOICES = ( ('new', u'New'), ('old', u'Old'), ) status = models.CharField(u'Status', max_length=10, choices=CHOICES, default=0) If I will type: "t1.status" in SQL I will get "new" & "old" instead of "New" & "Old" whereas in django I can type: get_status_display() to get "New" & "Old", how can I do that in SQL ? -
How do i send file through email attachment saved in a FileField in django?
How will i send an attachment stored in a filefield? My views.py looks like this. def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() email_to=form.cleaned_data['email'] subject="Thanks for uploading" message="uploaded file is attached below" try: mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [ email_to]) mail.attach("??????")#How to attach the file here? mail.send() except: return "Attachment error" # Redirect to the document list after POST return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render( request, 'list.html', {'documents': documents, 'form': form} ) I have already setup EMAIL_HOST_USER in settings.py file. My forms.py file look like the. forms.py - # -*- coding: utf-8 -*- from django import forms class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file' ) email=forms.EmailField(label='e-mail',required=True) My models.py file look look this models.py- # -*- coding: utf-8 -*- from django.db import models class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d')