Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I preserve the items order when filtering in Django?
I've order the Recommendations by the rating_prediction and get the ids, then when I filter it to get the Tracks, the order is not the same anymore class RecommendationView(generics.ListAPIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = RecommendedTrackSerializer queryset = Recommendations.objects.all() pagination_class = api_settings.DEFAULT_PAGINATION_CLASS def get_queryset(self): recommendation = Recommendations.objects.filter(user=self.request.user) sorted_recommendation = recommendation.order_by('-rating_prediction') ids = list(sorted_recommendation.values_list('track', flat=True)) tracks = Track.objects.filter(id__in=ids) return tracks -
Django el-pagination adding GET parameters
I have went trough the official documentation and i couldn't figure out how can i override/add additional user arguments to my GET request for additional filtering for like something like search. My current initialization looks like: $('.infinite_scroll').endlessPaginate({paginateOnScroll: false}); -
What's best approach to maintain database table field between git branch
I'm using Django and Postgresql to develop a web service. Suppose we've 3~4 branch which for the different features or old-version bugfix purpose. Then, I met a problem, when I was in branch A and change django model, and run migrate to change database in my local test desktop. When I switch to another branch which has no migration file, database will inconsistent and cannot work when I try to run django, I've to delete the database and recreate it. In general, what's the best/common way to deal with this kind demands for developer environment? -
Twitter API Product with Django
I am making a twitter Api product.My plan is to make such a twitter api product when a user enter a trending tweets or any keyword like #donaldtrump etc.It should display images with tweettext and video with tweettext.So,for that i am using python library tweepy,django.What i did is made search box and analyse button while clicking button. I am getting all text tweets,links,etc.so, how to improve my code so that i can make image along with tweet and video along with tweet. views.py from django.shortcuts import render,redirect from django.views.generic import TemplateView from .models import * from django.http import HttpResponse from django.views.generic.edit import FormView from .forms import TweetForm from django.views import View import pdb import tweepy consumer_key = 'VR95CmIMrv7q7vfDoPcjC8NZS' consumer_secret = 'YlWo6BzDnhXozSZnvnN1cIcjvRKrJFJVnYA9vvqMDocOdjyBNu' access_key = '1006840281361047553-JQPFugH9xVNifKRY1b4BjgpdTLiVND' access_secret = '5R3DXQmf6Xf3FwZHZzqSU3P3oYQAReUqwux9ttj5Gj7K5' class Tweet(FormView): template_name = 'tweet.html' form_class = TweetForm def form_valid(self, form): user = form.cleaned_data.get('tweet') return redirect('tweet_details', user) class TweetDetails(View): def get(self, request, user): auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) number_of_tweets=100 tweets = api.search(q=user,count=100, lang="en") twitterData = [] for tweet in tweets: print(tweet.text) twitterData.append(tweet) searchedData = str(twitterData) return render(request, 'tweet_details.html', {'TwitterFeed': searchedData}) urls.py ` from django.conf.urls import url from . import views urlpatterns = [ url(r'Tweet/$', views.Tweet.as_view(), name='Tweet'), url(r'TweetDetails/(?P<user>.+)/$', views.TweetDetails.as_view(), name='tweet_details'), … -
Bulk insert and Update in Django rest frame work
I am trying to do bulkinsert and bulk update in single request using https://github.com/miki725/django-rest-framework-bulk, Below is my list serilizer and modelViewset. class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping: book.delete() return ret class BookSerializer(serializers.Serializer): class Meta: list_serializer_class = BookListSerializer class BookCSVViewSet(generics.BulkModelViewSet): queryset = Book.objects.all() serializer_class = BookCSVSerializer def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] if isinstance(data, list): kwargs["many"] = True return super(BookCSVViewSet, self).get_serializer(*args, **kwargs) @list_route(methods=['PUT']) def bulk_update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) # restrict the update to the filtered queryset serializer = self.get_serializer( self.filter_queryset(self.get_queryset()), data=request.data, many=True, partial=partial, ) validated_data = [] validation_errors = [] for item in request.data: print self.get_queryset().get(pk=item['id']) item_serializer = self.get_serializer( self.get_queryset().get(pk=item['id']), data=item, partial=partial, ) item_serializer.is_valid(raise_exception=True) if item_serializer.errors: validation_errors.append(item_serializer.errors) validated_data.append(item_serializer.validated_data) if validation_errors: raise ValidationError(validation_errors) serializer._validated_data = validated_data self.perform_bulk_update(serializer) return Response(serializer.data, status=status.HTTP_200_OK) I am sending both existing record and new record in the same … -
django-rest-auth error - save() takes 1 positional argument but 2 were given
I'm using django-rest-auth with a custom user model, registration view and serializer. What I'm trying to achieve is an email login instead of username. The api view shows correctly but when I post, I get the error: TypeError at /rest-auth/registration/ save() takes 1 positional argument but 2 were given this is the traceback: http://dpaste.com/2FR3DZY serializer.py class CustomUserSerializer(serializers.ModelSerializer): """Serializer for User objects.""" class Meta: model = models.User fields = ('id', 'email', 'name', 'password') extra_kwargs ={'password': {'write_only': True}} def create(self, validated_data): """Create and return a new User.""" user = models.User( email=validated_data['email'], name=validated_data['name'] ) user.set_password(validated_data['password']) user.save() return user view.py class CustomRegistrationsView(RegisterView): serializer_class = CustomUserSerializer urls.py path('rest-auth/registration/', CustomRegistrationsView.as_view(), name='rest_register'), path('rest-auth/', include('rest_auth.urls')), Can anyone advise? -
Django restframe work send email from posted data
I'm using Django rest framework, I have a contact us table.. in views, I use class based view i want to send email when user post data .. this's my function def post(self, request): subject = request.POST.get('subject', '') message = request.POST.get('message', '') from_email = request.POST.get('email', '') if subject and message and from_email: send_mail(subject, message, from_email, ['haguwanax@l0real.net'], fail_silently=False) return Response (status=status.HTTP_200_OK) return self.create(request) it saves the data but there's nothing being sent. this's my settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_PORT = 587 EMAIL_HOST_USER = '*****@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_USE_TLS = True -
SMTPSenderRefused at / (501, b'5.1.7 Invalid address [MAXPR01MB0396.INDPRD01.PROD.OUTLOOK.COM]', '=?utf-8?q?Your?=')
I am unable to send mail on django application using office365 settings my settings for the email service. EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = "***********" EMAIL_HOST_PASSWORD = '***********' EMAIL_PORT = 587 -
Group by 2 fields combination and then order by the sum of each group, multiple annotations django
I was trying to get top products ordered by their total margin sum from invoices as: Filter invoices by given store_id Group by product_name And the get the Sum of gross_margin of each group Finally order them by Sum of gross_margin (high to low) Wrong previous code: high_margin = StoreInvoiceBreakup.objects \ .filter(store_invoice__store_id=store_id) \ .annotate(product_count=Count('product_name')) \ .annotate(gross_margin_sum=Sum('gross_margin')) \ .order_by('-gross_margin_sum') \ .values(name=F('product_name')) \ .distinct()[:int(top_count)] And then ended up solving multiple annotation problem via Stack Overflow similar question as: (as previous code was giving wrong results.) New correct code: high_margin = StoreInvoiceBreakup.objects \ .filter(store_invoice__store_id=store_id) \ .values('product_name') \ .annotate(gross_margin_sum=Sum('gross_margin')) \ .order_by('gross_margin_sum') \ .distinct()[:int(sell_range)] And the output looks like: "high_margin ": [{ "product_name": "ABCD", "gross_margin_sum": 100 --sum of all margins for abcd }...other products with sum] Which is absolutely correct, but encountered another problem, as: A store can have a product with same product_name, but may have different expiry date. So what i want is, To group products by their product_name and expiry_date combination. Then get the margin sum for each group and return ordered by the Sum, with distinct combinations. (Not distinct product names only.) *Removing distinct does't help Or a MySQL query to do so would also be helpful. If can't do it … -
Django not recognizing files deleted/added
I have the following function that gives me the list of files(complete path) in a given list of directries: from os import walk from os.path import join # Returns a list of all the files in the list of directories passed def get_files(directories = get_template_directories()): files = [] for directory in directories: for dir, dirnames, filenames in walk(directory): for filename in filenames: file_name = join(dir, filename) files.append(file_name) return files I'am adding some files to the template directories in Django. But this function always return the same list of files even though some are added/deleted in the run time. These changes are reflected only when I do a server restart. Is that because of some caching that os.walk() performs or is it required that we need to restart the server after adding/removing some files ? -
Django CharField equal to evaluation
I have a model with Field like key = CharField(max_length=100, blank=True) when i check for the value after form submission like this. if self.key is None: the condition fails But when i check for if self.key == '' it works. My question is why it doesn't works when i evaluate it to None and works when i use ''. The None condition works only when i assign the values like this. key = CharField(max_length=100, null=True ,blank=True) I read some posts where it states that when evaluating the CharField as blank=True an empty string '' is saved but they didn't shed any light why it does that. because as far i understand it should save a Null value. -
Django datetimefield, timezonefield and epoch
I want to work on a django project that work with time(track time of user), but I don't know to choose datetime field or timezone field or epoch time in an integer field for project model. I worked with all of them and I know we can convert them to each other. My question is for saving time in db, process on time and represent which one is recomended and why? What I need to consider for choosing between them? -
django static file Internal Server Error: Missing staticfiles manifest entry for 'favicon.ico'
i have django and static angular project when i turn debug to off in setting.py i get error 500 (Server Error (500) and when i check my email it say: Internal Server Error: / ValueError at / Missing staticfiles manifest entry for 'favicon.ico' i print all path in setting looks all path is correct. this person had very similar problem to me : and i did all suggestion but it didnt work for me ValueError: Missing staticfiles manifest entry for 'favicon.ico' favicon.ico is already available in static and staticfiles folders if i remove STATICFILES_STORAGE from setting app will load but no media image that are in upload folder will load !! i tried many way to fix it but i had no chance ... if you know any suggestion please tell me this is my setting: MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, 'upload') print('meida root',MEDIA_ROOT) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.dirname((__file__))) #STATIC_ROOT = BASE_DIR+'/academy/staticfiles' STATIC_URL = '/static/' #STATIC_ROOT = os.path.join((BASE_DIR),"static/") STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') print("staticroot", STATIC_ROOT) #MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"media") # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) print("staticfiledir",STATICFILES_DIRS) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' #STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' #STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' and … -
How to get data of particular sender and receiver in chatbox?
I want to get all messages history of particular sender and receiver. i am using fronEnd angular5 and Backend Django.. my db sample table : { "id": 288, "name": "Faric", "receiver": "drit", "text": "hiee", "myDate": "2018-07-26T04:38:05.505000Z" } chatService: getMessage(){ return this.http.get(this.url).map(res => res.json()); #url of messages API } chatcomponent: this.chat.getMessage() .subscribe(msg=> this.messages = msg); # messges = [] using this service and component i get all mssages.. jst i want to get perticular sender and receiver's data. how to do this? -
Django 'Image' object has no attribute '_committed'
So I have been trying to resize the images uploaded to my projects page of my personal website but for some reason it is throwing me an error. I am trying PIL to resize but it keeps to throwing me the attribute error whenever I post my post with the uploaded image. MY code is down below: from django.db import models from django.utils import timezone from django.forms import ModelForm from django.utils.text import slugify from django.utils.crypto import get_random_string from PIL import Image # Create your models here. class Projects(models.Model): title = models.CharField(max_length=30) description = models.TextField(max_length=150) publish_date = models.DateTimeField(auto_now=False, auto_now_add=True) update_date = models.DateTimeField(auto_now=True, auto_now_add=False) slug = models.SlugField(unique=True) files = models.FileField(upload_to='files/',blank=True) images = models.ImageField(upload_to='images/',blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): # Opening the image to be resized r_image = Image.open(self.images) # Resizing the image from the imagefield new_image = r_image.resize((96, 96), Image.ANTIALIAS) self.images = new_image # Generates a random string unique_string = get_random_string(length=32) # Combines title and unique string to slugify slugtext = self.title + "-" + "unique_id=-" + unique_string self.slug = slugify(slugtext) return super(Projects, self).save(*args, **kwargs) I would appreciate your answers! -
How to set a default value for a float field using django models?
from django.db import models class doctors(models.Model): docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary name = models.CharField(max_length=35) regid = models.CharField(max_length=15, default="") photo = models.CharField(max_length=35, default="") email = models.EmailField(default="") phone = models.IntegerField(default=0, null=True) qualifications = models.CharField(max_length=50, default="") about = models.CharField(max_length=35, default="") specialities = models.CharField(max_length=50, default="") department = models.CharField(max_length=50, default="ENT") fees = models.FloatField(default=300.0, null=True) displayfee = models.IntegerField(default=0, null=True) slotrange = models.CharField(max_length=50) slotdurn = models.IntegerField(default=10, null=True) breakrange = models.CharField(max_length=50, default="") slotsleft = models.CharField(max_length=50, default="") What I intended: If one of the fields like phone, fees, displayfee, or slotdurn is not specified, they should be filled in a default value. Unfortunately these are filled with an automatic value of NULL when I do the following: from appointments.models import doctors doc=doctors(name="Dr Joel", regid="12524", email="joel@mydomain.com") doc.save() I checked the sql created, and it is like this: CREATE TABLE `appointments_doctors` ( `docid` int(11) NOT NULL, `name` varchar(35) NOT NULL, `regid` varchar(15) NOT NULL, `photo` varchar(35) NOT NULL, `email` varchar(254) NOT NULL, `phone` int(11) DEFAULT NULL, `qualifications` varchar(50) NOT NULL, `about` varchar(35) NOT NULL, `specialities` varchar(50) NOT NULL, `department` varchar(50) NOT NULL, `fees` double DEFAULT NULL, `displayfee` int(11) DEFAULT NULL, `slotrange` varchar(50) NOT NULL, `slotdurn` int(11) DEFAULT NULL, `breakrange` varchar(50) NOT NULL, `slotsleft` varchar(50) NOT NULL … -
Django - how to modify crispy forms?
First, I want to generate a page that looks like this: There are three things that makes it difficult. 1. Label + Input field set should line up horizontally 2. Some of the fields have checkbox 3. Date Field has a special Bootstrap plugin. Here are the html source code for each types: generic type: <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" style="margin-bottom: 5px"> <label class="input-upper-title">Drill String Name</label> <input type="text" id="" class="form-control input-field-height-vertical" name="" required=""> </div> has checkbox: <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" style="margin-bottom: 5px"> <label class="input-upper-title">String Length (ft)</label> <div class="has-checkbox"> <input type="checkbox"><input disabled="disabled" type="text" id="" class="form-control input-field-height-vertical input-calculated" name="" data-parsley-trigger="" required=""> </div> </div> has date plugin: <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6" style="margin-bottom: 5px"> <label class="input-upper-title">Date Run</label> <div class="form-group"> <div class="input-group date" id="datetimepicker7" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input input-field-height-vertical" data-target="#datetimepicker7"/> <div class="input-group-append" data-target="#datetimepicker7" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> </div> </div> And here is my forms.py: class BHA_overall_Form(forms.ModelForm): prefix = 'bha_overall' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() class Meta(): model = BHA_overall fields = '__all__' How should I modify my forms.py, using crispy_forms to get the same effect as my html source code does? -
Passing kwargs to a custom field in django
I used this question as a base for creating a custom field: Django File upload size limit When I try to makemigrations I get an error stating that 'content_types' isn't in the kwargs. I've debugged through the code and it almost seems like my custom field init is being called twice. Once from within the model where I have this field (with the kwargs) and once without the kwargs included. I referenced this post: How to pass additional keyword arguments in a custom Field in Django Rest Framework? However I am already doing whatever the solution says. def __init__(self, *args, **kwargs): self.content_types = kwargs.pop('content_types') self.max_upload_size = kwargs.pop('max_upload_size') super(MediaField, self).__init__(*args, **kwargs) the error: KeyError: 'content_types' the stacktrace: (efs-cP0vQdei) user@right:~/Documents/websites/efs$ ./manage.py makemigrations Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 133, in handle ProjectState.from_apps(apps), File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/db/migrations/state.py", line 222, in from_apps model_state = ModelState.from_model(model) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/db/migrations/state.py", line 411, in from_model fields.append((name, field.clone())) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 470, in clone return self.__class__(*args, **kwargs) File "/home/user/Documents/websites/efs/ssadventures/customfields.py", line … -
How to get notified when a message is published in rabbitMQ queue in django?
right now i have a pure python file that always is running and listens to rabbitMQ but i want to know is there any way in my django app to get notified when a new message is published to a specific queue in rabbitMQ. -
django/python 3.5 imports/separating views.py into separate files
I've looked at just about everything I can here. I'm using python 3.5 and i've seen stuff about how they've changed the way imports work. My django project structure is like this: project --app --views/ --__init__.py --myFile.py --__init__.py --models.py --admin.py --urls.py --etc.... My urls.py is such: from django.contrib import admin from django.urls import path from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^api$', views.function_from_myFile_that_is_not_being_found), otherurls()... ] The error I'm getting is AttributeError: module 'app.views' has no attribute 'function_from_myFile_that_is_not_being_found' I'm really lost as to why this is happening. I've tried putting imports in my __init__.py files and that hasn't worked either. Not sure what else I'm missing. Thanks in advance. -
How to create Django browsable REST API without auth or permissions?
I removed admin, auth, permissions, and a few other apps and middleware pieces from my DRF service. I'm running a microservice architecture where each service owns its own database. I don't need Django to pollute all those databases with its own set of auth/user/permissions tables. Now I'm getting: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. What is still using the auth models and how do I get rid of it? More Context: I want a microservice with only three things: A REST framework A database abstraction layer A browsable API (doesn't have to be HTML, can be pure JSON) Is it even possible to do such a thing in DRF without having 20 sets of auth tables for 20 databases (for 20 services)? -
why I can't get map in admin? (geodjango)
I am beginner for geodjango. I followed video tutorials on youtube. And I finished the geo-database installation. models.py: from django.db import models from django.contrib.gis.db import models as geomodels class City(models.Model): name = models.CharField(max_length=100, blank=False) geometry = geomodels.PointField() class Meta: # order of drop-down list items ordering = ('name',) verbose_name_plural = 'cities' When I opened the admin page. There is only a dark image for the PointField. dark image but I can add the location. location How can I get the real map instead of a dark image? I use Django 2.0 and python 3.6 -
ManyToMany field point to self wrong behavior?
I am having the following lines in my model : class UserProfile(models.Model): user_favorites = models.ManyToManyField('self', verbose_name='Favorites', blank=True) What I am doing here is simple. I have a UserProfile object, each user have a list of users he favorites. this list is the user_favorites field. I am accessing my field via Admin to add new favorites to the user. however, the behavior I see is that each time I am adding a user (via admin) to that specific user I see that the user I have favorite also has the user added him added to its user_favorites field. So I want to make user X favorite Y and what happens is user X favorite Y and user Y favorite X. which was not what I intended. Am I doing something wrong ? or maybe many to many to self is the problem ? -
Change Python Version from 3.6 to 2.7 in AWS Elastic Beanstalk
I recently set up a new application in Elastic Beanstalk and created an environment using python. I want to use this environment to host a small Django web app I made using python 2.7 and Django 1.11. However, when I set up the environment, it defaulted to python 3.6 and for some reason the option to change the configuration is disabled. Does anyone know why it is disabled and how I can change this configuration? disabled configuration button -
Django freezes for a minute
i had some issues with django. While i was running some tests from a phone and computer this problem appeared. Image Problem. After adding a change in the admin of django, the server console frozen for a minute. On the image It can be seen as i underlined it with yellow, were this problem occurs. I tried more than three times but the problem persists. Our webpage stoped working by that time. Does anyone know how to help me or any kind of solution?