Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Custom Form save bulk creation using CSV
I am trying to implement a CSV Import in Django Admin and save bulk data corresponding to the CSV file's rows. I have a model Employee with a OneToOneField to Django's Auth model. I have written a custom Form that accepts a csv file. However, when I call the super().save() method, I get an Integrity Error. My Model class is: class Employee(models.Model): user = models.OneToOneField(User, primary_key=True) company = models.ForeignKey(Companies) department = models.ForeignKey(Departments) mobile = models.CharField(max_length=16, default="0", blank=True) gender = models.CharField(max_length=1, default="m", choices=GENDERS) image = models.ImageField(upload_to=getImageUploadPath, null=True, blank=True) designation = models.CharField(max_length=64) is_hod = models.BooleanField(default=False) is_director = models.BooleanField(default=False) This is my Admin class: class EmployeeAdmin(admin.ModelAdmin): list_display = ('user', 'company', 'department', 'designation', 'is_hod', 'is_director') search_fields = ['user__email', 'user__first_name', 'user__last_name'] form = EmployeeForm This is my Form class: class EmployeeForm(forms.ModelForm): company = forms.ModelChoiceField(queryset=Companies.objects.all()) file_to_import = forms.FileField() class Meta: model = Employee fields = ("company", "file_to_import") def save(self, commit=True, *args, **kwargs): try: company = self.cleaned_data['company'] records = csv.reader(self.cleaned_data['file_to_import']) for line in records: # Get CSV Data. # Create new employee. employee = CreateEmployee(...) super(EmployeeForm, self).save(*args, **kwargs) except Exception as e: traceback.print_exc() raise forms.ValidationError('Something went wrong.') I am getting an exception in the except block with the error: IntegrityError: (1048, "Column 'user_id' cannot be null") In … -
Ubuntu Server 16.1 Django Apache Setup
I am having a hell of a time getting a project to come through on an apache web site. I can see the project fine if I start the project on port 8000, but if I let apache do the work I get nothing. All help is greatly appreciated! I referenced this for instructions... https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 Here is my error log... [Sat Oct 08 22:42:17.962310 2016] [wsgi:error] [pid 13524] mod_wsgi (pid=13524): Call to 'site.addsitedir()' failed for '(null)', stopping. [Sat Oct 08 22:42:17.962340 2016] [wsgi:error] [pid 13524] mod_wsgi (pid=13524): Call to 'site.addsitedir()' failed for '/home/addohm/projects/rtservice/projectenv/lib/python2.$ [Sat Oct 08 22:42:18.225731 2016] [wsgi:error] [pid 13524] [remote 192.168.2.249:6662] mod_wsgi (pid=13524): Target WSGI script '/home/addohm/projects/rtservice/servicesite/ser$ [Sat Oct 08 22:42:18.225780 2016] [wsgi:error] [pid 13524] [remote 192.168.2.249:6662] mod_wsgi (pid=13524): Exception occurred processing WSGI script '/home/addohm/projects/rt$ [Sat Oct 08 22:42:18.226283 2016] [wsgi:error] [pid 13524] [remote 192.168.2.249:6662] Traceback (most recent call last): [Sat Oct 08 22:42:18.226325 2016] [wsgi:error] [pid 13524] [remote 192.168.2.249:6662] File "/home/addohm/projects/rtservice/servicesite/servicesite/wsgi.py", line 16, in <mo$ [Sat Oct 08 22:42:18.226329 2016] [wsgi:error] [pid 13524] [remote 192.168.2.249:6662] application = get_wsgi_application() [Sat Oct 08 22:42:18.226335 2016] [wsgi:error] [pid 13524] [remote 192.168.2.249:6662] File "/usr/lib/python3/dist-packages/django/core/wsgi.py", line 14, in get_wsgi_applica$ [Sat Oct 08 22:42:18.226338 2016] [wsgi:error] [pid 13524] [remote 192.168.2.249:6662] django.setup() [Sat Oct … -
How to write a table without database in HTML in Django
I just want to write a table in HTML in Django, where the data is not from Database. It seems django-tables2 is a good package that I can use in Django. However, my data is not from Database, so maybe it's not necessary to use Django model. Here comes my code of view.py and HTML page: def device_manager_submit(request): '''Switch manager page''' ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}] return HttpResponse(ret) #return data to HTML I can use for loop in HTML to display this data but I'm not clearly about how to show them: <tbody> {% for item in xx %} //I'm not sure <tr> <td>111</td> //how to display? </tr> {% endfor %} Does anyone has any example that I can follow to display the data from view.py in HTML page -
Best way of giving user's the ability to create their own datastores?
I want the user's of my site to be able to upload information into a database. I know that Django doesn't really allow me to let the user's have their own dynamically created tables. So I'm wondering what is the most efficient way of handling this. For instance if all user's want to save mailing lists containing names, emails, numbers etc Would I just put all of these into one giant table with a column for the user ID or is there a smarter way to do this? -
Custom Django admin command having extra new line characters
I am trying to write custom Django Admin command. But while using print statement with the handle() function of it, I am getting extra new line character. Even though I am using print with end='' but still the new line character. Does any one know the reason for this? The code I have written is: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print('Text 1', end='') print('Text 2', end='') I was expecting the output to be: Text 1Text 2 but what I am getting is: Text 1 Text 2 Weird. Isn't it? -
AttributeError in view/form
My functions working, but i have debug-error 'int' object has no attribute 'get' my view @csrf_exempt def t1(request): q_p_id = request.POST.get('id') return 0 my form <form action="/url/t1" method="post"> {% csrf_token %} <input type="text" name="id" value="0">Id<Br> <input class="button" type="submit" value="Go"> </form> -
Django cleanly passing parameters through URL
Here's the context: I'm going for a single-view web app, lets call this view index in my views.py file. In order to handle POST calls, I have a bunch of methods in views.py like getWords. When the user submits the HTML form, it will call getWords, which should process the words, and then pass the words to index through HttpResponseRedirect('/index?words=aardvark,apple,anarchy'). This way, I can access the words in index by calling request.GET.get(words). The problem is that obviously now the URL contains index?words=... and it doesn't look that good. Is there a better way to give index access to the words without cluttering the URL, while still using getWords to receive the POST request? -
how to set raw_id_fields param into a views.py function using a form class
I have a model I'll call Item, an admin class I'll call ItemAdmin and an admin form I'll call ItemAdminForm So far I'm adding elements by using ItemAdminForm class associated to ItemAdmin and it perfectly works class ItemAdmin(admin.ModelAdmin): list_display = ('id', 'label', 'city') ordering = ('label',) raw_id_fields = ('city',) form = ItemFormAdmin admin.site.register(Item, ItemAdmin) (for the record, city is a simple ForeignKey model) What I want to do is create into views.py a custom add function with its template that looks more or less like this (it's in views.py) def item_add(request): form = ItemFormAdmin(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } return render(request, 'item_add.html', context) But I don't know how and where to set raw id fields (ans similar options) before calling ItemsFormAdmin , since city should be a raw id field raw_id_fields = ('city',) Thanx in advance for your help -
Django - Get Id of the ForeignKey Object in List View
I have two models linked by Foreign Key. RunConfig RunConfigStatus class RunConfig(models.Model): config_name = models.CharField(max_length=100) class RunConfigStatus(models.Model): config_run_name = models.CharField(max_length=200,unique=True ) config_name = models.ForeignKey('RunConfig',on_delete=models.CASCADE,) Overall_Status = models.CharField(max_length=50,blank=True,null=True) I am currently using a CBV list view for RunConfigStatus. I would like to href/link the foreign key object to its detail view. is this possible? class RunConfigStatusListView(LoginRequiredMixin,ListView): model = RunConfigStatus context_object_name = 'run_config_status_list' On my Template: {% for run in run_config_status_list %} <td><a href={% url 'runconfigstatus-detail' pk=run.id %}>{{run.config_run_name}}</a></td> <td>{{run.config_name}}</td> <td>{{run.Overall_Status}}</td> I want that config_name should have a href which will redirect to RunConfig detail view <td><a href={% url 'runconfig-detail' pk=**NOT SURE** %}>{{run.config_name}}</a></td> Screen Shot of my current output, I would like to click on ConfigName values and it should redirect to its details view. (In this case Test, MyFirstTest on all entries) -
API Authorization from JavaScript SDK
I have an API built using Django Rest Framework and an SDK that many clients use in order to integrate with the API services. There are no user notions, as this service is intended to be used by the websites that have integrated the SDK inside their source code. I am trying to find a way to make the API communication between the servers and the SDK clients more secure. When the SDK is used from the website, it makes the calls on the API using an "application_id" string. There's no point in using api_keys or tokens, as the SDK code is in plain sight from the website's source. Do you have any recommendations on this one? -
Can't run a simple application on Django 1.8.7
I'm a C programmer who's now working with Python + Django.. So, i'm dealing with this: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f675b847ea0> Traceback (most recent call last): File "/home/zydeco/virtualenvs/wttd/lib/python3.5/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/home/zydeco/virtualenvs/wttd/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/home/zydeco/virtualenvs/wttd/lib/python3.5/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/home/zydeco/virtualenvs/wttd/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/zydeco/virtualenvs/wttd/lib/python3.5/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/home/zydeco/virtualenvs/wttd/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/zydeco/virtualenvs/wttd/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/zydeco/virtualenvs/wttd/lib/python3.5/site-packages/django/apps/config.py", line 112, in create mod = import_module(mod_path) File "/home/zydeco/virtualenvs/wttd/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked So far, i barely coded the project, here is what i just added this line to urls.py: url(r'^$', 'eventex.core.view.home'), and this one to the generic "views.py" def home(request): return render(request,'index.html') I also created a dir called "Template" with a HTML called "index.html" inside For more information, this is the freeze of my env: (wttd) zydeco@zydeco-pc:~/projetos/wttd/eventex$ pip freeze Django==1.8.7 I'm using Ubuntu 16.04 LTS Thanks in advance! -
Django admin Getting 404 code on change_form.js
I'm getting an error of not found file (status 404) for these JS files: /static/admin/js/change_form.js 404 (Not Found) /static/admin/js/prepopulate_init.js 404 (Not Found) I already did the python manage.py collectstatic and everythings seems ok but these 404 errors. I'm currently using Django 1.9.8 version. I Just looked the source code and didn't found these files on js folder. I did found the files on the master branch. So, I guess the files should be able only for developers. PS: I'm using a django-admin-bootstrap for a different template layout, don't know if it's relevant. Some one already overcame this situation? Thanks! -
Is Django better than PHP for web development? [on hold]
I learned Python programming language. Now I am interested in back-end work. I am learning Python web development with Django framework. Is it worth learning? Is PHP better than Python? -
Is there any video chat plugin for django website? [on hold]
I want to integrate video group chat (more like a webinar) in my django website,so is there any stable video chat plugin available to integrate in my website? -
Django get_or_create only if form constraints are met
I have a form that asks for a song's Artist, Title and Mix. Artist and Title are required fields but Mix is not. The form should only save if Artist, Title and Mix does not exists. If the form has either empty Artist or Title field it should show "This field is required" on submit. The issue I'm having is if the Title field is empty but Artist is populated, it'll still create the Artist object with get_or_create (See ###forms.py below). How do I only create Artist object if the form is valid? ###########models.py class Artist (models.Model): name = models.CharField(max_length=100) class Track (models.Model): artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist") user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Submitted by", default=1) title = models.CharField(max_length=100, verbose_name="Title") mix = models.CharField(max_length=100, blank=True, verbose_name="Mix") ###########views.py class TrackCreateView(SuccessMessageMixin, AjaxCreateView): form_class = ProfileForm success_message = "Thank you for submitting track: %(artist)s - %(title)s - %(mix)s" def get_initial(self): self.initial.update({ 'user': self.request.user }) return self.initial def get_success_message(self, cleaned_data): return self.success_message % dict(cleaned_data, artist=self.object.artist, title=self.object.title, ) ###########forms.py class ProfileForm(forms.ModelForm): class Meta: model = Track fields = [ "artist", "title", "mix", ] artist = forms.CharField(widget=forms.TextInput(attrs={'maxlength': '100',})) def __init__(self, *args, **kwargs): self.user = kwargs['initial']['user'] super(ProfileForm, self).__init__(*args, **kwargs) # Set layout for fields. my_field_text= … -
Using GET and POST to add data to a database in Django
I am working on a project that will have a raspberry PI collect data from a set of sensors and then send the data to a django server. I need the server to then take that data and add it to a database and perform ARIMA time series forecasting on the updated dataset every x seconds after a number of new entries are added. Can I use POST in the raspberry PI program to send the data to that url and then use GET in a django view to add the incoming data into a database? Sorry if this is a dumb question, I am new to django and web-based python. -
Cannot access a file from worker, but works in the view - [Errno 2] No such file or directory
I have followed the tutorial on https://devcenter.heroku.com/articles/python-rq Let's say I have a function that converts PDF Files to JPG and stores them in the app's tmp/file/ and that it later uploads it to S3. However, since the request timeout is 30s on heroku, I am not able to put this in a View, so I decided to use a background worker to execute the task. So I moved the code to the task but the worker is not able to find the right path. [Errno 2] No such file or directory. I tried printing without luck, but I'm able to print in the function. The function I tried calling that gives an empty string in the task but gives the right value in the view issorted(os.listdir('tmp/file/') I searched around and thought that maybe PYTHONPATH variable could be wrong, but everything works via the manage.py My worker.py looks like this. import os import redis import sys from rq import Worker, Queue, Connection listen = ['high', 'default', 'low'] os.environ['DJANGO_SETTINGS_MODULE'] = 'cinnamon_rest.settings' redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work() And my manage.py looks like this. #!/usr/bin/env python import os import sys if … -
Django - Access Parent Model field when creating many-to-one model
Imagine you have a model which is a book/web comic/cartoon for online reading: class Book(models.Model): name = models.CharField(max_length=255, default="") image = models.ImageField(upload_to='uploads/ + name + /coverImage/') ... Then a model for each Chapter: class Chapter(models.Model): book= models.ForeignKey('Book', on_delete=models.CASCADE) name = models.CharField(max_length=255, default="") date_released = models.DateField(auto_now_add=True) date_changed = models.DateTimeField(auto_now=True) views = models.IntegerField(default=0) Then you have the child model which will contain the images for each page: class ChapterImages(models.Model): chapter = models.ForeignKey('Chapter', on_delete=models.CASCADE) image = models.ImageField(upload_to='uploads/' + chapter.book.name + '/chapter') The code in the last field of the ChapterImages field image is wrong. And I want to know if it's even possible to get the name of the parent while creating the child? This is so I can upload it easily to the same folder as the book itself in a sub-folder for that chapter. As you can see I typed in chapter.book.name which wont work(right?). Is there a good way to change this so it can work fine without having to do it manually trough the view? -
Converting mark down content to HTML in a Django-React app
I want to store blog content in my database, which I could then display in an HTML page, ideally by sending the content over an AJAX call. After looking through the web I've read a few people suggesting storing the blog post as markdown which makes the most sense since it contains supports headers, paragraphs and code formatting, and mark down would be the easiest way to read/write the post. However I'm not sure how to convert the markdown to an HTML page. I'm also not sure if I want to do that conversion client side (React frontend) or server side (Django Rest Framework backend). What are some tools or methods to get this done given my stack? -
How can i amazon purchase programmatically?
I'd like to purchase something on amazon programmatically. Is it possible? If so, could you tell me the way..? When I use selenium web driver, I couldn't sign in. Because of image authentication was appeared. I tried chrome and PhantomJS. -
How to get back inlines add\change buttons in case, when custom queryset is provided to ModelChoiceField?
When I add to inline form which has custom queryset in UserModelChoiceField, add\change buttons are disappeared. How to get them back? I did as shown here, ie: class UserModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() class UserForm(forms.ModelForm): user = UserModelChoiceField(queryset=UserProfile.objects.filter(*some_kv*)) class UserProfileInlineAdmin(admin.TabularInline): model = UserProfile form = UserForm -
Django Rest Framework JWT with multiple custom models
I'm trying to create a login with django rest framework jwt. I have two models in my settings file: one for users (AUTH_USER_MODEL) and the second for clients(AUTH_CLIENT_MODEL). I was able to create a login using the AUTH_USER_MODEL. However, when i try to login with client credentials i get the following error: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "non_field_errors": [ "Unable to login with provided credentials." ] } Can you please help figure out how can i login with django rest jwt using multiple auth models, or may be how to override payload handler to include both models. Thanks -
Invalid block tag : 'endblock'. Did you forget to register or load this tag?
l get stuck in this error. l'm fresh user of Django and l m learning it by following steps on Youtube channel. l did everything same but l got this block tag error. here is layout1 html content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{ % block title %}{% endblock %}</title> </head> <body> { % block content %} {% endblock %} </body> </html> index html content: {% extends "layout/layout1.html"%} {% block title %}The Video page{% endblock %} { % block content %} <h1>This is a html</h1> <p>This is a p tag</p> <a href="http://www.noobmovies.com">Click me!</a> <img src="https://upload.wikimedia.org/wikipedia/en/7/72/Anthony_Raneri.jpg"/> {% endblock % } views.py content: from django.template.response import TemplateResponse # Create your views here. def video(request): return TemplateResponse (request,"video/index.html",{}) how can l handle this problem? as l did double-check to make sure everything is typed same like Youtube channel and normally ,l did not get where l did a mistake. -
DRF - relationships of different models
I have several models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) birthday = models.DateField(auto_now=False, auto_now_add=False) weight = models.IntegerField(default=0) heigth = models.IntegerField(default=0) class ProfileFields(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) class ProfilePic(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg') class Pics user = models.ForeignKey(User, on_delete=models.CASCADE) pic = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg') Is it possbile to create serializer, that will show user with all another models, that attached to this particular user ? So I dont have to crease requests for each model separately but retrieve everything user related in one request ? -
PostgreSQL on pythonanywhere.com
Please i used the django-girls django tutorial created my first django project but used postgreSQL database instead and i pushed it to my repository on github. I tried to host it on pythonanywhere.com but i got an error. I researched on the error and found out that i have to upgrade to a paid account to use postgreSQL. I deleted the repository from github and even started the django project again this time using the default SQLlite3 and then i pushed it to github. When i tried to push it to pythonanywhere.com, i got the same postgreSQL error. Please i want to know how i can change the database back to SQLlite3 because pythonanywhere.com is still recognising the postgreSQL. I hope my question is understood. Thanks