Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Referencing user object inside model method in Django
I have the following in my model: class Genre(models.Model): name = models.CharField(max_length=100) def my_latest_song(self): song = Song.objects.filter(genre_id=self.id, author_id=XXXXXXXXX).order_by('date') return song[0]; class Song(models.Model): name = models.CharField(max_length=100) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True) date = models.DateField() author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) So with the my_latest_song method I want to obtain for each genre what the latest song is for the user currently logged in. Note: I am already making sure that users MUST be logged in to see this, do not worry about this additional validation. The question is: how can I pass the user id of the user that is currently logged in onto this model method? Where the XXXXXXXXXX is listed I have tried: author_id=request.user.id author_id=user.id author=request.user author=user And many similar options. But I'm new to Django and just not sure about how to properly reference this. Nothing is working yet. -
Get same object in multi Querysets in Python Django
Hope you guys help me to Get same object in multi Querysets in Python. I use Django Framework I assumed that I have 2 Queryset: qrs1 = [1, 2, 3, 5, 9] and qrs2 = [1, 4, 2, 5] I want to print result with this queryset: [1, 2, 5] -
Error on git push : ! [remote rejected] master -> master (pre-receive hook declined) in heroku
I am trying to deploy my django app on heroku but i am getting this error : remote: Error: could not determine PostgreSQL version from '10.1' remote: remote: ---------------------------------------- remote: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-r9b1_s/psycopg2/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to bookmark. remote: To https://git.heroku.com/bookmark.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/bookmark.git' My requirements.txt : Django==1.11.6 gunicorn==19.7.1 Pillow==3.1.2 Markdown==2.6.9 whitenoise==3.3.1 psycopg2==2.6.1 Can someone guide me on this.Thanks -
how to create New user form in django Only those who have filled the my form, can enter my website
Hello i am new with Django an i want to create a New User Form an Only those who have filled the my form, can enter my website! My form required form fields First Name Last Nanme EmailId Mobile No Broker Address Field 1 Address Field 2 Address Field 3 City State PIN AdhaarCard PAN No Bank Account No Bank Name Branch -
Adding a Wiki Field in Django
I'm trying to add a Wiki Field to Django. I however have no experience with how to design it. I need to have a single Wiki Field for a single Product I only want users with certain reputation to directly edit the Wiki and others will be placed in moderation queue much like SO. My main concern is multiple items in moderation queue How do I store and handle and multiple editions while in moderation queue How do I setup a method for moderators to get old revisions if some one messes up? How do SO and SE handle multiple items in moderation queue? This is my current code. class ProductWiki(models.Model): product = models.OneToOneField('Product') approved_revision = models.OneToOneField('productWikiRevision') class ProdcutWikiRevision(models.Model): content = models.TextField() wiki = models.ForeignKey(ProductWiki) revision = models.PositiveIntegerField() author = models.ForeignKey('auth.User') summary = models.CharField(max_length=300, blank=True) added_on = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False, db_index=True) approved_by = models.ForeignKey(User, null=True, blank=True) approved_at = models.DateTimeField(null=True, blank=True) ip_address = models.GenericIPAddressField(max_length=45, default='0.0.0.0', db_index=True) user_agent = models.TextField() -
Django IntegrityError of this overriding save method
My Model class Worksite(models.Model): firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True, verbose_name="Şantiye Adı") My save method def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_unique_slug() os.mkdir(BASE_DIR+'/file/'+slugify(str(self.firm).replace('ı','i'))+'/'+self.slug) return super(Worksite, self).save(self, *args, **kwargs) My UpdateView def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_unique_slug() os.mkdir(BASE_DIR+'/file/'+slugify(str(self.firm).replace('ı','i'))+'/'+self.slug) return super(Worksite, self).save(self, *args, **kwargs) IntegrityError : (1062, "Duplicate entry '1' for key 'PRIMARY'") If the save method is deleted, the update process is successful. but this time the folder can not be created. so save method is necessary. but this error is annoying. where is the mistakes? Help pls. -
My serializer is returning index instead of the actual fields
I am new to Django and I have been trying to serialize my model object called MoviesCategories. class MoviesCategories(models.Model): name = models.CharField(max_length=120, null=False) def __str__(self): return self.name There is also a Movie model that is as follows class Movie(models.Model): name = models.CharField(max_length=120, null=False) thumbnail = models.CharField(max_length=120, null=False) source_url = models.CharField(max_length=500, null=False) duration = models.TimeField(default=timedelta(hours=2)) added_on = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(MoviesCategories, related_name="movies", on_delete=models.DO_NOTHING) def __str__(self): return self.name class Meta: ordering = ('added_on',) My MoviesCategoriesSerializer looks like this class MoviesCategoriesSerializer(serializers.ModelSerializer): class Meta: model = MoviesCategories fields = ('name', 'movies') What I am getting from this serializer when I do MoviesCategoriesSerializer(MoviesCategories.objects.first()).data is {'movies': [1, 2], 'name': 'Animations'} I expect to get the fields of the movies too. I have created a MovieSerializer class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('name', 'thumbnail', 'source_url', 'duration') But I have no Idea on how to link the two such that MoviesCategoriesSerializer(MoviesCategories.objects.first()).data returns me all movies in the first category -
Model not inheriting User data
So I am working with built-in Django login forms and I want my blogger model to inherit all the users created using the form but it is not showing up in the blogger model. Models class Blogger(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) follows = models.ManyToManyField('self', related_name='following', symmetrical=False) def __str__(self): return self.user.username View for the sign up def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/blog') else: form = SignUpForm() return render(request, 'winterblog/signup.html', {'form': form}) Django form used def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/blog') else: form = SignUpForm() return render(request, 'winterblog/signup.html', {'form': form}) Thanks a lot! -
Django rest framework w/ no models - can't route to detail view
Following this tutorial, I'm trying to add a url to which one could make a POST request without a model: router.register(r'send_message', SendMessageViewSet, base_name='send_message') I don't need a GET, but I added one for debugging purposes: class SendMessageViewSet(ViewSet): def get(self, request, *args, **kwargs): return Response(HTTP_200_OK) def create(self, request, *args, **kwargs): ... Yet I'm able to get the "list" (url with no pk) but not the specific resource. Thanks! -
Django not a valid value for a primary key error in ModelMultipleChoiceField
I created a form consisting of two ModelMultipleChoiceFields of all the countries in the world. But after a POST request, Django doesn't deem the form valid with the error: "Algeria" is not a valid value for a primary key (or whichever country I select). Here is my form: class ComparisonForm(forms.Form): country_1 = forms.ModelMultipleChoiceField( queryset=WorldBorder.objects.values_list('name',flat=True) ) country_2 = forms.ModelMultipleChoiceField( queryset=WorldBorder.objects.values_list('name',flat=True) ) The list of countries is drawn from the db, which works fine. And my views: def lookup(request): if request.method == "POST": form = ComparisonForm(request.POST) if form.is_valid(): results = form.save(commit=False) country_1 = WorldBorder.objects.get(name=results.country_1) country_2 = WorldBorder.objects.get(name=results.country_2) country_1_name = country_1.name country_2_name = country_2.name multiplier = round(country_2.area / country_1.area, 1) return render( request, 'results.html', { 'country_1': dummy, 'country_1': country_1_name, 'country_2': country_2_name, 'multiplier': multiplier, } ) else: return render(request, 'error.html', {'form': form}) else: form = ComparisonForm() return render( request, 'lookup.html', {'form': form} ) And finally the html belonging to the form: {% extends "base.html" %} {% block content %} <h2>Compare the size of two countries here:</h2> <form id="comparison" action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" name="compare" value="Go compare!"> </form> {% endblock %} I am quite new to Django and somewhat at a loss as to how to solve this. From where … -
Django. Two queries in once. Is it right?
For example i will do something like this: class ProductInsertAndDeleteView(CreateView, DeleteView): # Create template_name = 'project/room_reserve.html' form_class = ReserveRoomCreateViewForm success_url = reverse_lazy('main:products') # Delete model = Product success_url = reverse_lazy('product:products') In short I have 2 requests. 1. Insert information to database 2. Delete information from database How to handle 2 requests? What to do in that situations? Is there any solution for that moments? Please explain what to do -
Post data to Djnago rest API via emberJS in desired format
I have EmberJS using Django REST API, I have few checkboxes which I am using to filter the data based on selection of checkbox. <label>Certificate</label> <div> <div> <div class="form-group-checkbox"> {{input type="checkbox" checked=certA id="certificate_A"}} <label for="certificate_A">A</label> </div> <div class="form-group-checkbox"> {{input type="checkbox" checked=certB id="certificate_B"}} <label for="certificate_B">B</label> </div> <div class="form-group-checkbox"> {{input type="checkbox" checked=certC id="certificate_C"}} <label for="certificate_C">C</label> </div> </div> </div> Currently I am getting below in querystring while calling the API: .../Search?certificate_A=true&certificate_B=true But the API needs string array for this parameter and it expects the parameter as mentioned below: ../Search?certification=certificate_A&certification=certificate_B How can I modify the emberJS code to generate the API request in above shown format? -
Method GET not allowed when PATCH Null Value in Django Rest Framework
I have a problem with PATCH Null Value in Django Rest Framework with Extend User Model. Please take a look my issues! Serializers:, Profile is extend User Model class UserEditSerializer(ModelSerializer): job_title = serializers.CharField(source='profile.job_title') class Meta: model = User fields = [ 'username', 'job_title', ] def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() if (validated_data.get('profile') is not None): profile_data = validated_data.pop('profile') profile = instance.profile profile.job_title = profile_data.get('job_title', profile.job_title) My viewsets: class UserUpdateAPIView(ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserEditSerializer permission_classes = (IsAuthenticated,) @detail_route(methods=['PATCH']) def edit(self, request): user_obj = User.objects.get(id=request.user.id) serializer = UserEditSerializer(user_obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return JsonResponse({'message': 'Error'}, status=500) My api patch request to server: { "job_title": "" } Error: { "detail": "Method \"GET\" not allowed." } Error Photo -
Bitnami instance downgrade from python 3 to python 2
Setting up a site on Google Cloud on a one install bitnami instance. The path for the python it's using is /opt/bitnami/apps/django/lib/python3.6/site-packages/ which is python 3.6 and when i check the default python with python --version it's 2.7.13 which I used when developing the site. I want to downgrade the version on the lib to 2.7 and depending on the error I get aftwerwards even lower the Django version to 1.8 or 1.9 since it's now using 2.0 I've just pointed the Apache conf files to my existing project and got an 500 internal error (from apache not django) and when I checked the error logs for Apache got the block of text below [Sat Jan 20 08:12:00.392061 2018] [ssl:warn] [pid 16792] AH01909: localhost:443:0 server certificate does NOT include an ID which matches the server name [Sat Jan 20 08:12:00.441919 2018] [ssl:warn] [pid 16793] AH01909: localhost:443:0 server certificate does NOT include an ID which matches the server name [Sat Jan 20 08:12:00.470337 2018] [mpm_prefork:notice] [pid 16793] AH00163: Apache/2.4.29 (Unix) OpenSSL/1.0.2n mod_wsgi/4.5.20 Python/3.6 configured -- resuming normal operations [Sat Jan 20 08:12:00.470390 2018] [core:notice] [pid 16793] AH00094: Command line: '/opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf' [Sat Jan 20 08:12:07.113691 2018] [wsgi:error] [pid 16803] /opt/bitnami/python/lib/python3.6/site-packages/pkg_resources/__init__.py:1298: … -
Django template shows only last file, instead of all uploaded
I want that for every lecture, the user to be able to upload multiple files, so I created a model that has FileField. So in my template, I want that for every lecture, the files uploaded to a particular lecture, to be shown in template. The Issue is that only the last uploaded file will show. <ul> {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% if c.files %} <li><a href='{{ MEDIA_URL }}{{ c.files.files.url }}'>download</a></li> {% endif %} {% endfor %} </ul> {% endfor %} </ul> </ul> def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), } return render(request, 'courses/courses.html', context) class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), ), default=0) lecture_title = models.CharField(max_length=100) content = models.TextField() files = models.ForeignKey('FileUpload', on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return str(self.lecture_category) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) def __str__(self): return str(self.files) def file_link(self): if self.files: return "<a href='%s'>download</a>" % (self.files.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' If I change to … -
How to add already built in delete permissions in Django programatically?
I have been trying to make an app which has 2 types of users : student and teacher. I have added custom permissions in both the models and they worked fine. Now I am not sure how to give the already built in delete permission to teacher so that she can delete a student? I havent been able to find anything regarding the same. -
Django {% load compress staticfiles %} image is not loading in heroku production path but works in local url
This is my heroku link : https://healthchecks-app.herokuapp.com/ I am not getting specific image.png files as it is loaded using Static compress file. Here is my Settings.py file: """ Django settings for hc project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os import warnings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) HOST = "localhost" SECRET_KEY = "---" DEBUG = True ALLOWED_HOSTS = [] DEFAULT_FROM_EMAIL = 'healthchecks@example.org' USE_PAYMENTS = False REGISTRATION_OPEN = True TEMPLATE_DEBUG = False INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'compressor', 'hc.accounts', 'hc.api', 'hc.front', 'hc.payments' ) MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'hc.accounts.middleware.TeamAccessMiddleware', ) AUTHENTICATION_BACKENDS = ( 'hc.accounts.backends.EmailBackend', 'hc.accounts.backends.ProfileBackend' ) ROOT_URLCONF = 'hc.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'hc.payments.context_processors.payments' ], }, }, ] WSGI_APPLICATION = 'hc.wsgi.application' TEST_RUNNER = 'hc.api.tests.CustomRunner' # Default database engine is SQLite. So one can just check out code, # install requirements.txt and do manage.py runserver and it works DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': './hc.sqlite', } } # You can switch database engine to postgres … -
Creating models and serializers for ManytoMany and foriegn key fields - django
I am new to Django and trying to create REST API for following problem : A user will add skills to his profile and other users can upvote the skill on other's profile . After learning from past 1 month I am able to create JWT session authentication for adding Skills (HTTP GET and POST). Next I am confused on how to make my serializers and views for operations like adding Skills to user profile and getting upvotes on it . I have following Model and View ready and tested : #import from django models module from django.db import models # This class will more or less map to a table in the database and defines skills at the application level class Skill (models.Model): # this defines a required name that cannot be more than 100 characters. skill_name = models.CharField(max_length=100,unique=True) class Meta: app_label = "wantedly_webapp" # This class will more or less map to a table in the database and defines the many to many relationship between user-skill, this is our intermediate model class UserSkill(models.Model): """ A Model for representing skill in user profile """ unique_together = (('user', 'skill_item'),) user = models.ForeignKey('UserProfile',on_delete=models.CASCADE,related_name='all_user_skills') skill_item = models.ForeignKey( Skill, on_delete=models.CASCADE ) def __str__(self): … -
Do I add the files in my migrations folder to my live Django server?
I'm going to push my offline Django project to Bitbucket, and then push that repo to my live Django server. My question is, do I exclude the contents in my migrations folders? And then perform makemigrations and migrate on my live server (Ubuntu/DigitalOcean) after the repo has been pushed to there? -
Django filter based on custom function
I have a table AvailableDates with a column date that stores date information. I want to filter the date after performing some operation on it which is defined by convert_date_to_type function. def convert_date_to_type(date): #perform some operation on date #return value will be a type, which will be any one item from types list below return type list of types: types = [] types.append('type1') types.append('type2') types.append('type3') Now I want to filter the table based on type. I will do this in for loop: for i in range(0,len(types)): #filter table here based on types[i], something like this AvailableDates.objects.filter(convert_date_to_type(date)=types[i]) How can I achieve this? Any other approach is much appreciated. -
How to use StringAgg aggregation functions in PostgreSQL 9.6 using DjangoORM
I am trying to join a field over a group. I could handle it in MySQL as described in one of my previous questions. However I migrated to PostgreSQL now and the proposed solutions does not work in PostgreSQL 9.6. According to Django docs, it is possible to use StringAgg as described here or here. I believe, in newer versions of PostgreSQL I cannot execute the line: from django.db.models.sql.aggregates import Aggregate as SQLAggregate Which throws the error: from django.db.models.sql.aggregates import Aggregate as SQLAggregate ModuleNotFoundError: No module named 'django.db.models.sql.aggregates' How can I create my own Aggregate Function using StringAgg? -
django best practice for navbar across multiple pages
What is the best practice way of implementing multipage navbars in webpages using Django. To be more specific (since this is the technology I am using) a Bootstrap navbar. Many tutorials motivate Django template inheritance by demonstrating an example of a page that inherits from a base page that contains the navbar. To my mind this doesn't sound optimal since the navbar would be re-downloaded and re-rendered in the browser with every request, while the server will have to re-serve it. On the other hand most Bootstrap tutorials assumes all the content in all the tabs of the navbar are in one webpage. So my question is, is there a standard Django or Bootstrap functionality that allows one to implement this scenario in a more optimal way? -
Installing MySqlDB on Python 3.6
I am unable to resolve this issue for a day now. when i try to execute my django project, pycharm throws the error "No module named 'MySQLdb'". From reference to similar questions on SO. I did try to install packages through file settings, that raises another error "Could not find a version that satisfies the requirement MySQLdb (from versions: ) No matching distribution found for MySQLdb" My project requires python 3.6 and the project doesn't seem to be working without MysqlDB. I did try to install mysqlAlchemy and mysqlconnector but it is of no use. Can some one point out how to resolve this ? I am on mac and there is no issue if i try to run the project from terminal. EDIT : I did try to install mysql from the pycharm package manager. But it throws another error No module named 'ConfigParser' -
sqlite database table is locked on tests
I am trying to migrate an application from django 1.11.1 to django 2.0.1 Tests are set up to run with sqlite in memory database. But every test is failing, because sqlite3.OperationalError: database table is locked for every table. How can I find out why is it locked? Icreasing timeout setting does not help. -
Connect Django with Oracle12C
I have successfully connected to the TESTDB using python program and JDBC and using the same credentials. Now, i want to connect to Django but getting error saying that "ORA-01017: Invalid Username/password; logon denied. python manage.py runserver error s django project settings.py oracle12c variables listener.ora file tnsnames.ora file connected using python