Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make api call from react hotreload server to django server?
I am trying to develop a website with react and django. I have react hotreload running in localhost:8080 and django on localhost:8000. Now when I try to make a api call to django server for data than chrome throws the following error: There has been a problem with your fetch operation: Failed to execute 'fetch' on 'Window': The origin of 'http://localhost:8000/' should be same as 'http://localhost:8080' I am using ubuntu 16.04 as my dev machine. Please help. -
How to properly paginate comments table by time
This question isn't so much about Django as it is about general pagination. Consider the following table of comments. | auto_inc_id | comment | timestamp | |-------------|-------------------------|-----------| | 1 | I sure love pie | 1000 | | 2 | I hate mondays | 2000 | | 3 | I want to watch a movie | 3000 | | 4 | hello world | 2500 | This is a simple table of user comments. When a user clicks "submit", the server pushes the event onto a processing queue. Due to the nature of the processing queue (this might take 1-2 hours). So in order to get the "real time of submission" the client interface also generates a timestamp that it bundles up with the request (I know this is spoofable) When the event gets finally dequeued. They are inserted into the table. There is also an app that queries this table, and displays a scrolling list of comments (most recent first - at the top). The user can scroll to the bottom and click "more" - which will load even older comments onto the app screen - and so on and so forth. I was planning to use a simple … -
Django-allauth not asking for permission while using facebook
While trying to login the application I have seen the Django-Allauth do not ask for the permissions for accessing the profile data. It just simply ask for the password for reauthentication purpose (even after using the oauth2 or js_sdk). See the following image which shows the current login screen: I expect the login should be like the following: Please let me know how I can achieve this in Django-allauth -
Setting up Mimetype when to show a mp4/webm in all browsers in Django
I'm trying to understand how I can have my website properly display - specifically a banner video. I think the issue relates to Mimetype - It works from my computer but not when server from a server. This is the website https://consultingpage.herokuapp.com/ . I assume that the issue is within my settings.py or urls.py - I'll put them below. Urls.py """ The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls import url from django.contrib import admin from django.conf.urls.static import static from profiles import views as profiles_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', profiles_views.base, name='base'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and Settings.py """ Django settings for alex1 project. Generated by 'django-admin startproject' using Django 1.11.4. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For … -
AllAUTH Django not redirecting to Home Page
I am trying to make a Django 1.11.5 Application including the Facebook Login using AllAuth. Settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True } } ACCOUNT_LOGOUT_ON_GET = True The problem is: When I click on the login through link a box appear for password. If I cancel the box then the error or cancel template appears on the browser like the below: I want that this page should not appear. Instead, the URL must redirect to HomePage. Hence I tried the following in my URLS.py url(r'^accounts/social/login/cancelled/$', RedirectView.as_view(pattern_name='homeIndex', permanent=False)) But has no effect on the browser. Please let me know what I am missing in the implementation to improve my functionality. -
Remove item with empty value in django dictionary
I want to remove dictionary item on my list. Animals = ['dog', 'cat', 'fish', 'goat'] Owner = ['Nash', 'Luffy', '', ''] C = dict(zip(Animals, Owner)) C = {'dog':'Nash', 'cat':'Luffy', 'fish':'', 'goat':''} What should I do to achieve the result below: C = {'dog':'Nash', 'cat':'Luffy'} -
django class based view shared code between post and get
I'm making a Django app and I was wondering if there was a way I can call a method dosomecheckups in both post and get method without having to type it twice. Keep in mind, I need the request object for my checkup method. NB: I don't want to use decorators for now. class Welcome(View): def get(self, request): #I wanna avoid having the method below both in post and get self.dosomecheckups(request) ... def post(self, request): #I wanna avoid having the method below both in post and get self.dosomecheckups(request) ... def dosomecheckups(self, request): # request is required for this checkup so __init__ isn't an option pass -
How to save the django model after its many to many field and foreign key saved
I am working on a Django project, which has a number of fields including many ForeignKey and ManyToMany Fields. and I am trying to create a flat json file by serializing this model so that I can index it into an elastic search server by using elasticsearch-DSL. models.py class Video(models.Model): """Video model""" title = models.CharField( max_length=255, ) education_levels = models.ManyToManyField( EducationLevel, verbose_name=_("Education Level") ) languages = models.ManyToManyField( Language, verbose_name=_("Languages") ) def save(self, *args, **kwargs): # Save the model instance super(Video, self).save() # After saving model instance, serialize all the fields # And save to elastic search self.serialize() def serialize(self): """Method that serialize all the dependencies and call elastic search to post data""" # The problem I am facing is # This method only able to serialize only its fields not able # to serialize Foreignkey and ManytoMany field. # The problem is serialized_data = dict( self.title, # got serialized # Not able to serialized as the instace is not saved before this model get saved. education_levels=[education_level.level for education_level in self.education_levels.all()], # # Not able to serialized as the instace is not saved before this model get saved. languages=[language.language for language in self.languages.all()], ) # Save data to Elastic search save_to_elastic_server(index="videoindex", … -
How to deploy website changes in Django
Recently, the web developer that created our website has gone a-wall. Our company is in the process of sourcing a new developer that knows Django and Python. I am a Microsoft developer with little to no Django experience. However, I do know a little unix and have worked with linux and apache before. We need to make a minor update to our contact details page as we have moved office. The developer originally hard coded this page so we can not update this page via the CMS. I have located the file on the server and made the address updates but I do not know how to deploy it so it reflects on the live site. Can anyone assist me in doing this? I'm ssh into the box and doing everything via the terminal. Cheers, Ben -
django-taggit issue with url for blog/tag page & display all tags
I am having issues getting django-taggit to work in a test blog to a test django website. I have been able to display the individual tags next to the blog description, when I list the blogs. However I have the following two issues: I cannot display all of the tags used for all the blog entries in the blog template; I cannot get the url link working to display the selected links to the blog/tag/<tag name>/ page. Here is my models.py code: class BlogDetails(models.Model): blog_title = models.CharField(null=False, blank=False, max_length=150, unique=True) blog_description = models.TextField(null=False, blank=False, max_length=1500) blog_script = models.TextField(null=True, blank=True, max_length=15000) blog_date_published = models.DateField(null=False, blank=False, default=datetime.now) blog_video_url = models.URLField(null=False, blank=False, max_length=250) blog_video_image_url = models.URLField(null=True, blank=True, max_length=250) blog_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) blog_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) blog_tags = TaggableManager() class Meta: ordering = ['-blog_date_published', '-blog_timestamp_added', '-id'] Here is my views.py code: def blog_details(request): date_now = timezone.now() all_blog_tags = BlogDetails.objects.all() blog_details_values = BlogDetails.objects.filter(blog_date_published__lte=date_now) ... paginator = Paginator(blog_details_values, 10) # Show 10 blogs per page page = request.GET.get('page') try: blog_details_values = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. blog_details_values = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. blog_details_values = … -
Set dynamic scheduling celerybeat
I have send_time field in my Notification model. I want to send notification to all mobile clients at that time. What i am doing right now is, I have created a task and scheduled it for every minute tasks.py @app.task(name='send_notification') def send_notification(): # here is logic to filter notification that fall inside that 1 minute time span cron.push_notification() settings.py CELERYBEAT_SCHEDULE = { 'send-notification-every-1-minute': { 'task': 'send_notification', 'schedule': crontab(minute="*/1"), }, } All things are working as expected. Question: is there any way to schedule task as per send_time field, so i don't have to schedule task for every minute. -
Tag an existing model and save it as a new model object in Django
I'm working on a django (1.10.5) project in which I need to build a logic as: We have a model as "Article" and upload articles by admin already. Now we need to allow a user to open an article and when he opens an article it comes with a form to tag it with some fields and then user have to submit this form and it will save again. When user load articles again he should be able to get only those articles not tagged by that user. Currently where I am: I have created a model for Articles to upload all articles : It's as articles/models.py Categories = ( ('Acute Threat ("Fear")', 'Acute Threat ("Fear")'), ('Potential Threat ("Anxiety")', 'Potential Threat ("Anxiety")'), ('Sustained Threat', 'Sustained Threat'), ('Loss', 'Loss'), ('Frustrative Nonreward', 'Frustrative Nonreward'), ('Approach Motivation: Reward Valuation', 'Approach Motivation: Reward Valuation'), ('Approach Motivation: Effort Valuation / Willingness to Work', 'Approach Motivation: Effort Valuation / Willingness to Work'), ('Approach Motivation: Expectancy / Reward Prediction Error', 'Approach Motivation: Expectancy / Reward Prediction Error'), ('Approach Motivation: Action Selection / Preference-Based Decision Making', 'Approach Motivation: Action Selection / Preference-Based Decision Making'), ('Initial Responsiveness to Reward Attainment', 'Initial Responsiveness to Reward Attainment'), ('Sustained/Longer-Term Responsiveness to Reward … -
Django Orm Query - Reverse list lookup
Its easy to check if item is in a list via Django ORM like User.objects.filter(name__in = ['x', 'y']) how about reverse way. if User has a field say list of suburbs which he vists (A comma separated list) and we have to check if he has not visited a particular suburb . class User(models.Model): suburb = models.TextField(_('suburbs'),validators=[validate_comma_separated_integer_list], blank=True) Data when retrieved from shell_plus will be of this sort for {'suburb': '965,967,969,972' } Want to get all users who have not visited suburb 100 ? -
Django to anguler4 site converstion
Well I have one web app in Django 1.9 and I want to convert it fully in Anguler4 but the thing is I want to use all the API of old Django and yes, site is in Django not in Django-REST First thing, is it possible? and if yes then the site is big enough to take 3.5 to 4 months so I want to be sure about how should I start with it? -
I wanna send localhost:8000/accounts/detail ,but it cannot be done
I wanna send localhost:8000/accounts/detail ,but it cannot be done. I wrote in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = regist_form.save(commit=False) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return HttpResponseRedirect('detail') if login_form.is_valid(): user = login_form.save(commit=False) login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return HttpResponseRedirect('detail') context = { 'login_form': login_form, 'regist_form': regist_form, } return render(request, 'registration/accounts/login.html', context) Now in the part of HttpResponseRedirect,it sends localhost:8000/accounts/login/detail so error happens.This page read login method is localhost:8000/accounts/login.I wanna send the url to localhost:8000/accounts/detail.So,how should I fix this? In urls.py,I wrote urlpatterns = [ url(r'^detail$', views.detail,name='detail'), url(r'^login/$', views.login,name='login'), ] -
How can I use django template filter to delete the last character?
I have a string such as 100M, I want to delete the M, how can I do that? I tried use slice filter, but the number length is variable(maybe 1000 or others), so, how can I do that? -
Python Django equals in function arguments. Setting the variable dynamically
I think this is called "Positional arguments" or the opposite or keyword arguments. I have written a script in Python Django and rest framework that has to take in parameters from the user and feed it to the Amazon API. Here is the code; page = request.query_params.get('page'); search = request.query_params.get('search'); search_field = request.query_params.get('search_field'); search_index = request.query_params.get('search_index'); response = amazon.ItemSearch(Keywords=search, SearchIndex=search_index, ResponseGroup="ItemAttributes,Offers,Images,EditorialReview,Reviews") In this code the text Keywords=search varies. That is. It could be like this Actor=search, Title=search, or Publisher=search I am not sure how to make the Keywords part dynamic such that it changes to the user's input such as Actor, Title, or Publisher -
Django post save function not saving
I have post save function that I am trying to execute to update the count on my model. I have tried these two methods of doing the post save, they are all not updating my counter to "5" inside my database after I do a save on my admin page. # method for updating def update_tagpoll(sender, instance, *args, **kwargs): # countptype = c.polltype.count() # TagPoll.objects.count = countptype instance.counter = 5 post_save.connect(update_tagpoll, sender=TagPoll) # method for updating @receiver(post_save, sender=TagPoll, dispatch_uid="update_tagpoll_count") def update_tagpoll(sender, instance, **kwargs): instance.counter == 5 I also tried to do a instance.save()which would lead to a maximum recursion issue(which is expected) below is the model that I am trying to update. class TagPoll(models.Model): title = models.CharField(max_length=120, unique=True) polltype = models.ManyToManyField(Ptype, blank=True) active = models.BooleanField(default=True) counter = models.IntegerField(default=0) def __unicode__(self): return str(self.title) I cant seem to find what the issue, any advice would be appreciated. -
build a follower system which is not between enduser
Usecase The app that I am developing is about linking startup, job seekers and investors. Sorry I could not give the name still though I have developed already around 40% :) .There will be three entities. One is Startup account, Enduser account and Investor account. I am thinking of adding follow/unfollow feature where Enduser can follow Startup and vice-versa Startup can follow Investor and vice-versa Enduser cannot follow other enduser and enduser cannot follow investor For this how should I model my application Here is the model for the entities I talked about Enduser Model class UserSetting(models.Model): user = models.OneToOneField(User) job_interest = models.ManyToManyField(Category, related_name='user') is_email_notification = models.BooleanField( default=True, help_text="Email me job recommendations based on my interests and preferences") class Meta: verbose_name = 'User Setting' verbose_name_plural = 'User Settings' def __str__(self): return self.user.username Startup Model class Startup(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) slug = models.SlugField(unique=True) description = models.CharField(max_length=400) Investor Model class Investor(models.Model): investor = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False, help_text='Full Name') slug = models.SlugField(max_length=200, unique=True) contact_email = models.EmailField(null=True, blank=True) # for now I have done like this followers = models.ManyToManyField( User, related_name='followers', blank=True) For now, you can see I have included the followers field in the Investor but … -
AttributeError at /accounts/login/ 'dict' object has no attribute 'status_code'
I got an error,AttributeError at /accounts/login/ 'dict' object has no attribute 'status_code' .My web site's page has login&new account registration in a page. I wrote in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = regist_form.save(commit=False) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return context if login_form.is_valid(): user = login_form.save(commit=False) login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return context context = { 'login_form': login_form, 'regist_form': regist_form, } return render(request, 'registration/accounts/login.html', context) in login.html(I cannot user code format,so I decide to use code snippet) <header class="clearfix"> <h1 class="title">WEB SITE</h1> <ul> <form class="form-inline" method="post" role="form"> {% csrf_token %} <div class="form-group"> <label class="white-letter">LOGIN</label> </div> <div class="form-group"> <label class="sr-only">USERNAME</label> <input id="id_username" name="username" type="text" value="" minlength="5" maxlength="12" placeholder="USERNAME" class="form-control"> </div> <div class="form-group"> <label class="sr-only">PASSWORD</label> <input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12" placeholder="PASSWORD" class="form-control"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-lg" style="color:white;background-color: #F62459;border-style: none;">LOGIN</button> <input name="next" type="hidden"/> </div> </form> </ul> </header> <main> <div class="heading col-lg-6 col-md-12"> <h2>NEW ACCOUNT</h2> <h3 class="margin-small">ALL FREE</h3> <form class="form-horizontal" method="POST"> <div class="form-group-lg"> <label for="id_username">USERNAME</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">EMAIL</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">PASSWORD</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">PASSWORD(CONFORMATION)</label> {{ … -
How can I re-label the "Password" field on the Django 1.11 login page?
I want to customise the appearance of the "Password" field on the Django 1.11 login page. Specifically, I want to change the label from "Password" to "Passphrase" while maximising re-use of default Django code. For other forms I have done this subclassing as follows: from django.utils.translation import ugettext_lazy as _ from x import BaseForm class CustomForm(BaseForm): def __init__(self, *args, **kwargs): super(CustomForm, self).__init__(*args, **kwargs) self.fields["fieldname"].label = _("Custom label") ...but simply subclassing AuthenticationForm has no effect, so I assume I have to hook it up somehow. And/or subclass LoginView? -
Inactive django account with djoser
Hi guys I am trying to log in with an inactive account, I used Djoser, Django Rest Framework but I need to show the correct message to the user. I was testing the API with an inactive account, but I always receive this message: Unable to login with provided credentials. I was studying the code of djoser, and I found that this line of code (https://github.com/sunscrapers/djoser/blob/master/djoser/serializers.py#L95) is never gets execute, because the authenticate method always return None when the user is not active. I can solve the problem with Django ORM, but I think that's is not a fancy solution. I hope can you help me. Thanks in advance. -
'image' is an invalid keyword argument for this function
Here is the error: 'image' is an invalid keyword argument for this function Any help in understanding what is happening and how to fix it would be much appreciated. Basically I have a 'Partner' model with a one to many relationship to a 'Product' model. I am using inlineFormSet for the 'Product' model which has fields like partner, image, desc, price etc. The form displays correctly in admin and when the form is rendered but upon submitting it throws the error. here is my views.py def partner_create(request): #Trying to add multiple product functionality if not request.user.is_staff or not request.user.is_superuser: raise Http404 ProductFormSet = inlineformset_factory(Partner, Product, form=ProductForm, extra=3) if request.method == 'POST': partnerForm = PartnerForm(request.POST or None, request.FILES or None) formset = ProductFormSet(request.POST, request.FILES, queryset=Product.objects.none()) if partnerForm.is_valid() and formset.is_valid(): instance = partnerForm.save(commit=False) instance.save() for form in formset.cleaned_data: image = form['image'] product = Product(partner=instance, image=image) product.save() messages.success(request, "Partner Successfully Created") else: print partnerForm.errors, formset.errors else: partnerForm = PartnerForm() formset = ProductFormSet(queryset=Product.objects.none()) return render(request, "partner_form.html", {"partnerForm": partnerForm, "formset": formset}) here is my models.py class Partner(models.Model): name = models.CharField(max_length=120) logo = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") banner_image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") mission = models.TextField() vision = models.TextField() height_field = models.IntegerField(default=0) width_field = … -
Django Rest Framework creating instance instead of updating
I want to update the Profile instance for a user, by sending data to the url update_profile/ I am using: curl -X PUT -H "Authorization: Token sometoken" -d "name=somename&age=20&user=1" 127.0.0.1:8000/update_profile/ and the error I get is: {"user":["This field must be unique."]} It seems like the error comes because the request creates a new instance of Profile, when there is already another instance of Profile with that same user. But I just want to update the current Profile instance for the user. Any idea why my code does try to create a new instance instead of updating it? views.py class UserProfileChangeAPIView(generics.UpdateAPIView, mixins.UpdateModelMixin): permission_classes = ( permissions.IsAuthenticated, UserIsOwnerOrReadOnly, ) serializer_class = UpdateProfileSerializer parser_classes = (MultiPartParser, FormParser,) def get_queryset(self, *args, **kwargs): queryset = Profile.objects.filter(user=self.request.user) return queryset def get_object(self): self.request.user.profile def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) def update(self, request, pk=None): try: self.request.user.profile except Http404: return Response( {'detail': 'Not found'}, status=status.HTTP_404_NOT_FOUND) return super(UserProfileChangeAPIView, self).update(request, pk) urls.py url(r'^update_profile/$', UserProfileChangeAPIView.as_view(), name='update_profile'), serializers.py class UpdateProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ 'name', 'age', 'user', ] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) age = models.PositiveIntegerField(null=True) -
Play song audio with django
I have this projet, where users can add songs, and everyone else can play it to listen to the audio (mp3). The problem is, I don't know how to make it play. <td> <button type="button" class="btn btn-success btn-xs"> <span class="glyphicon glyphicon-play"></span>&nbsp; Play </button> </td>