Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect - not a valid view function or pattern name error
I'm a newbie in Django and am trying to set up a simple contact form which redirects to a thank you page on successful submission. I'm having trouble getting it to redirect to the thanks page after submission and getting the below error: NoReverseMatch at /contact/ Reverse for 'thanks' not found. 'thanks' is not a valid view function or pattern name. This is my urls.py app_name = 'home' urlpatterns = [ url(r'^$', views.HomePageView.as_view()), url(r'^contact/$', views.ContactView, name='contact'), url(r'^thanks/$', views.ThanksView, name='thanks'), ] and my views.py def ContactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, 'contact.html', {'form': form}) def ThanksView(request): return render(request, 'thanks.html', {}) I added the templates directory in my settings.py TEMPLATES = [ { 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, '/home', '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', # Third Party Apps 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', # <-- ], }, }, ] Can someone please point out where I'm making a mistake? Thanks! -
What is the equivalent of Django's DecimalField in Java?
I have an Android app which communicates with a Django backend. I am currently using DecimalField to represent money related variables, like: from django.db import models ... fee = models.DecimalField(max_digits=10,decimal_places=3) Is there an equivalent data type in Java I can use, or should I send the number in two parts(decimal part and fraction part separately)? -
Different logic for serializer on get and create
I want to use one serializer in order to create comments and get list of them. Here is my comment serializer: class CommentSerializer(serializers.ModelSerializer): creator = UserBaseSerializer(source='author') replies = ShortCommentSerializer(many=True, read_only=True) reply_on = serializers.PrimaryKeyRelatedField( queryset=Comment.objects.all(), write_only=True, allow_null=True, required=False ) author = serializers.PrimaryKeyRelatedField( queryset=get_user_model().objects.all(), write_only=True ) class Meta: model = Comment fields = ('id', 'text', 'object_id', 'creator', 'replies', 'reply_on', 'author') extra_kwargs = { 'text': {'required': True}, 'object_id': {'read_only': True} } def create(self, validated_data): validated_data.update( {'content_type': self.context['content_type'], 'object_id': self.context['pk']} ) return Comment.objects.create(**validated_data) My Comment model has field author which is FK to User model. On GET method I'm returning creator as NestedSerializer with source='author'. Also I got author field for write only purposes. I'm trying to figure out is it possible to use author field both for read and write. -
how to use id from 1 function to another in django views.py
how to use id from 1 function to another in django views.py How to use id which i used in this line id = (logininfo.objects.get(user_name=request.POST.get("username")).id) to another function def home3(request) t = logininfo.objects.get(id = id)//how in this line def home2(request): if request.method=="POST": password=request.POST.get("password") user_name=request.POST.get("username") id = (logininfo.objects.get(user_name=request.POST.get("username")).id) context = { 'id': id, } user_obj=logininfo.objects.filter(user_name=user_name,password=password) if user_obj.count()==0: return HttpResponse("Sorry wrong password try again") return render(request,'home.html',context) def home3(request): t = logininfo.objects.get(id = id) context = { 'balance': int(t.balance), } return render(request, "viewBalance.html", context) -
Protecting user's model view from other users
I'm trying to write a generic DetailView for my model (which is related to User), but I don't know how to limit access for specific model (view) for only that User (owner). I've looked into docs but haven't found any guide how to do that the proper way. So far I've managed to overwrite test_func() method of the class using UserPassesTestMixin where i check if object.user == self.request.user but I'm not sure if that's the proper way to do that. What I've just said may not be clear, so e.g. Model A of id 4 is related (owned by) User A. Now, if User B tries to request Model A DetailView (/models/4) he should be rejected with 403 Error Code, or even better, custom error page. -
how to access field using django signals
I would like to check the value of a field (lightStatusA) when a new record is saved into my Django database. I feel like iv'e read the docs 10 times and still can't grasp how to get this. Here is my current models.py code: from django.db import models from accounts.models import Customer from django.conf import settings from django.contrib.auth import get_user_model from django.db.models.signals import post_save class Data(models.Model): author = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,) tempData= models.CharField(max_length=50,blank=True,) humidData= models.CharField(max_length=50,blank=True,) lightStatusA= models.BooleanField(default=True,) dateTime = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.author) def check_light_status(sender, **kwargs): if kwargs['created']: #make sure its a new record #need logic to grab instance.lightStatusA and check it's value post_save.connect(check_light_status, sender = Data) Is there some way of passing this value as an argument to the signal? -
Django: Assign options to model
I have a form with fields. The view consists of html-options. They should be always updated, because maybe someone is saving something on another tab. The html-options shows all my models (the text is self-assembled through the value of "name" and "adress" in Wohnungseinheiten) which doesn't have filled the column "GROUP". It also shows the text-option "add a new group", because I want to redirect to a page to create the model. When I choose a model from the options, then I want to assign the model in the column "GROUP". How can I assign text to the model ("add new Wohnungseinheiten" means that it has NONE)? My Trial: <script> $(document).ready(function() { $.ajaxSetup({ cache: false }); var my_refresh = setInterval(function() { $('#output_box').load('user/mietgruppe/mietgruppe_answer/'); }, 1000); }); </script> <form class="form-signin" action="mietgruppe" method="post">{% csrf_token %} <input class="form-control" name="wohnungsgruppenname" type="text" placeholder="Mietgruppenname"> <select class="form-control" name="wohnungseinheiten"> <option>Neue Wohnung anlegen</option> <div id="output_box"></div> </select> <button type="submit" class="btn btn-primary mb-2">Submit</button> </form> class Wohnungsgruppe(model.Models): wohnungsgruppenname = models.CharField("wohnungsgruppenname",max_length=100, unique=True) wohnungseinheiten = models.ForeignKey(Wohnungseinheiten,blank=True,on_delete=models.SET_NULL,null=True) class MietgruppeCreationForm(forms.ModelForm): wohnungsgruppenname = forms.CharField(required=True,max_length=100) wohnungseinheiten = forms.CharField(required=True,max_length=100) def save(self, commit = True): m = super().save(commit) if wohnungseinheiten == "Neue Wohnung anlegen": setattr(self, 'wohnungseinheiten',None) if commit: m.save() return m class Meta: model = Wohnungsgruppe fields = ('wohnungsgruppenname','wohnungseinheiten') -
How to authenticate Office365 users using OAuth2.0 where username is alias?
I have a product where I have implemented OAuth2.0 for Office365. Users with their O365 accounts login into my product. For example, user1@domain.org can login into their O365 account and gets redirected to my product after the authentication is successful. I am storing their email address in my database to uniquely identify the users. Recently, one of the organization has asked their users to start using email alias to login to O365. The problem is that when authentication is successful and call gets redirected to my product, my code tries to match the username stored as user1@domain.org with the alias they have used to sign into Office365. Since there is a mismatch, my product gives an error saying there is id mismatch. I want to know if there is an API which can return a list of all alias that user is using or is there a better way to handle such situations? Any comments appreciated, thanks. -
How to make radio buttons in Django admin
Does Django itself provide radio button models? I was trying to find out how to make radio buttons in Django admin, but since there is nothing related to that, It seems like Django doesn't have radio buttons as default. -
django in post_save signal DecimalField become float type
models.py from django.db import models from django.db.models.signals import pre_save, post_save class Order(models.Model): total = models.DecimalField(default=0.00, max_digits=20, decimal_places=2) def post_save_order(): if created: print(type(instance.total)) # here post_save.connect(post_save_order, sender=Order) I think the 'total' field shoule be Decimal type, but when I save a Order instance, it always print < class 'float'>. I know I can use 'decimal.Decimal' to convert it, I just wonder why it behaviors like this. Thanks. -
UpdateView from django tutorial does not save files or images
UpdateView does not save files or images anywhere, what can be the problem? settings: MEDIA_ROOT="" article_form.html: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> views.py: from django.views.generic.edit import UpdateView class updatingexample(UpdateView): model = Article fields = ['file1','file2','photo'] url.py app_name = 'polls' urlpatterns=[ path('<int:pk>/upd/', updatingexample.as_view(),name="ugh") ] models: class Article(models.Model): title = models.CharField(max_length=200) pub_date = models.DateField() file1 = models.FileField(upload_to='uploads/',blank=True) file2 = models.FileField(upload_to='uploads/%Y/%m/%d/',blank=True) photo = models.ImageField(upload_to='uploads',blank=True) def get_absolute_url(self): return reverse('polls:ugh', kwargs={'pk': self.pk})#back to itself -
search and replace file text with code with single quotes inside python string
I'm have with a question in the last two days. I'm trying search and replace part of text file with single quotes, bur I'm receiving an error. log: Traceback (most recent call last): File "./vhost.py", line 194, in <module> """.format(db_name=_db_name, db_user=_db_user,db_pass=_db_pass, db_host=_db_host) KeyError: "\n 'default'" I think the problem are in 'default'" The code: if _create_database == "Y" or _create_database == "y": _backendmysql = """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '{db_name}', 'USER': '{db_user}', 'PASSWORD': '{db_pass}', 'HOST': '{db_host}', # Or an IP Address that your DB is hosted on #'PORT': '3306', } } """.format(db_name=_db_name, db_user=_db_user,db_pass=_db_pass, db_host=_db_host) _backendsqlite = ''' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ''' try: with fileinput.FileInput(strSettingsPath, inplace=True, backup=None) as file: for line in file: print(line.replace(bytes(_backendsqlite, 'UTF-8'), bytes(_backendmysql, 'UTF-8') , end='')) except Exception as e: raise e # ----------------------------------------------------------------- -
Python Django urls not working how they should?
from django.contrib import admin from django.urls import path import main.views urlpatterns = [ path('', main.views.index, name="index"), path('story/', main.views.story, name="story"), path('haxs/', main.views.haxs, name="haxs"), path('contact/', main.views.contact, name="contact"), path('admin/', admin.site.urls), ] . <li class="nav-item"><a class="nav-link" href="/">home</a></li> <li class="nav-item"><a class="nav-link" href="story/">our story</a></li> <li class="nav-item"><a class="nav-link" href="haxs/">haxs</a></li> <li class="nav-item"><a class="nav-link" href="contact/">contact us</a></li> I am working on a python django website and my urls are not working properly. I have included my urls.py and the nav links which are the same on each page. From home I can go to all the other pages and from the other pages I can go back to home. My problem is when I go from for example: haxs to contact it does not work and the code url becomes "http://127.0.0.1:8000/haxs/story/" when it should just be "http://127.0.0.1:8000/story/" . It is like that with our story/haxs/contact, I can not go between them pages. How do I fix this? -
Python mixin/decorator/__metaclass__ for base class enhancement
I am implementing a content-aware caching system for a Django REST API. I would like to develop a component which can be added to existing views that would modify the behavior of the base class by checking the cache and falling back to the base class behavior on a miss. basically, I have something like this: class Base: def get(self, request, *args, **kwargs) .... return Response class Derived(Base): pass and my initial thought was to do something along the lines of class Cacheable: def get(self, request, *args, **kwargs): cache_key = self.get_cache_key(request) base_get = #.... and this is the problem return cache.get(cache_key, base_get(request, *args, **kwargs)) def get_cache_key(self, request): # .... do stuff So clearly this doesn't work, as I don't know how, or if it's possible, or if it's advisable to access the sibling superclass(es) from a mixin. Is it more appropriate to use method decorators? or would a class decorator be more appropriate. And then I've seen references to __metaclass__ in researching this, but I'm not clear on what that approach looks like. This is Python 3.6 -
Django empty_label for ModelMultipleChoiceField. Multiple values for keyword argument 'empty_label'
I'm trying to put a placeholder in a Select2 field, by putting an empty_label in the field. Now i get the error: TypeError: init() got multiple values for keyword argument 'empty_label' What do i have to change? Here is my code: self.fields['work_types'] = ModelMultipleChoiceField( queryset=WorkTypes.objects.filter( white_label_client=logged_in_user.white_label_client, deleted=False), empty_label='Type', required=False) Thanks in advance Jim -
Using Django and Bootstrap4, the input field does not render nicely
I am using Bootstrap4 w/ Django and created a CSS class named 'field': .field{ box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; outline: none; display: block; width: 100%; padding: 7px; border: none; border-bottom: 1px solid #ddd; background: transparent; margin-bottom: 10px; font: 16px Arial, Helvetica, sans-serif; height: 45px; } This is what it should look like: screenshot 1 However, it renders like this: screenshot 2 See how in the 2nd screenshot the text field still has a border? How can I change / adjust this so it looks like in the first screenshot? -
Send Mail Using Django Framework and Mail may contain HTML,CSS and Javascript File
I am trying to send mail which may contain some HTML page using python as Backend. My HTML page may contain some external js file. Let's assume it includes <script src="http://cdn.bootcss.com/echarts/3.2.2/echarts.min.js"></script>. When I am sending mail using django.core.mail.backends.smtp.EmailBackend then it is loading HTML but in my mail, it is not able to use the function of echarts.min.js and HTML is not loading properly in Mail. I have read some of the articles and some of the articles are indicating the problem of loading js file in mail, but how come the company sends us mail which contains several images, CSS and js file. -
How do I include model in Django Model Serializer?
Let's say I have this model and serializer: class Animal(models.Model): id = models.AutoField(primary_key=True) data_url = models.TextField(unique=True) class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = '__all__' If I run: animal = Animal.objects.filter(id=1).first() data = serializers.serialize("json", animal) I get a json string that looks like this: [{"model": "zoo.animal", "pk": 1, "fields": {"id": "1", "sound": "woof"}] Now if I run: animal = Animal.objects.filter(id=1).first() animal_serialized = AnimalSerializer(animal) animal = JSONRenderer().render(animal.data) I get a json string that looks like this: b'[{"id":1,"sound":"woof"}]' However, this json string is missing the "model" and "pk" and "fields" dictionaries, its just the fields. How to get make my AnimalSerializer return this data as well, as it does when I run serializers.serialize("json", animal)? -
Auto-detect the logout in browser tabs?
I have multiple tabs opened of a website in a browser. My question is if I logout from one window "How do other windows will detect that user has been logged out?" I am using python/django for development The approach I am using is: function user_checking(){ $.ajax({ url: /check_user_login, type: 'POST', success: function (data) { if (data['user_status'] == 'not_loggedin'){ location.reload(); } }, error: function (data) { }, }); //ajax end } var validateSession = setInterval(user_checking, 1000); I am sending user_checking() every second to check if the user is logged out or not. Is this the right approach ? -
Django Form Adding New Database Entries Erroneously
Disclaimer: Relatively new to Djano so forgive any shortcomings in the question. I have a simple form with a DAL field and I'm trying to submit the form value id and slug to render detail page. DAL is providing results as expected. When submitted, I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'asset_detail' with arguments '(39526, '')' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)\\/(?P<slug>[-a-zA-Z0-9_]+)\\/$'] Note that the ids of existing data stop at 39499. That id (and 39500-39525) was generated upon submission. I don't want to add new entries to the database, but rather look up existing ones. See below for urls, form, views, model, and template: # models.py class CI(models.Model): ci_type = models.ForeignKey(Category, related_name='assets', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200,db_index=True) status = models.BooleanField(default=True) serial = models.CharField(max_length=140, blank=True) asset_tag = models.CharField(max_length=53, blank=True) model_source = models.CharField(max_length=54, blank=True) vendor = models.CharField(max_length=58, blank=True) support_level = models.CharField(max_length=60, blank=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('lookup:asset_detail', args=[self.id, self.slug]) # forms.py class AssetForm(forms.ModelForm): category = forms.ModelChoiceField( queryset=Category.objects.all(),) name = forms.ModelChoiceField( queryset=CI.objects.all(), widget=autocomplete.ModelSelect2( url='asset-autocomplete', forward=(forward.Field('category', 'ci_type'),))) class Meta: model = CI fields = ('name',) # views.py class AssetView(CreateView): model = CI form_class = AssetForm … -
select a id from django model
This is my views.py In first line of def home3(request): I am hard coding by writing id=1 i.e t = logininfo.objects.get(id=1) How to write in general so that it takes id of that user who logs in.. from django.shortcuts import render from django.http import HttpResponse from .models import logininfo,ministatement from django.shortcuts import render def home1(request): return render(request,'login.html') def home2(request): if request.method=="POST": password=request.POST.get("password") user_name=request.POST.get("username") user_obj=logininfo.objects.filter(user_name=user_name,password=password) if user_obj.count()==0: return HttpResponse("Sorry wrong password try again") return render(request,'home.html') def home3(request): t = logininfo.objects.get(id=1) context = {` 'balance': int(t.balance), } return render(request, "viewBalance.html", context) -
Django Channels Along with uWSGI
I currently, Django rest api which is developed using docker, nginx, uWSGI, redis, Django & Angular. I am adding couple of websocket endpoints, I would like to keep the existing architecture and keep serving http requests via uWSGI & nginx. And use Django channels (with nginx) for web-socket connections. Is that possible? If so, can I use just one container and start uWSGI and daphne on different ports ? Or do I need separate Django app for channels all together and separate container ? -
SSL: CERTIFICATE_VERIFY_FAILED Error in Django running through uwsgi on nginx webserver
I am running Django REST API project through uwsgi in nginx webserver. Also configured ssl for HTTPS. In project directory there are certificate & key files (as below), which helps to establish the secured HTTPS connection. /my-project/test-cert.pem /my-project/test-cert.KEY I have checked from browser, the https://mysite.domain.com/ is returning all the APIs, and the https://mysite.domain.com/admin/ is returning the Django Admin page. This means the Django is responding properly. I am actually facing error is calling my internal APIs through external web URLs. https://mysite.domain.com/api/account/ is my web url which will call the https://mysite.domain.com/user-list-details/api internally. Consider the below sample code: import request # I have tried with three different certificates available. CERT_1 = '/etc/ssl/certs/ca-bundle.crt' CERT_2 = '/my-project/test-cert.pem' CERT_3 = '/tech/lib/python3.5/site-packages/certifi/cacert.pem' url = 'https://mysite.domain.com/api/account/' apisession = requests.Session() response = apisession.get(url, verify=CERT_1) # <= Error in this line Error: HTTPSConnectionPool(host='', port=443); Max reties exceeded with url: /user-list-details/?query=all&name=Jhon (caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),)) I have tried using the bundle certificate, but for that I am getting 504 error. I tried verify=False though not recommended, but getting 504 error. I have checked similar posts as this: Python Requests throwing SSLError but didn't get any way out. I also learned from http://docs.python-requests.org/en/master/user/advanced/ The private key … -
How to mock the get_object method of a Django Rest Framework view?
I am playing with the build (as opposed to create) method of FactoryBoy in Django. This creates objects without storing them in the database. Therefore, in order for the tests of my views to work, I need to patch the methods that touch the database. Here is some code... models.py: class Book(models.Model): title = models.CharField(max_length=100) serializers.py: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('name') views.py: class BookViewSet(viewsets.ModelViewSet): def get_queryset(self): return Book.objects.all() def get_serializer_class(self): return BookSerializer tests.py: class BookFactory(factory.DjangoModelFactory): title = factory.Faker('sentence', nb_words=4) class Meta: model = "Book" def my_test(): client = APIClient() books = BookFactory.build_batch(10) list_url = reverse("books-list") with patch.object(BookViewSet, "get_queryset", return_value=books): list_url = reverse("books-list") response = client.get(list_url) # this works assert response.content = <a list of books> with patch.object(BookViewSet, "get_object", return_value=books[0]): detail_url = reverse("books-detail", args=123) response = client.get(detail_url) # this is always empty.. assert response.content == <a book> No matter what I try, the detail-view always returns empty JSON. Am I using patch wrong? -
Reverse for 'post_edit' not found. 'post_edit' is not a valid view function or pattern name
Reverse for 'post_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['\^edit/\(\?P(?P[^/]+)\\d\+\)/\$$'] Reverse for 'post_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['\^edit/\(\?P(?P[^/]+)\\d\+\)/\$$'] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from . models import Topic from django.views.generic.edit import CreateView,UpdateView from django.urls import reverse_lazy # Create your views here. class BlogListView(ListView): model = Topic template_name='home.html' class BlogDetailView(DetailView): model = Topic template_name='post_detail.html' context_object_name='anything_you_want' class BlogCreateView(CreateView): model = Topic template_name = "post_new.html" fields='__all__' class BlogUpdateView(UpdateView): model=Topic fields=['title','body'] template_name='post_edit.html' post_edit.html {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> <a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post </a> {% endblock content %} urls.py from django.urls import path from . import views urlpatterns = [ path('',views.BlogListView.as_view(),name='home'), path('post/<int:pk>', views.BlogDetailView.as_view(),name='post_detail'), path('post/new', views.BlogCreateView.as_view(),name='post_new'), path('post/<int:pk>/edit/', views.BlogUpdateView.as_view(), name='post_edit'), ] models.py from django.db import models from django.urls import reverse # Create your models here. class Topic(models.Model): title=models.CharField(max_length=200) author=models.ForeignKey('auth.User',on_delete=models.CASCADE,) body=models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("post_detail", args=[str(self.id)]) ![Error]: https://i.imgur.com/2LoDxtS.png ![Error]: https://i.imgur.com/o6WHFFe.png