Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail: render a page programmatically in a Class Based View
I've got a Wagtail setting where a user can select a page to render, and if it is not set, it returns a listing page using ListView of recent posts. Here is the setting: @register_setting class PeregrineSettings(BaseSetting): """ Settings for the user to customize their Peregrine blog. """ landing_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, help_text='The page to display at the root. If blank, displays the latest posts.' ) The setting works. When I try to use it in the ListView, I'm attempting to pass the url_path to Wagtail's serve method, but it doesn't render the page view; I get a 404. Here's the code of the ListView: class PostsListView(ListView): """ Paginated view of blog posts. """ model = SitePost template_name = 'peregrine/site_post_list.html' context_object_name = 'posts' paginate_by = 10 ordering = ['-post_date'] def get(self, request, *args, **kwargs): peregrine_settings = PeregrineSettings.for_site(request.site) if peregrine_settings.landing_page is None: # Render list of recent posts response = super().get(request, *args, **kwargs) return response else: # Render landing page serve(request, peregrine_settings.landing_page.url_path) It feels like I'm missing a way to just pass the Page instance stored in peregrine_settings.landing_page to a method to render. Can anyone shed some light on the internals at work here? Thank you! -
Test Application Keys for Twilio Authy Client
I am using Python Client for Twilio Authy API (https://github.com/authy/authy-python). To create a new Connection Instance the following is used: from authy.api import AuthyApiClient authy_api = AuthyApiClient('#your_api_key') For testing purposes, are test Application Keys available that do not necessarily send the OTP to phone but gives the appropriate responses? Where or how do I get this test Application Key? -
Django Iterating over Many to Many Objects
My main problem is that my code never goes into the for loop though within the debugger I can see that hardware exists. The for loop gets just skipped and I can´t figure out why this is the case. Models: class Hardware(models.Model): name = models.CharField(max_length=30) description = models.TextField() class Bundle(models.Model): name = models.CharField(max_length=30) description = models.TextField() devices = models.ManyToManyField(Hardware) class BundleForm(ModelForm): class Meta: model = Bundle fields = ('name', 'description', 'devices') labels = { 'name': _('Bundlename'), 'description': _('Beschreibung des Bundle'), 'devices': _('Hardware im Bundle') } Views: elif request.method == 'POST' and 'newbundle' in request.POST: form = BundleForm(request.POST) if form.is_valid(): bundle = form.save(commit=False) bundle.save() for hardware in bundle.devices.all(): print(hardware) messages.success(request, 'Erfolg! Die Daten wurden erfolgreich gespeichert.') return redirect('/knowledgeeditor/bundle/', {'messages': messages}) -
How to fix Django "NoReverseMatch" Error
I have built a simple blog app with Django and I have had some issue with NoReverseMatch. here are my problem screenshot: 1. https://prnt.sc/imqx70 2. https://prnt.sc/imqwpt Here is my code on Github: https://github.com/nafiulhasanbd/Django_blog_app Can anyone please explain. Thank you Best Regards Nafiul Hasan -
Multiline Charfield Django
How can I make a multi-line CharField in a model form in Django? I don't want to use Textarea, as I want the input to be with limited length. The question is about the field 'description' This is my model: class Resource(models.Model): type = models.CharField(max_length=50) name = models.CharField(max_length=150) description = models.CharField(max_length=250, blank=True) creationDate = models.DateTimeField(default=datetime.now, blank=True) And this is my form: class AddNewResourceForm(forms.ModelForm): class Meta: model = Resource fields = ("name","type","description") def __init__(self, *args, **kwargs): super(AddNewResourceForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class' : 'new-res-name', 'placeholder' : 'max 150 characters'}) self.fields['type'].widget.attrs.update({'class' : 'new-res-type', 'placeholder' : 'max 50 characters'}) self.fields['description'].widget.attrs.update({'class' : 'new-res- description', 'placeholder' : 'max 250 characters'}) -
How does one build an spa with webpack when deploying Docker container to Heroku
I'm developing an Aurelia Single Page App that will talk to a REST api built with Django Rest Framework. Without containers, I would have two buildpacks, one for Node that runs a script in the package.json file and another for Python that builds the Django app. If I push a container image, then what mechanism replaces the node buildpack that calls the script in package.json to trigger webpack to create the asset bundles? -
How to separate a Django app in order to make part of its GitHub repo private
I have hired a contractor to do some web development work on my app and would like to only give them access to certain parts of my GitHub repo (I would like to keep the Python utility files private). The stack is Python/Django/GitHub/Heroku. Based on other SO posts, it sounds like the solution is to create two GitHub repositories, one which is public and the other which is private, and then manage these two repos via Git. The problem is that if I move the Python utility files to another repo, outside of my Django root project, then I'm not sure how to import those files into my Django project. I went down the route of moving the Python files to an external location and then trying to import them via sys.path.append('/mypath') in the Django settings file and alternately tried packaging my python files into a separate module and then installing it via pip but have run into issues with both of these methods. Is there a suggested approach for how to best separate these two parts of the code base, such that the Django project is able to import the Python files? -
How to get user details using JWT token
I'm using angular 5 front end and django as back end. I use JWT token to communicate between django to angular. How can I get logged user details in backend using token. EG: class PostSerializer(ModelSerializer): class Meta: model = PostDetail fields = [ 'title', 'upvote', ] Here upvote is a many to many field contain all voted user list. I want to add one more field "user_vote_status" to check the vote status of logged in user. How can I figure out this issue, please help me. -
how to call some logic in my views after rendering template in django
I am using form.py and the user is typing some Email-id, let us say I want to send an email to that particular email and write all that email into google sheet using gspread, I am able to do this in my views.py, but the problem is it's taking a lot of time to write which slow down the rendering process. Is there any other way I can use my logic after rendering the template. -
Django how to update object with multiple fields which is already saved in Database
I'm trying to create a logic in Django which checks if User had already provided certain information. If not then it creates new object and save in the databse. And information was already there then it updates the same object with the new information. I'm making some mistake because it is able to create a new object but not updating it. try: # Check if user already have data available data_created_or_not = UserUsageInfo.objects.get(user_id=request.user.id).data_available_or_not except Exception: # If not available than, make it false data_created_or_not = False if not data_created_or_not: # If its False then create new object UserUsageInfo.objects.create(user=request.user, space_used=used_space, space_allocated=allocated_space, folders_list=folders, files_list=files, files_hash_list=files_hash, data_available_or_not=True ) else: # If already there then update it UserUsageInfo.objects.update(user=request.user, space_used=used_space, space_allocated=allocated_space, folders_list=folders, files_list=files, files_hash_list=files_hash, data_available_or_not=True ) -
ImproperlyConfigured: Field name `address` is not valid for model `User`
I am trying to overide Djoser User registration serializer to add a custom field to user model. Following is my models.py from django.db import models class User(models.Model): email = models.CharField(max_length=100, blank=False) first_name = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=30, blank=True) password = models.CharField(max_length=100, blank=False) and my serializers.py looks like follwing: from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer class UserRegistrationSerializer(BaseUserRegistrationSerializer): class Meta(BaseUserRegistrationSerializer.Meta): fields = ('url', 'id', 'email', 'first_name', 'address', 'password') and this is my view.py from User.models import User from User.serializers import UserRegistrationSerializer from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserRegistrationSerializer I have configured Djoser configurations in setting.py in following way DJOSER = { 'SERIALIZERS': { 'user_create': 'User.serializers.UserRegistrationSerializer', }, } I am getting following error when I try to create a new user I ran makemigration and migrate but error is still there. any help is appreciated :) -
CSV to sqlite import
Trying to import an existing csv into a table that will have blank elements but they're already allowed to have nulls and blanks. It seems no matter which approach I take I get binding errors or a syntax error on the %s portion of the insert. The Csv has four elements and does not include column headings. import csv, sqlite3,sys con = sqlite3.connect('db.sqlite3') cur = con.cursor() query="""INSERT INTO adm_Appointment(sch_time, operation_id, surgeon, pat_name) VALUES(%s,%s,%s,%s)""" with open('dailypatientlist.csv','r') as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader) for line in reader: elements="line[0],line[1],line[2],line[3]" cur.execute(query,(elements,)) con.commit() con.close() -
Why pip freeze >requirements.txt return Permission denied
When I worked in a virtual environment, I installed my packages django-2.0 there. Yet it is installed globally: sudo virtualenv -p /usr/bin/python3.5 ~/.virtualenv/venv source ~/.virtualenv/venv/bin/activate (venv) $ pip install django==2.0 And I had django-1.11 in my global environment before. However django-1.11 is also hoping to be installed into the other virtual environment, but it was also installed globally. I uninstall this package, and try to install it into my virtual environ again. but it seems like not work at all. All package installed newly were in global env. Now i want to use pip freeze >requirements.txt to get requirements file,but it return : (venv) $ pip3 freeze >requirements.txt bash: requirements.txt: Permission denied (venv) $ sudo pip3 freeze >requirements.txt bash: requirements.txt: Permission denied I thought maybe it was because that i install these package globally?I don't know. How can i install package into my virtual environment correctly, and get requirement file:( -
Django update or delete own made data only
Trying to add permissions on a django form. User created own instances. That data only updatable/deletable if the creator trying to do action. I'm using generic updateview. Thanks in advance -
django multi form and file field
I am currently using several differents forms on a single view. I am able to fill my forms but when i submit one of them, it seems that my form is unvalid. I displayed the request.POST (it contains all my informations) and my form (it is empty but i don't understand why) Could you explain me how to correct it? Could it be linked to my models? (I am using bootstrap 3 through django) my view : def view_addfiles(request): try: print(request.POST) except: {} if request.method == 'POST' and 'search' in request.POST: print("recherche") recherche=searchbar(request.POST, prefix='search') if recherche.is_valid(): print("recherche") else : recherche=searchbar(prefix='search') if request.method == 'POST' and 'film' in request.POST: print("film") addfilm=Addfilms(request.POST,request.FILES, prefix='film') print(addfilm) if addfilm.is_valid(): print("film") return redirect(view_accueil, inscription=3) else : print("dfsd") addfilm=Addfilms(prefix='film') if request.method == 'POST' and 'serie' in request.POST: print("serie") addserie=Addseries(request.POST,request.FILES, prefix='serie') if addserie.is_valid(): print("serie") return redirect(view_accueil, inscription=3) else : addserie=Addseries(prefix='serie') return render(request, 'menuAjout.html',locals()) my html : <form action="{% url "add_files" %}" method="post"> {% csrf_token %} {{ recherche.as_p }} <input type="submit" id="validation" name="search"/> </form> <div id="films"> {% load bootstrap3 %} {% bootstrap_css %} <form action="{% url "add_files" %}" method="post"> {% csrf_token %} {% bootstrap_form addfilm %} {% buttons %} <button type="submit" class="btn btn-primary" id="submitbutton" name="film" value="submit"> {% bootstrap_icon "star" … -
What should I use to create a drag and drop form that allows users upload image and then display it?
I use Django and want to create a form that get an image, upload it to the server and then display it on the same page. This should work without user authentication. Appreciate any directions. -
Website in Angular, django and Firebase
Is it possible to create a web application which use Angular as view, django as Controller and firebase Nosql database as modal. If it is possible what are gonna be the benefits and drawbacks of this approach. -
How To Save A User's Favorite Posts in Django
So, i'm trying to allow a user to favorite a post (in my case Deals), which will later be displayed on their profile page. The problem I'm having --If I look in the Django admin, under a specific user for the 'favorites' field, ALL of the Deals are appearing. I got my initial inspiration from this post here So i added a 'favorites' field to my User model with a Many to Many relationship on my Deal model...like so: favorites = models.ManyToManyField(Deal, related_name='favorited_by') My html template where a user can favorite a 'Deal' looks like this: <form id="favorite{{deal_detail.id}}" method="POST" action="{% url 'deals:favorite' deal_detail.id %}"> {% csrf_token %} <input type="hidden" name="supporttype" /> <input type="submit" value="Add Deal to Favorites" /> My url for favorites is this: url(r'^(?P<pk>[0-9]+)/favorite', favorite, name='favorite') this is the view for 'deal_detail' and 'favorite' def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) def favorite(request, pk): if request.method == 'POST': deal = Deal.objects.get(pk=pk) deal.save() messages.add_message(request, messages.INFO, 'Deal Favorited.') return redirect('home') -
how to authenticate users in Django rest framework?
I have added some URLs in my Django API for posting deleting and putting data and I don't know how to authenticate users first and give some of them to use these methods and ban some of them -
urls.py django 2.0.2 need parameters
i'm learning django and i'm making a blog tutorial but it's from older version that i have, i have version 2.0.2 and i'm not understand documentation my problem is that i dont know how configure my urls.py this is my three proyect: i need to put archive.html in 127.0.0.1:8000/ and this is my urls code codigofacilito/blog.urls.py : """codigofacilito URL Configuration The urlpatterns list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), ] and codigofacilito/codigofacilito.urls.py: from django.contrib import admin from django.urls import path from . import views enter code hereurlpatterns = [ path('admin/', admin.site.urls), ] -
Django REST Framework, limiting fields on foreignkey relationship when serializer depth = 1
I am using the Django REST Framework and I have a serializer as follows: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile depth = 1 fields = ['user','team','correct','wrong','percentage'] The problem if this passes all user data (including a hashed password). How do I limit the fields being passed? I have a UserSerializer as follows (which holds the only fields I really want): class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['first_name','last_name','username'] -
Django Sign Up with extra fields
I have expanded my SignUp form with UserCreationForm and make email activations. And all works perfect, but I don't understand how I address the new variable. I can't display it in a template and I do not find it in the user admin panel. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from customuser.models import User class SignUpForm(UserCreationForm): phone = forms.CharField(max_length= 20) #<--my new variable class Meta: model = User fields = ('phone', 'email', 'password1', 'password2',) views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('reg/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignUpForm() return render(request, 'reg/signup.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('index') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') … -
Disable CSRF on api view method(django rest framework)
I have such api method: @api_view(['POST']) @login_required def get_posts(request): # ... How can I disable CSRF only on this method? -
module 'uritemplate' has no attribute 'variables'
I am getting this module 'uritemplate' has no attribute 'variables' using corepai Schema Generator in Drf probably not working -
How can I compare two Django QuerySets and return QuerySet with replacement of the same values from second in first?
My env is Django 2.0.2 and Python 3.6.1. How can I compare two Django QuerySets and return QuerySet with replacement of the same values from second in first? For example, I have QuerySets: >>> qs_local = PriceLocal.objects.filter(user_id=request.user.id) >>> print(qs_local) [{ 'user_id': 1, 'product_id': 1, 'price': 100 }] >>> qs_world = PriceWorld.objects.all() >>> print(qs_world) [{ 'product_id': 1, 'price': 300 }, { 'product_id': 2, 'price': 500 }, ... ] I want to compare this Django QuerySets and return QuerySet, like this: [{ 'product_id': 1, 'price': 100 }, { 'product_id': 2, 'price': 500 }, ...] At this point, we are replacing the same records (with 'product_id': 1) from second to first QuerySet.