Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HttpResponseRedirect and NoReverseMatch
I am trying to redirect to a new form page whose fields get automatically filled with the data sent from the view function. My urls.py is: url(r"user_dashboard/NewRequest/([\{.*\}])", views.request_form, name = "NewRequest") The view function which is sending the data is present at: url(r"user_dashboard/NReq", views.request_request, name="NReq"), which calls the above url. The return statement from my view function is: return HttpResponseRedirect(reverse(request_form, kwargs={"device_type":devicetype})) But, I get the following error: NoReverseMatch at /user_dashboard/NReq Reverse for 'inventory_management_app.views.request_form' with keyword arguments '{u'device_type': u'Laptop'}' not found. 1 pattern(s) tried: ['user_dashboard/NewRequest/([\\{.*\\}])'] Request Method: POST Request URL: http://127.0.0.1:8000/user_dashboard/NReq Django Version: 1.11.13 Exception Type: NoReverseMatch Exception Value: Reverse for 'inventory_management_app.views.request_form' with keyword arguments '{u'device_type': u'Laptop'}' not found. 1 pattern(s) tried: ['user_dashboard/NewRequest/([\\{.*\\}])'] Exception Location: C:\Anaconda2\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: C:\Anaconda2\python.exe Python Version: 2.7.14 Python Path: ['E:\\inventory management\\inventory_management_service', 'C:\\Anaconda2\\python27.zip', 'C:\\Anaconda2\\DLLs', 'C:\\Anaconda2\\lib', 'C:\\Anaconda2\\lib\\plat-win', 'C:\\Anaconda2\\lib\\lib-tk', 'C:\\Anaconda2', 'C:\\Users\\Jaimik Jain\\AppData\\Roaming\\Python\\Python27\\site-packages', 'C:\\Anaconda2\\lib\\site-packages', 'C:\\Anaconda2\\lib\\site-packages\\win32', 'C:\\Anaconda2\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda2\\lib\\site-packages\\Pythonwin', 'C:\\Anaconda2\\lib\\site-packages\\pywinpty-0.5-py2.7-win-amd64.egg'] Server time: Wed, 6 Jun 2018 07:48:44 +0000 Can anyone please tell me what's wrong present in the above code? -
Selenium Python/Django: using it with chromedriver on ubuntu
I have the following in a django app chat's tests.py from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH /home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/ cls.driver = webdriver.Chrome(executable_path="/home/muiruri_samuel/webapp/chatsys/chat/chromedriver") except: super().tearDownClass() raise ... it's supposed to check if channels works ok, but before that fails to connect to the chromedriver with this error (chatenv) muiruri_samuel@train:~/webapp/chatsys$ python manage.py test chat.tests Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: setUpClass (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/common/service.py", l ine 76, in start stdin=PIPE) File "/usr/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/home/muiruri_samuel/webapp/chatsys/chat/chromedriver': '/home/muiruri_samuel/webapp/chatsys/chat/chromedriver' line 68, in __init__ During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/muiruri_samuel/webapp/chatsys/chat/tests.py", line 14, in setUpClass cls.driver = webdriver.Chrome(executable_path="/home/muiruri_samuel/webapp/chatsys/chat/chromedriver") File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 68, in __init__ self.service.start() File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home ---------------------------------------------------------------------- Ran 0 β¦ -
How to test Django REST API using postman?
I need to test REST API using postman. API is build using Django REST Framework. Only login user can get access to API. I am not able to find how I can send login credentials using postman. Thanks in advance -
How to send nested form-data using postman?
Assume I have some data as below, { "name":"John", "age":30, "cars": { "car_img_1":"car_img_file1", "car_img_2":"car_img_file2", "car_img_3":"car_img_file3" } } How can I send it using POSTMAN with form-data? NOTES 1. car_img_fileX will be the file(.jpg,.png etc types) 2. What I'd tried -->> POSTMAN Screenshot. 3. Local server builted with Django framework Current Output Receiving 5 different items/data instaed of Nested data--> see this Pycharm Debugger Output -
Populate existing Django rows, But there are no rows
I'm trying to migrate my model: class EntitiesModel(models.Model): entity_id = models.TextField() entity_name = models.TextField() entity_type = models.TextField(choices=ENTITY_TYPES) #generic key to sources or targets content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') And I get the error: You are trying to add a non-nullable field 'entity_name' to entitiesmodel without a default; we can't do that (the database needs something to populate existing rows). But when I check the database: >>>from forward import models >>>models.EntitiesModel.objects.all() <QuerySet []> Do you have any clue what could cause this problem? -
"Authentication plugin 'caching_sha2_password' cannot be loaded
On starting the server in django I get the error message "Authentication plugin 'caching_sha2_password' cannot be loaded but, The mysql server is running and the root user has already been created in the DB. this is the error that i get these are the users -
Django Connection to MySQL RuntimeError: populate() isn't reentrant
I have configured the sample Django application to be on virtualenv, with apache and mod_wsgi. This application will be running on a centos server. However, when I have changed my settings.py file to the mysql setting, I have received a 500 Internal error. Logs [wsgi:error] [pid 11556] Traceback (most recent call last): [wsgi:error] [pid 11556] File "/var/www/django/mysite/mysite/wsgi.py", line 35, in <module>. [wsgi:error] [pid 11556] application = get_wsgi_application(). [wsgi:error] [pid 11556] File "/var/www/django/mysite/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application. [wsgi:error] [pid 11556] django.setup(set_prefix=False). [wsgi:error] [pid 11556] File "/var/www/django/mysite/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [wsgi:error] [pid 11556] apps.populate(settings.INSTALLED_APPS). [wsgi:error] [pid 11556] File "/var/www/django/mysite/lib/python3.6/site-packages/django/apps/registry.py", line 81, in populate [wsgi:error] [pid 11556] raise RuntimeError("populate() isn't reentrant") [wsgi:error] [pid 11556] RuntimeError: populate() isn't reentrant settings.py # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'test_user', 'PASSWORD': 'password_test', 'HOST': '192.168.0.1', 'PORT': '3306', } } Running the following command on the server itself does not show any errors python manage.py runserver However, when it's deployed via mod_wsgi, the above error is shown. Help is appreciated. Thank you! -
django shows User ID but i want to see User name
I have a problem with blog API. I want to see the author's name but this code shows me ID models.py author = models.ForeignKey(User,related_name='blog_posts') serializers.py class blogPostRetrieveSerializer(ModelSerializer): class Meta: model = BlogPost fields = ('image','title','author','body') serializers view (views.py): @permission_classes((permissions.AllowAny,)) class blogPostListAPIView(generics.ListAPIView): queryset = BlogPost.objects.all() serializer_class = blogPostRetrieveSerializer -
Django : render the parent's data to the template only if the child of the child has data
this is my models.py class Category(models.Model): name = models.CharField(max_length=50) ordering_num = models.IntegerField(default=0) class Meta: ordering = ['ordering_num'] def __str__(self): return self.name class SubCategory(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) name = models.CharField(max_length=50) ordering_num = models.IntegerField(default=0) class Meta: ordering = ['ordering_num'] def __str__(self): return self.name class ProductBasicModels(models.Model): whose = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.ForeignKey(SubCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) standard = models.CharField(max_length=50) maker = models.CharField(max_length=50, blank=True) outbox = models.CharField(max_length=50, blank=True) extra = models.CharField(max_length=100, blank=True) orderto = models.ForeignKey(OrderCompany, null=True, blank=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['name'] def __str__(self): return self.name views.py @ login_required def product_list(request): categories = Category.objects.all() context = {'categories': categories} return render(request, 'medicalapp_1/products_h.html', context) products_h.html (simple structure...) ... {% for category in categories %} {{ category.name }} {% for sub_category in category.subcategory_set.all %} {{ sub_category.name }} {% for list in sub_category.productbasicmodels_set.all %} {% if list.whose.id is request.user.id %} {{ list.name }} {% endif %} {% endfor %} {% endfor %} {% endfor %} .... according to my code.. all of category and subcategory and products being displayed. But I want to make them display only products models has data. like this.. category1 subcategory1 product1 product2 product3 category4 subcategory1 product4 product5 subcategory3 product6 (category2,3) and (subcategory2 of category4) β¦ -
Import files in python
I know it's possible to import everything in a file into another file like this: from app1.models import * But I want to do something like this: from *.models import * It means import everything inside models file from any directory. for example in this file structure /module /app1 /models.py /app2 /models.py /allModels.py I want to import all models.py files into allModels.py Is it possible? Do we have such syntax? -
Python Django or Java script Node.js
i am Pranit Kokate. I just cleared Engineering, i wanted to know which technology is better for my career in developer profile. So i discussed with friends with this so i came to know Node.js and Python Django are best option. help me choose one. -
what are the headers to set in the Rest API for the HTTP GET request
@api_view(['GET']) def gatewayentities_list(request,format=None): requestMeta = request.META if ('HTTP_AUTHORIZATION' not in requestMeta.keys()): return JSONResponse({"status": "UNAUTHORIZED"}, status=401) elif (requestMeta['HTTP_AUTHORIZATION'] is not None): headerParameters = requestMeta['HTTP_AUTHORIZATION'].split(" ") companyid_id = headerParameters[2] apikey = headerParameters[0] userId = headerParameters[3] try: applicationid = int(headerParameters[4]) except IndexError: applicationid = 0 {'Transfer-Encoding': 'chunked', 'Vary': 'Cookie', 'Server': 'Apache/2.2.29 (Amazon)', 'Connection': 'close', 'Date': 'Wed, 06 Jun 2018 06:50:09 GMT', 'Content-Type': 'text/html; charset=UTF-8'} Server Error (500) -
Django count number of records per day
I'm using Django 2.0 I am preparing data to show on a graph in template. I want to fetch number of records per day. This is what I'm doing qs = self.get_queryset().\ extra({'date_created': "date(created)"}).\ values('date_created').\ annotate(item_count=Count('id')) but, the output given is [ {'date_created': datetime.date(2018, 5, 24), 'item_count': 1}, {'date_created': datetime.date(2018, 5, 24), 'item_count': 1}, {'date_created': datetime.date(2018, 5, 24), 'item_count': 1}, {'date_created': datetime.date(2018, 5, 24), 'item_count': 1}, {'date_created': datetime.date(2018, 5, 24), 'item_count': 1}, {'date_created': datetime.date(2018, 5, 24), 'item_count': 1}, {'date_created': datetime.date(2018, 5, 24), 'item_count': 1} ] Here data is not grouped and same date is returning repeatedly with count as 1 -
Docker Images are not working properly
I am working on a python,django application. when i run application locally it works fine.But after building the docker images for same code and running the application with docker-compose up it works but some feature of application are not working as they work while running locally. My application is document based application. while running locally it shows the image for document but in case of application run with docker images it does not show document images. Screen shots are attached. is there any conflict with docker version which is causing problem. Docker version is: Docker version 18.03.1-ce, build 9ee9f40 any help will b greatly appreciated, Thanks in advance.https://ibb.co/m2CUoT https://ibb.co/cPTfv8 -
create() takes 1 positional argument but 2 were given?
I have a model named Following that has these fields: class Following(models.Model): target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE) follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE) def __str__(self): return '{} is followed by {}'.format(self.target, self.follower) What I'm trying to create is a follow button that when pressed, gives the target a follower. Inside the view that has the follow button, has this logic: class ProfileView(DetailView): model = User slug_field = 'username' template_name = 'oauth/profile.html' context_object_name = 'user_profile' # Without this, Django would default to request.user instead which is the logged in user def post(self, request, slug): follower = self.request.user self.object = self.get_object() context = self.get_context_data(object=self.object) follow_unfollow(follower, self.object.id) # Error is found inside this function return render(request, self.template_name, context=context) def follow_unfollow(follower, id): target = get_object_or_404(User, id=id) if follower.is_authenticated(): if follower in target.followers.all(): target.followers.delete(follower) else: target.followers.create(follower) # Error outputs: create() takes 1 positional argument but 2 were given When we want to create a row for the new follower, an error happens saying that create() takes 1 positional argument but 2 were given What am I doing wrong? -
Can you use a disabled form for DetailsView?
I use a lot of class based views in Django in my project. In particular, I find that it is very troublesome to create model_detail.html. Django has the ability to create a form for a model (ModelForm). Is it possible to render the ModelForm for an object but with all inputs disabled in model_detail.html? -
Flower dashboard doesn't show up
We are using django for our python website. We are using celery==4.1.1 to run background tasks. Everything works fines. I cannot monitor the tasks processed or processing. In previous celery we use to have djcelery it would show up everything. I heard of flower.I used flower==0.9.2 tornado==4.5.2 babel==2.5.3 here is the command in supervisor [program:celery-flower] command=flower -A lbb --natural-time --url_prefix=flower --port=5555 --inspect --enable-events here is my nginx conf upstream application { server lbb-app:8000; } upstream application2 { server lbb-app:5555; } server { listen 80 default_server; charset utf-8; client_max_body_size 4G; # adjust to taste server_tokens off; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; add_header Cache-Control "no-store"; add_header Pragma "no-cache"; add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;"; location /work { include uwsgi_params; uwsgi_pass application; } # Finally, send all non-media requests to the Django server. location / { include uwsgi_params; uwsgi_pass application; } location /flower/ { include uwsgi_params; uwsgi_pass application2; } } I cannot open the dashboard. it shows 504 error. Is --broker-api compulsory to just show up flower dashboard. Is there any problem in my settings. What should I do. Any help would be really appreciated. Thanks. -
γdjango2.0.5γfail to get post data in request.body or request.POST even in set csrf_exempt
Environment: django 2.0.5,python3.6.5,postman Specification: i wrote a single view without templates to receive post json data from any client like postman or other programs. Even used csrf_exempt decorator, it couldn't get post data correctly in request.body or request.POST. i have searched google and always got the answer that once disabled the csrf_exempt it would be correct to get the post data in request.body. Thanks a lot for your help! Refer snapshot: view code urls code debug snapshot postman1 postman2 -
Django - sending JSON arrary on POST request
I am creating a dynamic form based on the number of records available in the DB. The input fields are dynamically set during rendering. Once the values are set I want them to be bulk inserted into the DB. (I am using modelSerializer class for serialization) For example <form id="issue_form"> <input name="issue" value="random"/> <input name="issue" value="sensor"/> <input name="issue" value="human"/> <input name="issue" value="pc"/> </form> <script> $(docment).on('submit','#issue_form',function(event){ event.preventDefault(); var data = $(this).serializeArray(); $.ajax({"url":"api/data",data :data }).done(function(res){ console.log(data) }) }) Model: class Issue(models.Model): issue = models.CharField(max_length=100) Serializer: class IssueSeralizer(serializers.ModelSerializer): class Meta: model = Issue fields = ('id',issue) view class IssueViewSet(viewsets.ModelViewSet): queryset = Issue.objects.all() serializer_class = IssueSerializer. I want to achieve storing bulk JSON value on post request to the model. For instance json = [{"name":"random"},{"name":"sensor"},{"name":"human"},{"name":"pc"}] -
related manager and through
I have models: class User(models.Model): title = models.CharField(max_lenght=100) regions = model.ManyToMany(Region, through=UserRegion) class UserRegion(models.Model): user = models.ForeignKey(User) region = models.FareignKey(Region) class Region(models.Model): title = models.CharField(max_lenght=100) and I want to determine so methods which are defaults. It means I want use user like this: user.regions.set(Region.objects.all()[:3]) How can I do it? -
Django,Template-loader postmortem
Django does not see my registration.templates folder.I do not understand where the problem lies. Why is he looking foe base.html? This is how I specified my templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'store/templates/registration')], My store directory tree . . βββ admin.py βββ apps.py βββ __init__.py βββ migrations β βββ 0001_initial.py β βββ 0002_auto_20180604_0751.py β βββ __init__.py β βββ __pycache__ β βββ 0001_initial.cpython-36.pyc β βββ 0002_auto_20180604_0751.cpython-36.pyc β βββ __init__.cpython-36.pyc βββ models.py βββ __pycache__ β βββ admin.cpython-36.pyc β βββ __init__.cpython-36.pyc β βββ models.cpython-36.pyc β βββ urls.cpython-36.pyc β βββ views.cpython-36.pyc βββ templates β βββ registration β β βββ activate.html β β βββ activation_complete.html β β βββ activation_email_subject.txt β β βββ activation_mail.txt β β βββ registration_complete.html β β βββ registration_form.html β βββ store.html β βββ template.html βββ tests.py βββ urls.py βββ views.py urls.py urlpatterns = [ url(r'^', include('store.urls')), path('accounts/', include('registration.backends.default.urls')), path('admin/', admin.site.urls), ] -
How implement dynamic testimonials and carousel in django python
Im facing implementing the dynamic testimonials and carousel in django python, means i need to content in models that so present in front below i mention my code of implemetions template.html <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> {% for p in tests %} {% if forloop.counter == 1 %} <div class="item active"> {% else %} <div class="item"> {% endif %} <h3>{{ p.title }}</h3> </div>`enter code here` </div> {% endfor %} </div> </div> view.py: def home(request): test=Testimonials.objects.all().order_by('id')[:13] template = loader.get_template('hme/home.html') context = { 'tests':test, } return HttpResponse(template.render(context, request)) -
TypeError: post() got an unexpected keyword argument 'slug'
I have a DetailView that displays a user's profile page. The profile takes a slug name that is part of the URL. For example, /profile/john/ where john is the username, and we are on john's profile. As shown here: class ProfileView(DetailView): model = User slug_field = 'username' template_name = 'oauth/profile.html' context_object_name = 'user_profile' def post(self, request): return render(request, self.template_name) Now whenever I submit a form, I get an error that says: TypeError: post() got an unexpected keyword argument 'slug' Knowing this, I added a new argument in the post method which is slug. However, when I submit the form, I get a blank page with no details about the user. We get redirected to the same page, but this time with no values about the user profile. What am I doing wrong? -
Django: update a page without reloading
I want to update my homepage.html with button action and show some result from the server. But the problem is when I click on the button the whole page is reloading. Here, my project name is "T2KG". My form tag looks like this: <form method="POST"> {% csrf_token %} <center><textarea placeholder="Give a input sentence....." class="text" name="sent" rows="5" cols="70" font="15px arial, sans-serif" autofocus>Barack Obama born in Hawaii. Hawaii locates in USA.</textarea></center><br> <button type="submit" class="btn btn-primary btn-block" id="display_result">Generate Triple</button> </form> By searching in many websites I have understood that my view.py and urls.py is not correct and also I have to use AJAX. But How to implement in this situation I don't know. I have tried but couldn't find any way out. In view.py I return the value like this: def result(request): text = 'null' if request.method == 'POST': form_input = Sentence(request.POST) if form_input.is_valid(): text = form_input.cleaned_data['sent'] else: form_input = Sentence() triples = getTriples(text) ent_list = entityList(text) triples = predicateList(aggregate(triples, ent_list)) return render(request, './T2KG/homepage.html',{'triples': triples, 'json_triples': json.dumps(triples), 'text':text}) And my urls.py is: urlpatterns = [ path('', views.set_sent, name='set_text'), url(r'^T2KG/homepage', views.result, name='result'),]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Please help me. -
Django: redirect from page if model field is certain value
I have a Class-based-view that sends a user to a webpage to view an item. The user can click on the edit button to edit the page, however, I don't want the user to always be able to edit the page. Once a field ('status') in a model has been set to 'completed', I'd like the user to no longer be able to update the page. I have a class based view. How do I redirect the user to a different url, (e.g. the view url) if the status=completed? My current approach is to have a form that errors if the field status is set to completed. It's not ideal since the person still sees the edit an may wonder why it is erroring out. urls.py url(r'^update/(?P<status_id>[0-9A-Za-z]+)/$', ThingUpdateView.as_view(), name='update'), class based view class ThingUpdateView(LoginRequiredMixin, UpdateView): model = Thing form_class = ThingChangeForm template_name = 'thing/thing_update.html'