Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I fix"is not recognized as an internal or external command, operable program or batch file" in windows10
hi I created a django project on desktop after that I cut it's file and paste it in :C but when I want to activate my virtualenv in cmd I get the bellow error. ('hyperDesign' is not recognized as an internal or external command, operable program or batch file) 'hyperDesign' is the name of my virtualenv file. -
Django MEDIA_URL is not serving the file on the local server
I have MEDIA_ROOT and MEDIA_URL in my settings.py. MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I am uploading files to uploaded_files = models.FileField(upload_to='uploads/%Y/%m/%d/') I also have defined this in my url.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The files are getting saved correctly but while accessing them I am getting 404. Any idea, what might be going wrong here. Thanks. Using the URLconf defined in assemblyautomation.urls, Django tried these URL patterns, in this order: admin/ genplansheet/ ^static/(?P<path>.*)$ The current path, media/uploads/2019/09/05/1125sft_sold.xlsx, didn't match any of these. -
You are trying to add a non-nullable field stock without a default
I have added a new field in my model but after that I have deleted db.sqlite3 (to ensure I don't get error below) agrawalo@:~/myapp> ls README.md config core manage.py requirements.txt But still I get this error when I run makemigrations agrawalo@:~/myapp> ./manage.py makemigrations You are trying to add a non-nullable field 'high52' to stock without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py -
Sending multiple get requests to multiple hosts simultaneous
Checked many questions here and can't find proper answer. What i have now, works. Just need to speed it up. What i have now is one function in views.py that a) gets list of hosts b) sends get request to hosts from the list one by one and if connection is successful it adds host to array. c) takes new array (with online hosts) and send requests to all "online hosts". I would like to focus on b) point def host_tst_online(request): abc_hosts = Host.objects.all() tsthost = Host.objects.filter(abcenv='tst').order_by('abchostname') tsthostonline = [] arr = [] ######################################## ######Check which hosts are online###### ######################################## for xyz in tsthost: try: response1 = requests.get( 'https://{}:6666/abc/api/v1/about'.format(xyz), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxx'}, timeout=1 ) if not response1.status_code == 401: tsthostonline.append(xyz) else: print('all ok') except (ConnectionError, ConnectTimeout) as e: print(e) response = "No response" ########################################################################### ##########Send request to all hosts from tsthostonline array############### ########################################################################### if request.method == 'POST': send_form = SendersFormO(request.POST) if send_form.is_valid(): abcsend = send_form.cleaned_data.get('abcsend') send_form = SendersFormO() for eee in tsthostonline: response = requests.get( 'https://{}:6666/abc/api/v1/objects/abcsend?id={}'.format(eee, abcsend), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxx'}, ).json() for key in response['data']: arr.append(key) context = {'response': response, 'arr': arr, 'send_form': send_form, 'tsthostonline': tsthostonline} return render(request, 'app/json_nest_send_online.html', context) else: send_form = SendersFormO() … -
Deploying django site
I want to deploy my first django site. Which will likely have 100 visitors a day ( just starting ). Database requirements are also very low ( like 100 user information ). Is there any way I can deploy it for free if not then please suggest something with low price without subdomain? (I have been thinking about heroku or python anywhere but I don't want to include subdomain and aws or google cloud pricing is not efficient for low traffic if I want cheap pricing ) -
custom dynamic list_filter with Django SimpleListFilter
According to Django document it is possible to write custom list filter by creating "a class inheriting from django.contrib.admin.SimpleListFilter, which you need to provide the title and parameter_name attributes to and override the lookups and queryset methods, e.g." some thing like this: from datetime import date from django.contrib import admin from django.utils.translation import gettext_lazy as _ class DecadeBornListFilter(admin.SimpleListFilter): title = _('filendName_amount') parameter_name = 'amount' filed_name = 'filed_name' compare_value = 100000 def lookups(self, request, model_admin): return ( ('mt', _('more than ') + str(self.compare_value)), ('lt', _('less than ') + str(self.compare_value)), ) def queryset(self, request, queryset): kwargs = {} if self.value() == 'mt': kwargs = { '{0}__{1}'.format(self.filed_name, 'gte'): self.compare_value, } if self.value() == 'lt': kwargs = { '{0}__{1}'.format(self.filed_name, 'lte'): self.compare_value, } return queryset.filter(**kwargs) It works fine. But is it possible to pass the filed_name and the compare_value to create more dynamic list filter? -
I cannot fetch data
views.py def home_page(request): context = Add.objects.aggregate( bud=Sum('budget'), exp=Sum('expense'), budexp=Sum('budget')-Sum('expense')) return render(request, 'home.html', context,) def list_page(request): qs = Add.objects.all() context = {'qs':qs} return render(request, 'list.html', context,) when i remove qs = Add.objects.all() and context if this page at that time my list_page work fine other wise indention error that happens because of def home_page code. How to solve this problem i just want to see all data on list_page. -
DRF: data is not passing to kwargs in patch method
I am creating a update comment view for my app. This is my code: serializer.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = FitnessRecord fields = ('comment', 'id') views.py class AddCommentView(APIView): permission_classes = [IsAuthenticated] def patch(self, request, *args, **kwargs): print(kwargs) # this is printing {} instance = get_object_or_404(FitnessRecord, pk=kwargs.get('id')) # error line print(22222) # not printing serializer = CommentSerializer(instance, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(CommentSerializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am using postman to send data. this is the error: { "detail": "Not found." } This may be because kwargs is blank. I am passing this data. { "comment": "gotham#bw9", "id": 14 } This is DRF setting if required. REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DATE_INPUT_FORMATS': ['%d-%m-%Y'], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json' } -
Get only text in RichTextField in CKEditor?
I'm a newbie. I'm using Django to write a personal blog. I'm using CKEditor to be able to insert images into my blog post. However, I want to show some first words of the posts on the homepage which does not include the images in the posts. I want to know if there is a way that I can get text only from RichTextField in CKEditor. I don't have enough reputation to post images. This is my current preview content: https://i.imgur.com/XJR13pH.png I want it to be like this (no images): https://i.imgur.com/eRaIWzy.png This is my current code: https://i.imgur.com/54IV7s3.png -
In select tag values passing as value="<ul id=" id_process" in django
Using CheckboxSelectMultiple widget in the forms, The select tag value attribute is automatically not generating properly the Inspect(F12) code is given below <select name="process" required="" class="valid"> <option value="<ul id=" id_process"></option> </select> How can I pass id in the value attribute -
I need to crop a pdf file and get the dimention in web page
I'm creating a web application for getting the dimension of pdf in Points(measurement), where i need to crop our require area using rectangular and get those dimension I tried to get create a pdf cropper but mostly there is only image cropper existing -
Problem with getting the select option data
I am having problem to get the selected data from a form. Here is my form <form action="#" method="GET"> {% csrf_token %} <select name="country" id="selectcountries" class="custom-select"> <option>Select country</option> {% for item in countries %} <option val="{{ item.name }}"> {{ item.name }} </option> {% endfor %} </select> <select name ="city" id="selectcities" class="custom-select"> <option>Select city</option> </select> <select class="custom-select" name="option" > <option selected> Tourist Spot </option> <option> Hotel </option> <option> Restaurent </option> </select> <button type="submit" class="btn tour-btn"><i class="fa fa-search pr-2" aria-hidden="true"></i> <a href="{% url 'advanceSearch' %}"> Search </a></button> </form> And my views.py is def advanceSearch(request): country = request.GET.get('country') city = request.GET.get('city') option = request.GET.get('option') if request.method == "GET" : if country: message = 'q= %s' % country else: message = 'Empty' else: message = 'fucking sheet' return HttpResponse(message) HTTPResponse always give me empty message even after with passing values by the form. I want to get the data from this form but i cant. -
how to show foreign key value instead of its ID
i'm try to display foreign key value , but it instead return the id , in template models.py class Product(models.Model): product_name = models.CharField(unique=True, max_length=50) pass def __str__(self): return self.product_name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') pass def __str__(self): return str(self.products.all()) class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) pass def __str__(self): return str(self.product) this is my views.py class ListOfOrder(ListView): template_name = 'order/product_group.html' context_object_name = 'productss' def get_queryset(self): return ProductOrder.objects.all() template.html {% for product in productss %} <tr class=""> <td style="text-align: center;">{{ product.product }}</td> {% endfor %} i expected to display the product name but it instead displayed the ID of the product thanks for your answer -
Django Serializer access json data from post string indices must be integers
I'm trying to create Serializer for a register post request's validation The json that send to the API with the POST request: { "username": "dat@icts.vn", "password": "123456", "confirm_password": "123456" } My serializer for validation: class RegisterSerializer(serializers.Serializer): username = serializers.EmailField(required=True) password = serializers.CharField(required=True) confirm_password = serializers.CharField(required=True) def validate_username(self, username): existing_email = User.objects.filter(email=username).first() if existing_email: raise serializers.ValidationError("Email already registered") return username def validate_confirm_password(self, data): if data['password']: if data['confirm_password'] != data['password']: raise serializers.ValidationError("Confirm password not match password") return data['confirm_password'] My view register function: @csrf_exempt @require_http_methods(["POST"]) def register(request): received_json_data=json.loads(request.body) valid_ser = RegisterSerializer(data=received_json_data) if valid_ser.is_valid(): post_username = received_json_data["username"] post_password = received_json_data["password"] user = User.objects.create_user(username=post_username,password=post_password) user.save() refresh = RefreshToken.for_user(user) content = { 'refresh': str(refresh), 'access': str(refresh.access_token), } return JsonResponse(content) else: return JsonResponse({'code':'400','errors':valid_ser.errors}, status=400) When i send the POST request i get the following error: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response web_1 | response = self.process_exception_by_middleware(e, request) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view web_1 | return view_func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner web_1 | return func(request, *args, **kwargs) web_1 | File "/app/api/views.py", line … -
Bullet points from model
I have a "Product" model. I want to have a <ul> in my product detail template to list product features. How can I list features of a certain product in a <ul>? product_detail.html <ul class="mb-0"> <li class="mb-2">lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li class="mb-2">donec pede justo, fringilla vel, aliquet nec.</li> <li class="mb-2">phasellus ullamcorper ipsum rutrum nunc. </li> </ul> -
Django Mailing failure: Connection to rabbitmq broker lost
I am trying to integrate a mailing feature in my shopping app which would mail to users notifying their order has been placed. I am using Celery for asynchronous tasks, rabbitmq as my message broker and Flower to monitor the tasks. But after placing the orders, the mail is not being sent and Flower Dashboard shows that the task has failed. I marked an error which I got into my Celery terminal: File "c:\users\acer\appdata\local\programs\python\python36\lib\site-packages\amqp\transport.py", line 438, in _read s = recv(n - len(rbuf)) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host and finally it shows: [2019-09-05 09:57:40,404: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection.. my tasks.py file: from celery import task from django.core.mail import send_mail from .models import Order @task def order_created(order_id): """ Task to send an e-mail notification when an order is successfully created. """ order = Order.objects.get(id=order_id) subject = 'Order nr. {}'.format(order.id) message = 'Dear {},\n\nYou have successfully placed an order.\ Your order id is {}.'.format(order.first_name, order.id) mail_sent = send_mail(subject, message, 'seller@admin.com', [order.email]) return mail_sent I am not able to figure out what's wrong. Any help would be appreciated :) -
How to find which item of table is selected?
I have a table like this in my UI. <table> <thead> <tr> <th>DELETE</th> <th>EDIT</th> <th>No</th> <th>Name</th> </tr> </thead> <tbody id="bodyTable"> {% for item in person_list %} <tr> <td> <a href="#"> Delete </a> </td> <td> <a href=""> EDIT </a> </td> <td>{{item.person_no}}</td> <td>{{item.person_name}}</td> </tr> </tbody> </table> and there is to option "EDIT" and "DELETE" for my tables items. and I want to know how to find with an item that is clicked for DELETE or EDIT? that item should be removed from database or edited, so i need find which item is clicked and send that id to my views. -
Login after successful registration Doesn't work in Django
I have a problem when I register in the site with a new user does not log in the site after registration as in the following code if formRegister.is_valid(): username = formRegister.cleaned_data.get('username') password = formRegister.cleaned_data.get('password') user=formRegister.save() #u= User.objects.get(username=request.POST.get('username')) userAthen = authenticate(request,username=user.username, password=user.password) if userAthen is not None: login(request, userAthen) return redirect('/') -
Display nested many-to-many fields in template as checkboxes
Im new to django and Im working on a website to generate engineering change documentation to support product design activity. I have three models with nested 'many to many' fields. when starting document generation, I ask the user to select the chassis for which the document will be generated, once the chassis is selected I want to display a form with all the fields from "DocDetials" model and a table showing all the boards available for the selected chassis as checkboxes, so that the user can select which board to apply the changes to. I can display most of DocDetails fields in a template using views, and get the data after summit. I just need to be able to display and select the boards for corresponding chassis. knowing which 'chassis' the user selected is done, lets asume the form sent to the view has the selected 'chassis' as default. I have been looking for a way to do this for days, have tried several approaches but haven't been able to do this. there are a lot of answers about how to display one tier many-to-many files, but nothing about NESTED many-to-many fields. I have not found a related solution here … -
Django Raw SQL Query - How to pull value via column (instead of tuple index) from SELECT query
I'm executing a fetchall() raw SQL query in Django (1.11) with a PostgreSQL data source. The result returns a tuple. My concern is that I can only seem to fetch a row's field via the tuple index i.e. row[2] (or in template I would do {{row.2}}). But I want to be able to use the actual field name instead of index i.e. row.itemno (or in template I would do {{row.itemno}}) I tried doing row.first_name but it says 'list' object has no attribute 'itemno' Is it or isn't it possible to use field names with this result? Here's a sample in python shell: P.S. You might be wondering why I'm still using Django 1.11... It's because we are using DjangoCMS and unfortunately, it supports up to 1.11 only... -
How to add views to the Browsable API Root?
When working with the Browsable API in Django Rest Framework the API root only appears to list responses for ViewSets registered via a router. For example, in the code below users and accounts would show, but not forgot-password: router = routers.SimpleRouter() router.register(r'users', UserViewSet) router.register(r'accounts', AccountViewSet) urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), ] urlpatterns += router.urls How can I add a hyperlink for forgot-password to the base API root? -
How do I create a functional api using django rest framework?
I am trying to use mailgun's api on a landing page made through unbounce.com, however I discovered that I can't make requests client side. I do have django set up, so, I'd like to use that to make api calls to mailgun instead. So, my question is how do I create using django-rest-framework, an API that would make the api calls for me and return the response. I have used drf before, but mostly serializing models, and this time I'd like to make a function-based api I expect to make a call to mailgun and pass a parameter called email so that I can use something like domain.com/api/mailgun/email="email@email.com" -
Keep getting duplicate key errors when saving database entires with Django
In the project I am currently working on, I have a Django model with a VARCHAR field that is the primary key. It was multiple purposes and it designed quite generically. This model is used within an app to store data saved, and a secondary model is create simultaneously to link the generic object with a less generic model, to easily find the related models. When saving the generic model, the VARCHAR primary key is generated based off certain parameters sent when saving (such as store it belongs to, and the time period it was saved, and the the product it is attached to). The issue is on more than one occasion, when a user saving data and creating a new generic modal and link model, Django is returning duplicate key errors. The key generated is fairly distinct and at least one version of the data is being created. Examples of the model structure (some fields omitted for levity) class GenericModel(models.Model): string_id = models.CharField(max_length=255, db_index=True) updated = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) class LinkModel(models.Model): generic_model = models.ForeignKey(form_models.GenericModel, on_delete=models.CASCADE, related_name='link_models') Example of saving process: string_id = f`{store.id}{period.id}{product.id}` generic_model = GenericModel.objects.filter(string_id=string_id).first() if generic_model: generic_model.updated = time.now() generic_model.save() else: generic_model = GenericModel.objects.create(string_id=string_id) link_record = … -
Graphene Django File field get absolute path
I have an image field in my Django model and I am trying to get absolute path of the image field output from Graphene. none class Meta: model = Account``` i do not get an absolute filefield path -
Email not sending using gmail
I am creating an e-commerce website by following a tutorial online and ive reached the point where I created a form and then I am supposed to send emails to anyone who completed the form, however, the emails are not sending. Settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password123' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'testing@testing.com' viwes.py from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings from .forms import contactForm # Create your views here. def contact(request): form = contactForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] comment = form.cleaned_data['comment'] subject = 'Message from MYSITE.com' message = '%s %s' %(comment, name) emailFrom = form.cleaned_data['email'] emailTo = [settings.EMAIL_HOST_USER] send_mail(subject, message, emailFrom, emailTo, fail_silently =True) context = locals() template = 'contact.html' return render(request,template,context) I don't get an error but I'm not receiving emails