Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No Post matches the given query.in django
am using django 2.0 and here is the problem Page not found (404) Request Method: GET Request URL: http://localhost:8000/blog/post-detail/ Raised by: blog.views.post_detail No Post matches the given query. here is the blog/urls from django.urls import path,include from .import views urlpatterns = [ path('blog/',views.post_list,name="post_list"), path('blog/post-detail/',views.post_detail,name="post_detail"), ] and views.py from django.shortcuts import render,get_object_or_404 from.models import Post # Create your views here. def post_list(request): object_list=Post.objects.all() context={ 'object_list': object_list, } return render(request,"blog.html",context) def post_detail(request,slug=None): post=get_object_or_404(Post,slug=slug) context={ 'post':post, } return render(request,"post_detail.html",context) and the post_detail.html {% extends "base.html" %} {% load static %} {% block seo_title %}{% endblock %} {% block seo_description %}{% endblock %} {% block Content %} <article> <div class="embed-responsive embed-responsive-16by9"> <img src="images/blog1.jpg" alt="" /> </div> <div class="post-content"> <h2>{{post.title}}</h2> <div> {{post.created}} Author {{Post.user}} <hr/> <p>{{post.body}}</p> </article> {% endblock Content %} CAN ANYONE HELP ON THIS THE ONLY PROBLEM I SEE THAT SLUG THING I MUST HAVE CONFUSED SOMEWHERE blog.html <!-- Blog --> <div class="blog"> <div class="row"> <div class="col-sm-8"> <!-- Blog Post--> {% for obj in object_list %} {% if obj.status == 'Published' %} <article> <div class="embed-responsive embed-responsive-16by9"> <img src="images/blog1.jpg" alt="" /> </div> <div class="post-content"> <h2>{{obj.title}}</h2> <div> {{obj.created}} Author {{obj.user}} <hr/> <p>{{obj.body}}</p> <a class="mtr-btn button-navy ripple" href= "{% url 'post_detail' slug= post.slug %}">Continue reading →</a><br> … -
Form is not valid django
I'm getting this error and I can't see why. I'm filling the form and it says that I'm not. Ask for more code if you needed it please. class="errorlist"><li>name<ul class="errorlist"><li>This field is required.</li></ul></li></ul> in forms: from django import forms class WorkFlowForm(forms.Form): name = forms.CharField(max_length=128, help_text="Please enter the workflow name.") in view: def workflow_search_form(request): form = WorkFlowForm(request.POST) if request.method == 'POST': print form if form.is_valid(): return workflow_search(request, form.cleaned_data['name']) else: print(form.errors) return render(request, 'find/list.html', {'form': form}) in html: <form id="WorkFlowForm" method="post" action="/find/workflow_search/"> {% csrf_token %} {% for field in form.visible_fields %} {{ field.errors }} {{ field.help_text }} {{ field }} {% endfor %} <input type="submit" name="name" value="Buscar workflow"/> </form> in urls: from django.conf.urls import url from find import views urlpatterns = [ url(r'^$', views.workflow_list, name='workflow_list'), url(r'^workflow_list_by_category/(?P<category_slug>[\w\-]+)/$', views.workflow_list, name='workflow_list_by_category'), url(r'^workflow_detail/(?P<id>[^/]+)/(?P<slug>[^/]+)/$', views.workflow_detail, name='workflow_detail'), url(r'^workflow_search/$', views.workflow_search_form, name='workflow_search'), ] -
Django Search function
How do I provide a search bar in django? My code is as follows... home.html <form method='GET' action=""> <input type="text" name="search" placeholder="Search posts"/> <input type="submit" value="Search"/> </form> views.py def home(request): posts = Post.objects.all() search_term = '' if 'search' in request.GET: search_term = request.GET['search'] posts = posts.filter(text__icontains=search_term) context = { 'posts': posts, 'search-term': search_term } return render(request, 'feed/home.html', context) -
Django REST Framework Serialization POST is slow
I am running on Django 2.1.1 and Python 3.6.5 and am performing a reasonably large POST operation (32,000 JSON objects). I have the following: Model: class Data(models.Model): investigation = models.ForeignKey(Investigation) usage = models.FloatField() sector = models.CharField(max_length=100, blank=False, default='') cost = models.FloatField() demand = models.FloatField() Serializer: class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('investigation', 'usage', 'sector', 'cost', 'demand') View: class DataView(generics.CreateAPIView): def create(self, request, pk, format=None): data_serializer = DataSerializer(data=request.data, many=True) if data_serializer.is_valid(): data_serializer.save() The problems come at both the is_valid() and save() steps which each fire off a separate query for each of the 32,000 objects. I've spent a long time looking into the issue and I'm guessing that the is_valid() step is slow because of the N+1 query problem since the foreign key is being looked up each time (although I could be wrong about this!) but I have no idea how to implement the prefetch_related method in this framework. The save() step (which is the slowest part) obviously needs to be done in one query (probably a bulk_create) but I can't find where to add the bulk_create step in. I've read this question but am still none the wiser from the answer. I tried to create a … -
Comparing enums fails in django
I have the following enum, class RoomType(enum.Enum): A = 1 B = 2 C = 3 D = 4 Then I have the following logic, if room.room_type is RoomType.A or room.room_type is RoomType.B: //do something else: //do something else or if room.room_type == RoomType.A or room.room_type == RoomType.B: //do something else: //do something else I have ascertained my object is RoomType A or B, but still the code always enters the else block. Can someone help with this? -
IntegrityError at /products/new/ NOT NULL constraint failed: products_product.user_id
I am creating a marketplace where selected users can have their shop and CRUD their products. I am running an error when creating the Createview class. I need the form where user adds a new product, returns his own shop name based on the shop model, but looks like there is an error as above. Following is my app: models.py class Shop(models.Model): shop_name = models.CharField(max_length=120) owner = models.OneToOneField(User,on_delete=models.CASCADE, related_name="owner") def __str__(self): return self.shop_name class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) shop = models.ForeignKey (Shop, on_delete=models.CASCADE, related_name='shop') category = models.ForeignKey(Category, verbose_name ='Categoria',on_delete=False ) title = models.CharField(max_length=120) slug = models.SlugField(blank= True, null=True, unique = True) views.py class ProductCreateView(LoginRequiredMixin,SubmitBtnMixin, CreateView): model = Product form_class = ProductForm template_name = 'form.html' success_url = '/products/list' submit_btn = 'Add Product' def form_valid(self, form): new_product = form.save(commit=False) user = self.request.user s = Shop.objects.get (owner=user) new_product.shop = s new_product.save() return super (ProductCreateView, self).form_valid(form) FORM.PY class ProductForm(ModelForm): class Meta: model = Product fields = ['category', 'title', 'description', 'price', 'image'] exclude = ['shop'] -
Unit testing REST endpoints in Django
I am pretty new to Django and web development in general. I decided to learn by creating a simple web app for posting and displaying college reviews. I have a number of GET and POST endpoints that I want to test. In the past, I have developed APIs where endpoints returned JSON objects that I could assert on when doing my API endpoint testing. However, in this case, my Django app returns HTML. The first issue I encountered was that my HTML sometimes contains dynamic values that I cannot assert on. For example, the csrf_token which is located in my forms. Here is part of the HTML file for the university details page: ... <form action="{% url 'university_add_review' university.id %}" method="post"> {% csrf_token %} <p>Date:</p><input type="date" name="date" id="date"/> <p>Summary:</p><textarea name="summary" id="summary">Enter your summary here.</textarea> <input type="submit" value="Submit"/> </form> ... In my unit tests, I want to check that a GET request to that page is getting the correct contents: def test_get_university_details(self): response = Client().get('/%s/overview/' % self.university.id) self.assertEqual(response.content, expected) Where expected is the expected HTML. However, that fails because the csrf_token is different in every GET request so I can't have an expected value for it. As a result this test … -
Having issues with AuthCanceled at /oauth/complete/google-oauth2/ Django Error
"Authentication process canceled (Having issues with AuthCanceled at /oauth/complete/google-oauth2)" Trying to setup google login for site and are running into this error. -
Django Jet Admin theme - Customize colors
currently i am working with django-jet and trying to change some colors in the admin using a custom theme. My setup: settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') app/static/jet/css/themes/my-theme/_variables.scss: $input-border-color: #000000; compiled it to css already, and back in my settings.py JET_DEFAULT_THEME = 'my-theme' but when i reload my django-admin there is absolutely no css in the admin. anybody ever had this issue? is there any documentation which covers in detail how to apply new scss to django-admin using django-jet (not the documentation provided)? thanks and greetings! -
slug error still comes after deleting django model
I had created a model in models.py but forgot to add the slug field. The error Key (slug)=() is duplicated comes after python manage.py migrate command. So I deleted my model and the slug field and again run the migration command but still the python manage.py migrate command shows the same error. I cannot delete my whole database because I have data stored in other models also. Here is the output of python manage.py showmigrations command: admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name schooldekho [X] 0001_initial [X] 0002_auto_20181114_0012 [X] 0003_auto_20181114_0041 [X] 0004_auto_20181114_0043 [X] 0005_auto_20181116_1759 [X] 0006_school [ ] 0007_school_slug [ ] 0008_auto_20181116_2259 [ ] 0009_auto_20181116_2300 [ ] 0010_auto_20181116_2304 [ ] 0011_remove_school_slug [ ] 0012_auto_20181118_2238 sessions [X] 0001_initial All I want is to run the migration successfully without any error. -
Django sqlite join query set based on condition
Models are given below: class Workspace(models.Model): wid = models.AutoField(primary_key=True, validators=[MinValueValidator(1000)]) wname = models.CharField(max_length=100) created_time = models.DateTimeField(auto_now_add=True) class Invitation(models.Model): iid = models.AutoField(primary_key=True, validators=[MinValueValidator(1000)]) invite_to = models.ForeignKey(User, related_name="invitation_uid2", on_delete=models.CASCADE) workspace = models.ForeignKey(Workspace, related_name="invitation_wid", on_delete=models.CASCADE) created_time = models.DateTimeField(auto_now_add=True) I need to get the list of workspaces based on invite_to "select * from Workspace where wid in (select workspace from Invitation where invite_to = 1)" The above query in ORM type -
flatten python tuple - django field options optgroups
I've been looking for a way to flatten a field's options in django that is structured as optgroup nested tuples: CHOICES = ( ('', ( ('value1', 'label1'), ('value2', 'label2'), ) ), ('Group2', ( ('value3', 'label3'), ('value4', 'label4'), ) ), ) What I want to achieve is a list containing only the values ['value1', 'value2', 'value3', 'value4']. I have tried itertools chain, zip and sum but I cannot get rid of the grouping labels, that is the empty string '' and 'Group2'. Any ideas? Thank you -
Input text field value behavior after Get request
I have this form <form class="form-inline" type="get" action="."> <input id="excel_input" class="form-control" type="text" name="excel_input" value="0"> <input class="btn" type="submit" name="excelbutton" value="excelbuttonclicked" onclick='document.getElementById("excel_input").value = "1";'><i class="ion ion-search"></i></input> </form> I want to get the value "1" when the excelbutton clicked in the Get request in order to export an excel file. I want to use the Get request because in this point I have a ready query set , the query set user sees on the screen. I use the commands request.GET.get('excel_input', None) if excel_string not in ['0', None]: testxlsxwriter(d_list) to get the value of the input field and export the excel file. The problem is that I get the value "1" from the input field on button click , but then I always get the value "1" on get requests( refresh , next page etc. I see the value "0" on screen on refresh but I get the value "1" on my view I also tried javascript with no luck window.onload = function(){ document.getElementById("excel_input").value = "0"; } Can someone help me please to understand how get request works with this input element? Thanks a lot Kostas -
throwing this error while generating user with phone number or otp 'function' object is not iterable in django
i am generating user authentication with phone number i got this error.i can not understand what means by this error please elaborate this. if is there any solution regarding this question then you can also suggest me. i got this error after runing the server File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/abksharma/Dev2/auth/src/accounts/admin.py", line 45, in <module> admin.site.register(User, UserAdmin) File "/Users/abksharma/Dev2/Auth/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 102, in register for model in model_or_iterable: TypeError: 'function' object is not iterable this is models.py from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager from django.core.validators import RegexValidator from django.db.models import Q from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.db.models.signals import post_save import random import os import requests class UserManager(BaseUserManager): def create_user(self, phone, password=None, is_staff=False, is_active=True, is_admin=False): if not phone: raise ValueError('User must Have a phone number') if not password: raise ValueError('user must have a password') user_obj = self.models( phone=phone ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active =is_active user_obj.save(using=self._db) … -
Django serve uploaded pdf method pros-cons?
I'm new to django, 2.0, I want to ask about the way I found to serve uploaded pdf files in a detail view, I've read that Django isn't supposed to serve files, and other post that I should use some packages specific for that, but I come up with this solution, but I don't now how well it could work: I setup a MEDIA_ROOT and MEDIA_URL in settings.py in models.py: class Base(models.Model): pdf = models.FileField(upload_to='pdf/pe/') def dwnld_pdf(self): return settings.MEDIA_URL + str(self.pdf) in views.py base = BaseForm(request.POST, request.FILES) in detail.html <label class="col-sm-3 col-form-label">Download PDF:</label> <div class="col-8"><a href="{{ base.dwld_pdf }}" target="_blank">Bajar Archivo</a></div> It works, but is it good practice?, what's the optimal way to serve uploaded files for viewing/download? Thanks -
How to change field in ModelForm generated html form?
I'm making one of my first django apps with sqlite database. I have some models like for example: class Connection(models.Model): routeID = models.ForeignKey(Route, on_delete=models.CASCADE) activityStatus = models.BooleanField() car = models.ForeignKey(Car, on_delete=models.CASCADE) class Route(models.Model): name = models.CharField(max_length=20) and forms class RouteForm(ModelForm): class Meta: model = Route fields = ['name'] class ConnectionForm(ModelForm): class Meta: model = Connection fields = ['routeID', 'activityStatus', 'car'] And in my website, in the url for adding new Connection, I have cascade list containing RouteIDs. And I'd like it to contain RouteName, not ID, so it would be easier to choose. How should I change my ConnectionForm, so I could still use foreign key to Route table, but see RouteName instead of RouteID? For now it's looking like this, but I'd love to have list of RouteNames, while still adding to Connection table good foreign key, RouteID -
Anyway to enable sentry on cookiecutter-django after the fact?
I created a django app using cookiecutter-django. While getting ready to deploy I realized I should have enabled sentry during project setup. Am i out of luck here and need to redo everything? Or is there a way I can enable it? -
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
I've the following room object which has Users as members. class Room(Base): name = models.CharField(db_index=True, unique=True, max_length=255) members = models.ManyToManyField(User, blank=True) I'm trying to find the Room that has only two specific members, if Room.objects.filter(members__id=first.id).filter(members__id=second.id).exists(): rooms = Room.objects.filter(members__id=first.id).filter(members__id=second.id) for room in rooms: print(room.members.count) if room.members.count == 2: return Response({"Success": RoomSerializer(room).data}, status=status.HTTP_200_OK) I know that there exists a Room object which has only two members. But I end up getting this error, AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` Any help appreciated. -
how to emulate escrow payments in django
i need to make online payments in my django website like what escrow provides i have scenario that client won't pay until delivery of his service what is the best way implement that workflow ? i have tried stripe but it didn't provide that feature to all countries i have provided workflow blew for what i need to make, Thanks -
How to use OR filters in djcli?
In djcli documentation they explain you can filter models like this with the list command: $ djcli ls settings.AUTH_USER_MODEL is_staff=1 username email is_superuser Auto-detected DJANGO_SETTINGS_MODULE=testproj2.settings Auto-detected model=auth.User ----- ------------ --------- email is_superuser username True newb False 13337noob ----- ------------ --------- But it does not show how to use the OR filter, ie. to list users that are either with is_staff=True, either is_superuser=True, is it possible ? Otherwise, how do you recommend to propose a syntax for OR'ing filters so I can contribute to djcli ? -
React: How to get a Django CSRF Token if CSRF_TOKEN_HTTPONLY is true?
I'm building a React application for a Django backend. In the backend the security setting CSRF_TOKEN_HTTPONLY is set to True. How can I obtain this csrf token in a React app? The documentation only describes how to do that using jquery. I'm usin the fetch API for my http requests. -
table has more than one primary key Django
I have got error. For start when I create models, I make mistake and give pk for all id fields in models. Then I make this right and change for unique, but when I makemigrations I get error, I try to delete DB, try to change venv for new, but it do nothing with this error, I think I make mistake in code, but can't find it. models.py code: class MainContact(models.Model): main_contact_id = models.IntegerField(null=True, unique=True) class Company(models.Model): company_id = models.IntegerField(null=True, unique=True) company_name = models.CharField(max_length=255, null=True) class Tags(models.Model): tags_id = models.IntegerField(null=True, unique=True) tags_name = models.CharField(max_length=255, null=True) class CustomFiledsValues(models.Model): custom_fields_values_value = models.CharField(max_length=255, null=True) custom_fields_values_enum = models.CharField(max_length=255, null=True) custom_fields_values_subtype = models.CharField(max_length=255, null=True) class CustomFields(models.Model): custom_fields_id = models.IntegerField(null=True, unique=True) custom_fields_name = models.CharField(max_length=255, null=True) custom_fields_values = models.ForeignKey(CustomFiledsValues, on_delete = models.CASCADE) custom_fields_is_system = models.BooleanField() class Contacts(models.Model): contact_id = models.IntegerField(null=True, unique=True) class Pipeline(models.Model): pipeline_id = models.IntegerField(null=True, unique=True) class Deal(models.Model): deal_id = models.IntegerField(null=True, unique=True) name = models.CharField(max_length=255, null=True) responsible_user_id = models.IntegerField(null=True) created_by = models.IntegerField(null=True) created_at = models.DateTimeField() updated_at = models.DateTimeField() account_id = models.IntegerField(null=True) is_deleted = models.BooleanField() main_contact = models.ForeignKey(MainContact, on_delete=models.CASCADE) group_id = models.IntegerField(null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) closed_at = models.DateTimeField() closest_task_at = models.DateTimeField() tags = models.ForeignKey(Tags, on_delete=models.CASCADE) custom_fields = models.ForeignKey(CustomFields, on_delete=models.CASCADE) contacts = models.ForeignKey(Contacts, on_delete=models.CASCADE) status_id = models.IntegerField(null=True) … -
How to retrieve the output of for-loop (dictionary) from models to views?
I have this model: class ModelName(models.Model): def my_dict(self): for i in range(n): …#some code context_a = {‘a’: a} return context_a I need to take context into view like this: from .models import ModelName class ViewName model = ModelName template_name = ’template_name.html’ def context_b(request): context_b = ModelName.objects.get(context_a=context_a) #here I want to get context_a as a dictionary and pass it to context_b for further operations. I know that my syntax here is not correct. return render(request, self.template_name, context_b) If I do it, I get Method Not Allowed: / [18/Nov/2018 12:40:34] "GET / HTTP/1.1" 405 0 I would like to know how to do it correctly, and also which specific resource (documentation and/or article) should I read/learn to understand my problem. I would appreciate any help. -
Django unit test with custom file storage backend
I'm writing a unit test case to test file upload in Django 2.x @pytest.mark.django_db class TestContact(TestCase): def test_model_add_contact(self): user = mixer.blend(User, is_superuser=True, username='anuj') contact = Contact( user=user, first_name='Anuj', last_name='Sharma', gender='m', date_of_birth='1996-10-19' ) contact.save() avatar_name = tempfile.NamedTemporaryFile(suffix='.jpg').name contact.avatar = avatar_name contact.save() # Avatar test assert contact.avatar == avatar_name, 'Should return avatar path' assert contact.get_avatar == settings.MEDIA_URL.rstrip('/') + avatar_name, 'Should return url of avatar path' Earlier when was using default storage backend, the test case was passing successfully. But now, I'm using django-storage with dropbox as storage backend DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'access_token' DROPBOX_ROOT_PATH = 'Koober' But now, the test case is failing django.core.exceptions.SuspiciousFileOperation: The joined path (/tmp/tmpwzfymbqf.jpg) is located outside of the base path component (/builds/app/app-py/MyApp) How can I change the storage backend in a unit test? -
Python, Django and facebook api
What is the best way to create a user profile using facebook public details to create a profile in Django's custom User model