Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply save_model() for inline models in Django
I used TabularInline so that I can combine Store and Image models in the same page. The problem is when saving images, the current user is supposed to be stored as a creator, and it works when saving images directly on Image page. However, if I images on Store page which having Image models as inline models, the creator is empty. I think it's because save_model() only for StoreAdmin executed. In this case, how can I apply save_model() for inline models? class ImageInline(admin.TabularInline): model = Image @admin.register(Store) class StoreAdmin(ImportExportModelAdmin, admin.ModelAdmin): form = StoreForm inlines = [ ImageInline, ] ... def save_model(self, request, obj, form, change): if not change: obj.created_by = request.user else: obj.updated_by = request.user obj.save() -
Django Error Uploading Crop Image Using JS Plugin
I wanted to upload the image in Django. I successfully integrate when is used the simple image field <input type="file" name="profile" class="form-control input-field"> But when I am using JS plugin for cropping the image and uploading then the actual field look like this <input type="file" class="form-control input-field"> <input type="hidden" name="profile_image" value="base64_string_of_crop_image"> So I am getting the validation error for a profile_image field. Anyone who can help me with this? -
Restrict API requests to first-party apps
Apologies if this has already been asked and answered, but after looking around a bunch I haven't found exactly what I am looking for. Suppose the following scenario : I have a REST API at https://api.example.com/ using the Django REST framework. I have a web client at https://example.com/ using React. I have an iOS app using React Native. Third-party apps are allowed to request the API thanks to the django-oauth-toolkit (OAuth2). WHAT I WANT : I want my users to login to their account using my web and iOS apps with their username/password pair, not to be redirected to manually authorize the apps as they have to do for third-party apps. PROBLEM : My first thought was: "Ok, I am able to achieve this using a simple token-based authentication. User requests the API with his username/password pair, then the app gets the token and use it for future requests. The django-rest-knox package seems to fit my expectations.". My second thought was: "Only my own apps should be allowed to request the API using the simple token-based authentication method. CORS headers could possibly restrict API requests to my web client but what about my iOS app? I can't hide secrets in … -
Impossible to publish an article in only one language
I am a beginner in django cms and I have recuperated a project in this language and I find a bug without an answer. The site is multilingual (French, English) and same for the blog. When an article is created in French I find myself having the article in French version in the list of articles on the English version of the site (in the list of English articles there are the French articles). I hope I've been clear, do you have any idea what the problem is? -
Django rest framework : POST on many to many items
I have a TransactionType model and I've implemented a viewset method to create transaction type as shown also below. Currently I can only post single credit_account or debit_account items as shown in this payload: {"name":"Repair and Maintenance","credit_account":16,"debit_account":38} I would to post multiple credit_accounts and debit_accounts such that my payload looks something like this: {"name":"Repair and Maintenance","credit_account":[16,4,5],"debit_account":[38,7]} Which is the efficient way of do this? class TransactionType(models.Model): name = models.CharField(max_length=255) organization = models.IntegerField(null=True, blank=False) credit_account = models.ManyToManyField(Account,related_name='credit_account', verbose_name="Account to Credit") debit_account = models.ManyToManyField(Account,related_name='debit_account',verbose_name="Account to Debit") def __str__(self): return '{}'.format(self.name) viewset method def create(self, request, format=None): name = request.data['name'] try: trans_type_obj = TransactionType.objects.create(name=name, credit_account=Account.objects.get(id=request.data['credit_account' ]), debit_account=Account.objects.get(id=request.data['debit_account' ]), organization=get_auth(request)) serializer = CreateTransactionTypeSerializer(trans_type_obj) except Exception, e: raise e return Response(data=serializer.data, status=status.HTTP_201_CREATED) -
Display name instead of id
I created a form with a choice field call membersid which will display the name in the option. My question is: How to display the name of the object but the value shows the id of the object? forms.py membersid = forms.ModelChoiceField(queryset=Member.objects.values_list('id',flat=True),required=True) I've tried this but I get the value and the display name are id. I've inspected the code, the options list is like: <select name="membersid" class="select form-control" required="" id="id_membersid"> <option value="" selected="">---------</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="21">21</option> <option value="82">82</option> </select> -
django-rest-swagger doesn't work properly after applying proxy_pass with nginx
I'm using django-rest-framework and did config my nginx to reverse proxy all outside connections into a sock file which is created by gunicorn for my djnago rest project. Here is my nginx config: upstream django { server unix://tmp/gunicorn.sock; } server { listen 80; server_name my_test_domain.com; location / { include uwsgi_params; proxy_pass http://django/; } } Nginx is working perfectly and all connections to my_test_domain.com will be passed to gunicorn.sock and everything is ok. Problem The problem is when i see swagger api-docs on browser, swagger will not detect the real domain name in requests that it creates, instead it just show the name of my upstream path which is django. so for example my url for test api will be: http://django/test But i want it to be like http://my_test_domain.com/test Any idea how to solve this! -
Adding in forms into django detail view
So I have a model fie, a forms.py file and a views.py file. The views file returns a detail view of a post, now I wish to add a model form of a comments model into the detail view so I can access it in d template as {{ form }}. I can do this with function-based views but finding it difficult to do with class-based views. Here are the code. #models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') image = models.ImageField(null=False, blank=False, upload_to='post_images') slug = models.SlugField(unique=True) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.CharField(max_length=150) date_commented = models.DateTimeField(auto_now_add=True) comment_by = models.ForeignKey(User, on_delete=models.CASCADE) #forms.py from django import forms from users.models import Profile from Post.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['text', ] #views.py from django.views.generic import ListView, DetailView class PostDetail(DetailView): model = Post template_name = 'Post/blog-detail.html' Hope my question makes sense Thanks. -
Get DRF paginated endpoint from axios
I have a paginated endpoint in my django-rest-framework API. A response to a list GET request looks like this: { "count": 161, "next": "http://localhost:8000/api/v2/bars/?limit=50&offset=50", "previous": null, "results": [ { "id": 1, "name": "Bar1", "url": "http://localhost:8000/api/v2/bars/1/", "budget": 800000, }, // more items... ] } What is the best approach if I want to fetch from axios all that pages until the end and then dump it to my vuex state? My current code only gets the first page. The axios session request: teams() { return session.get('/bars/') } The vuex action: barsRefresh(context) { api.bars().then((data) => context.commit('setBars', data.results)) } -
Show auto-incremental serial number in html table
I have one django project. In the template html page, I use a table to demonstrate data. In the first row of the table, I want to show the ID of "i". But since the i.0 is the batch_id of the model, it does not increment from 1. How could I change the html of this page to show the serial number in first row starting from 1? <table width="100" border="1" style="table-layout:fixed;position:relative;left:75px;" bordercolor="#E0E0E0"> <tr bgcolor="#F0F0F0"> <th width="55px" style="word-wrap:break-word;"><div class="panel-heading">ID</div></th> <th width="130px" style="word-wrap:break-word;"><div class="panel-heading">Search Content</div></th> </tr> <tr> {% for i in datas %} <td style="word-wrap:break-word;"><div class="panel-body"><small>{{ i.0 }}</small></div></td> <td style="word-wrap:break-word;color: #0066CC"><div class="panel-body"><strong><small>{{ i.2 }}</small></strong></div></td> {% endfor %} </tr> </table> -
(1062, "Duplicate entry '2' for key 'user_id'")
I am trying to update a profile by cropping the image, after cropping the image it is giving me a base64 string which i have to covert it into the image and store on the server as well as its url in the database. I am getting the image on the server but unable to store its url in the database. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.FileField(default='default.jpg', upload_to='profile_pics') def __str__(self): return self.user.username def save(self, *args, **kwargs): #super(Profile, self).save(*args, **kwargs) super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py #profile view @login_required def profile(request): #if any changes POST data if request.method == 'POST': image_data = request.POST['image'] format12,img = image_data.split(';base64,') ext = format12.split('/')[-1] imageObj = ContentFile(base64.b64decode(img+"==")) file_name = "myphoto."+ext #print(file_name) #Profile.image = data #Profile.save(file_name, data, save=True) #Profile.save() profile = Profile() profile.user_id = request.user.id #profile.image= imageObj u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile) #check if both forms are valid if u_form.is_valid() and p_form.is_valid(): u_form.save() # if yes Save profile.image.save(file_name, imageObj) profile.save() #p_form.save() # if yes save messages.success(request, format('Your Profile has been updated.')) return redirect('profile') else: u_form = UserUpdateForm(instance=request.user)#instance … -
Upgrade Django project to Python3 - migrations fail
I have a Django project which has been developed with Python2.7, it is currently using Django version 1.10. I am now in the process of upgrading - first to Python3, and then afterwards I will do the Django upgrade. When I make Python3 virtual environment and run the tests: venv bash% ./manage.py tests I get a massive traceback: Traceback (most recent call last): File "./manage.py", line 9, in <module> execute_from_command_line( sys.argv ) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 72, in handle failures = test_runner.run_tests(test_labels) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/test/runner.py", line 549, in run_tests old_config = self.setup_databases() File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/test/runner.py", line 499, in setup_databases self.parallel, **kwargs File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/test/runner.py", line 743, in setup_databases serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True), File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 70, in create_test_db run_syncdb=True, File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 202, in handle targets, plan, fake=fake, fake_initial=fake_initial File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 97, in migrate state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 132, in … -
Create Model field based on existing models
I am currently working to implement review app in Django. In models.py of this review app: from salon.models import salon from services.models import Service from packages.models import Packages MODEL_OBJECTS = ( ('salon':salon), ('service':service), ('package':package), ) class Reviews(models.MODEL): user = models.ForeignKey(User, verbose_name=_("user"), on_delete=models.CASCADE) comment = models.TextField(_("User Comment")) rating = models.IntegerRangeField(min_value=1, max_value=5, blank=True) rate_object = models.CharField(_("Model Choice") choices=MODEL_OBJECTS,default='salon') rate_object_id = models.IntegerField(_("rate_object_id")) i want rate_object to contain model for which the rating is being done and rate_object_id to contain the instance id of the model selected in rate_object. I am not able to think forward on implementing this. any help will be helpful, Thanks -
Typescript, --outFile argument and "Cannot find module"
I'm trying to use vuejs/typescript with django and django-compressor. I have this files /project-root/tsconfig.json /project-root/packages.json /project-root/static/main.ts File content tsconfig.json { "compilerOptions": { "target": "es5", "strict": true, "module": "es2015", "moduleResolution": "node" } } packages.json { "name": "project", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "vue": "^2.5.21", "vue-class-component": "^6.3.2", "vue-property-decorator": "^7.2.0" } } main.ts import Vue from 'vue' export const app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }); So when I run command tsc --outFile static/main.js --module amd static/main.ts I got the following error static/main.ts:1:17 - error TS2307: Cannot find module 'vue'.. How to properly setup typescript and use it with --outFile argument? -
Nginx Gunicorn Django -- upstream prematurely closed connection Error
I am pretty new to NGINX, GUNICORN, DJANGO setup. I am using supervisor between nginx, gunicorn. Without NGINX, setup works well with supervisor and gunicorn and I can see the result through my server IP. But when i am using nginx to serve the requests, the error "upstream prematurely closed connection while reading response header from upstream" occurs. please anyone help me in this? Supervisor command I am using: sudo /path/to/gunicorn/gunicorn -k gevent --workers 4 --bind unix:/tmp/gunicorn.sock --chdir /path/to/application wsgi:application --timeout 120 -
Reset password of custom users model on django rest auth?
I am using custom user in django rest framework for authentications and now I need to reset password but I am not able to do that. url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/password/reset/', include('rest_auth.urls')), url(r'^rest-auth/password/reset/confirm/<uidb64>/<token>/', include('rest_auth.urls')), I am using these url and this is working for default django user but not woking for custom users. So, How can I reset the password of my custom users on django rest auth. -
Getting task timeout error when accessing the django application which is deployed on AWS
I have my django application deployed on AWS. It is working fine as of now but when i tried to hit an api which is deployed on ec2 instance it is showing task time out error.is there any way to overcome it. [1556766665330] [DEBUG] 2018-12-14T05:46:25.330Z 98072431-ff63-11e8-97db- 2d7bd216d81f Starting new HTTP connection (1): 1.2.3.4:3000 [1544799995279] 2018-12-14T05:46:55.279Z 98072431-ff63-11e8-97db-2d7bd216d81f Task timed out after 30.03 seconds my django application is deployed on aws through zappa -
{ % extends parent _ template|default:"base.html" % } vs {% extends "base.html" %} in Django?
What is the difference between { % extends parent _ template|default:"base.html" % } vs {% extends "base.html" %} in template inheritance in django ? I've seen both being used. -
How to read a file in my local storage as in memory and attach it into email?
This snippet is to generate an xlsx file and then attach that file into an email Note: I'm not saving any file, it is in memory. import io a = io.BytesIO() from django.core.mail import EmailMessage import xlsxwriter workbook = xlsxwriter.Workbook(a, {'in_memory': True}) worksheet_s = workbook.add_worksheet('abcd') worksheet_s.write(0, 0, 'Hello, world!') workbook.close() a.seek(0) email = EmailMessage('Subject', 'Body', 'sentby@mailinator.com', ['sentto@mailinator.com']) email.attach('file.xlsx', a.getvalue()) email.send() Similarly to this, I want to attach a file in my storage to email but first want to open it in in memory. As I am Trying to write a generic code to send Email from one place whether it has attachments(self-generated file or file in storage) or not. Thanks in advance. -
How to deploy Django under subdirectory with correct mod_rewrite?
To install Django app under root folder is much easier but I have a project that I have to set up an app under a subfolder although I know most of the experienced developer wouldn't do it this way. I have a website hosted with NameCheap, http://www.sctongye.com , a WordPress blog is installed under the root folder, now I'm trying to set up a Django app under a subfolder thru cPanel http://sctongye.com/thoughts/ with settings.py shown below STATIC_URL = 'thoughts/static/' # on server STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) Everything seems to be working fine, but when I tried to login thru admin http://sctongye.com/thoughts/admin/ or http://sctongye.com/thoughts/xadmin/ (another admin I installed) the path of all the static files are wrong, as shown below: GET http://sctongye.com/thoughts/xadmin/thoughts/static/thoughts/static/xadmin/vendor/bootstrap/css/bootstrap.css 404 (Not Found) GET http://sctongye.com/thoughts/xadmin/thoughts/static/xadmin/css/themes/bootstrap-xadmin.css 404 (Not Found) GET http://sctongye.com/thoughts/xadmin/thoughts/static/thoughts/static/xadmin/css/xadmin.main.css 404 (Not Found) As you can see, tons of duplicated static name in the path link. In order to have the subfolder Django app work, I'll have to set up a .htaccess file right under the subfolder # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/username/thoughts" PassengerBaseURI "/thoughts" PassengerPython "/home/username/virtualenv/thoughts/3.6/bin/python3.6" RewriteCond %{REQUEST_URI} !^/thoughts (<== I had to add this line to make it work, but I … -
Big O Notation: Using multiple forloops within Django template VS multiple queries using a filter in views.py
This is a specific question based on an attempt to increase performance speeds when querying data. So I was trying to figure out within a Django template itself, how to break a conditional on the first attempt. It seems that it is not possible, and the suggestions were all to use the views.py for the logic instead. This led me to try filtering based on a condition being met. In my example, I have two scenarios that I'm comparing. (1) In the first one, I have one query inside my views.py to get all items. Naturally, Item is a schema I have in my models. Anyway, inside the template I want to render, I have the context being passed and have 11 separate forloops all iterating over the same all_items loop. Then based on the condition (ie item.category), the appropriate html is rendered. Again, what I wanted to do was have 1 loop, and then based on the condition, rendering to the appropriate places. Unfortunately, I'm not able to break the loop in the template after the condition to not over-render html I don't want on each successive iteration. So this led me the next scenario: (2) In my views … -
how to send a form to html in django
I am trying to send a form to html using django. this is the form from django import forms class contactForm(forms.Form): name = forms.CharField(required=False, max_length=100,help_text='100 characters max.') email = forms.EmailField(required=True) comment = forms.CharField(required=True, widget=forms.Textarea) The view file is from django.shortcuts import render from .forms import contactForm # Create your views here. def contact(request): form = contactForm(request.POST or None) if form.is_valid(): print (request.POST) context = locals() template = 'contact.html' return render(request, template, context) and the html file which is named correctly is, {% extends 'base.html' %} {% block content %} <h1> Contact </h1> <form method='POST' action=''> {% csrf_token %} {{ form.as_p }} <input type='submit' value='submit form' class='btn btn-default' /> </form> {% endblock %} When you visit the page the only thing that shows up is the h1 tag how do i fix this? -
Django DateField TypeError expected string or bytes-like object
I'm a Django newbie, I'm getting an error when submitting and attempting to save the updated value selected in one of the dropdown lists. I think it's related to the date being passed to the form, but I'm unsure how to fix this. The trace back error : match = date_re.match(value) TypeError: expected string or bytes-like object My models.py from django.db import models class Person(models.Model): person_name = models.CharField(max_length=50, unique=True) person_dept = models.ForeignKey('Department', default='1', on_delete=models.CASCADE) number = models.CharField(max_length=10, unique=True) email = models.EmailField(max_length = 100, unique=True) class Meta(): db_table = 'person' def save(self, *args, **kwargs): for field_name in ['person_name']: val = getattr(self, field_name, False) if (val): setattr(self, field_name, val.title()) super(Person, self).save(*args, **kwargs) def __str__ (self): return self.person_name class Department(models.Model): dept_desc = models.CharField(max_length=100, unique=True) class Meta(): db_table = 'dept' def __str__ (self): return self.dept_desc class Roster(models.Model): roster_date = models.DateField() oss_person = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='+', limit_choices_to={'person_dept': 1},) nw_person = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='+', limit_choices_to={'person_dept': 2},) class Meta(): db_table = 'roster' def __str__(self): return str(self.roster_date) My forms.py from datetime import datetime, timedelta from django import forms from django.core import validators from roster.models import Roster, Person, Department class UpdateRosterForm(forms.ModelForm): class Meta(): model = Roster fields = '__all__' labels = { "roster_date":"Start On Call Date", "oss_person":"Servers", "nw_person":"Networks", } … -
django how to pass bookinstance.id for a particular book to function-based view
I have a django library application, wherein the customer can view a book from a book list(and is redirected to book_detail.html page), and if the book is available, can borrow the book. book_detail.html - borrow book button {% for copy in book.bookinstance_set.all %} {% if copy.status == 'a' %} <form method="POST" action ="{% url 'borrow_book' book_instance.id%}" enctype="multipart/form-data"> # none of these alternatives work # OR 'borrow_book' book_instance.id # OR 'borrow_book' book_instance.pk # OR 'borrow_book' book_instance.book_id # OR 'borrow_book' book_instance.book.id {% csrf_token %} <button type="submit" class="btn btn-success">Borrow the book</button> </form> {% endif %} {% endfor %} This is the urls.py routing within the app project path('book/<uuid:pk>/borrow/', views.borrow_book, name='borrow_book'), And the function borrow_book is invoked: def borrow_book(request, pk): book_instance = get_object_or_404(BookInstance, pk=pk) if request.method == 'POST': if request.user.is_authenticated: book_instance.borrower = request.user book_instance.due_back = datetime.date.today() + datetime.timedelta(weeks=3) book_instance.status = STATUS_ON_LOAN book_instance.save() return HttpResponseRedirect(reverse('dashboard_customer')) context = { 'book_instance': book_instance, } return render(request, 'catalog/book_detail.html', context) When user clicks on Borrow book button, I need to create an instance of the book hence I am using the book_instance model. Here is the relation between the Book and BookInstance model: class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique … -
Check/verify if in Django template, there are real numbers in decimal places, and if zeros, round off
I couldn't seem to find a specific answer for this question. So, my question differs based on two different scenarios: (1) In my Django template, can I use some kind of filter to round real numbers in the decimal position, to only 2 digits, but still round any zeros to the nearest whole number/integer? (ie $1.25 and 1.00 would look like $1.25 and $1 respectively) ** Unfortunately, |floatformat:2 includes the zeros (2) If the above is not possible, is there some kind of conditional where I can check beforehand in the Django template if there are real numbers in the decimal position instead of zeros, and perform some kind of logic as a result? Thanks in advance!