Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx without static files (Django + Gunicorn)
I launch the site on VM (localnetwork, Ubuntu 18 LTS). But the admin panel works without static files. Settings Django: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = "/home/portal/static/" After command 'manage.py collectstatic' static files created here: There is also a static folder in the project root, but it is empty. File contents new_portal: server { listen 80; server_name 10.0.0.18; location = /favicon.ico {access_log off;log_not_found off;} location /static { alias /home/portal/static; expires max; } location /media/ { root /home/portal/my_django_app/new_portal; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}} gunicorn.conf: bind = '10.0.0.18:8000' workers = 3 user = "nobody" Tell me where is the error? Is there something wrong with Gunicorn? If something else is required (code or screen) - I will attach it upon request. -
How to create a product successfully using woo commerce api with python
I am trying to create / update products from my django app to my website. The problem I am facing with is that i can not create the product from my django to the website using the woo commerce api. The update procedure works. Here is my code: def create_woocommerce_product_individually(wcapi_yachtcharterapp,name,fetched_sku,fetched_url,short_description,description,woo_commerce_category_id): data = { "name": name, "sku": fetched_sku, "images": [ { "src": fetched_url }, ], "short_description": short_description, "description": description, "categories": [ { "id": woo_commerce_category_id } ], } #post data to the woocommerce API wcapi_yachtcharterapp.post("products",data).json() print(" 3A STEP - WOO PRODUCT CREATED IN THE SITE") def update_woocommerce_product_individually(wcapi_yachtcharterapp,name,fetched_sku,fetched_url,short_description,description,woo_commerce_category_id,post_id): data = { "name": name, "sku": fetched_sku, "images": [ { "src": fetched_url }, ], "short_description": short_description, "description": description, "categories": [ { "id": woo_commerce_category_id } ], } #put data to the woocommerce API wcapi_yachtcharterapp.put("products/"+str(post_id),data).json() print(" 3B STEP - WOO PRODUCT UPDATED IN THE SITE") Here is the part of code, calling the above functions based on the response: r=wcapi_yachtcharterapp.get("products/?sku="+fetched_sku).json() if len(r) > 0: #if it exists in the website , take the post id post_id=r[0]['id'] if len(r) == 0: #call the create create_woocommerce_product_individually(wcapi_yachtcharterapp,name,fetched_sku,fetched_url,short_description,description,woo_commerce_category_id) product.is_stored_to_website = True product.save() print("Stored : {} \n".format(product.is_stored_to_website)) else: #call the update update_woocommerce_product_individually(wcapi_yachtcharterapp,name,fetched_sku,fetched_url,short_description,description,woo_commerce_category_id,post_id) product.is_stored_to_website = True product.save() print("Stored : {} \n".format(product.is_stored_to_website)) I read … -
NoReverseMatch at / Error during template rendering
when i opens http://127.0.0.1:8000/ which is home.html, Iam getting NoReverseMatch at / and *Reverse for 'exam-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['exam/(?P[^/]+)$'] Iam thinking the error is due to in urls.py. The following is urls.py file from . import views from .views import ExamListView, ExamDetailView app_name='map' urlpatterns = [ path("", ExamListView.as_view(), name='map-home'), path("exam/<str:pk>", ExamDetailView.as_view(), name="exam-detail"), path("login_student/", views.login_student, name='map-login'), path("register_student", views.register_student, name='map-register'), path('add_student/', views.add_student, name='add_student'), path('front/', views.front, name="front"), ] models.py file subject = models.TextField(primary_key = True, unique = True) def __str__(self): return self.subject home.html {% extends "map/base.html" %} {% block content %} <p>WELCOME HOME</p> {% for exam in exams %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'map:exam-detail' exam.subject %}">{{ exam }} </a> </div> </div> </article> {% endfor %} {% endblock content %} base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'map/main.css' %}"> {% if title %} <title>{{ title }}</title> {% else %} <title> MAP PAGE </title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="/">Project M.A.P</a> … -
How to Add custom urls to oscar API documentation page(API root)
I have a Django oscar application and I use django-oscarapi for my custom APIs. I have created an app(api), and in that app, I have included the oscarapi.url, which is showing me the URLs for oscarapi. However, I have added a custom, viewset for registration that I call 'users', I also want to display that users in the same list as of oscarapi's. i.e I want to add some more URLs to the same list....how can I add it to get displayed as other API hyperlink on the API ROOT page e.g http://127.0.0.1:8000/api/users/ i am able to access the users URL, but it is not getting displayed in the list of all APIs. How can I do it? https://prnt.sc/r792or api/urls.py router = routers.DefaultRouter() router.register(r'users', UserCreateAPIView) urlpatterns = [ #oscarapi default urls path(r'', include("oscarapi.urls")), #custom url path(r'', include(router.urls)), ] -
Python, return html file generated by business logic in django rest framework
I'm trying to create a Rest API that can receive data from a user, run some business logic on it and return as a response an HTML File that is generated based on the data passed in. # models.py from django.db import models from django.utils import timezone from django import forms # Create your models here. areas = [ ('210', '210'), ('769', '769'), ('300', '300') ] class LocationInfo(models.Model): latitude = models.FloatField(name="GDT1Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) longitude = models.FloatField(name="GDT1Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=1) gdt2_lat = models.FloatField(name="GDT2Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) gdt2_lon = models.FloatField(name="GDT2Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_lat = models.FloatField(name="UavLatitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_lon = models.FloatField(name="UavLongitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_elevation = models.FloatField(name="UavElevation", max_length=100, default=1, blank=False, help_text="Enter the above ~Sea Level~ planned uav Elevation. " ) area = models.CharField( max_length=8, choices=areas, ) date_added = models.DateTimeField(default=timezone.now) class Meta: get_latest_by = 'date_added' … -
Multiple forms on one page Django
How can I add several forms per page? My code currently only displays one form, how do I add another form to my code? class OrderUpdateView(UpdateView): model = Order template_name = 'order_update.html' #in this expample only one form form_class = OrderEditForm def get_success_url(self): return reverse('update_order', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) instance = self.object qs_p = Product.objects.filter(active=True)[:12] products = ProductTable(qs_p) order_items = OrderItemTable(instance.order_items.all()) RequestConfig(self.request).configure(products) RequestConfig(self.request).configure(order_items) context.update(locals()) return context -
The view course.views.coursehome didn't return an HttpResponse object. It returned None instead
Unable redirect the "return redirect(reverse('detail', kwargs={"id": instance.id}))" page. enter image description here @login_required(login_url="/login/") def coursehome(request,courseid): courseid=get_object_or_404(CourseId,courseid=courseid) instance=get_object_or_404(CourseDetails,courseid=courseid) scorm_type=get_object_or_404(scormcontent,courseid=courseid) cohome=CourseDetails.objects.filter(courseid=courseid) scormcourse=scormcontent.objects.filter(courseid=courseid) course_enroll=Enrollment.objects.filter(courseid=courseid) student_data=course_enroll.filter(student_id=request.user.id) user_id=str(request.user.id) if request.user.is_authenticated: for student in course_enroll: if user_id in student.student_id: home={ 'courseid':courseid, 'cohome':cohome, 'scormcourse':scormcourse, 'student_data':student_data, "scorm":scorm_type, } return render(request,'course_home.html',home) else: return redirect(reverse('detail', kwargs={"id": instance.id})) else: return redirect('/login') -
Django Channels With clojure environment
I have a clojure server which is a game server and need to communicate with django channels. Do anyone have any idea how to proceed with the above requirement? -
Django - How can I prevent a tenant from accessing an app in Django using django-tenant-schemas?
I have a project with that implements multi tenancy using django-tenant-schemas package. There are three ways to register an app: Installed app, shared apps, and tenant apps. I have an app that is not present in shared apps or tenant apps, only in the Installed apps list. But tenants are also able to access this app and its views. Is there a way to prevent tenants from accessing installed apps? Im very new to this kind of functionality, am I understanding it correctly? or is there another way to do this? -
User display Information in Django
I am having an issue to display students information when they've created their profile. For each student that is registered, I want to display their information on a/the home when they've logged in. I've been reading the docs and searching on implementations that are close to what I want to do but can't getting it functioning well. -
DateTimeInput is being rendered as simple text input in django
I have tried to take date time input from the user but data type of date input is being set as type="text" following are the code snippets: template: <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.min.css" integrity="sha256-DOS9W6NR+NFe1fUhEE0PGKY/fubbUCnOfTje2JMDw3Y=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js" integrity="sha256-FEqEelWI3WouFOo2VWP/uJfs1y8KJ++FLh2Lbqc8SJk=" crossorigin="anonymous"></script> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.stayFrom}} <script> $(function () { $("#id_stayFrom").datetimepicker({ format: 'd/m/y', }); }); </script> </form> forms.py: class RoomApplicationForm(forms.ModelForm): stayFrom = forms.DateTimeField(input_formats=['%d/%m/%y']) class Meta: model = Stay fields = ('stayFrom') models.py: class Stay(models.Model): user = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key = True) stayFrom = models.DateTimeField(verbose_name="stay start date") heres the rendered html: <input type="text" name="stayFrom" id="id_stayFrom" autocomplete="off"> can you point out what i'm missing in my code? -
Auto Create new User for new teanants in django
I'm trying to develop multi tenants web applications using this packages. Every things is working fine, Here one thing is missing that is automatically create new user for new tenants. I know we can create new super user using this command python manage.py tenant_command createsuperuser --schema=schema_name But i want to automatically create new user on basis of information provided by the user -
TestCase testing create order django
I writing testcase to create an order in Django and when I run test it's ok. But, I'm not sure if the testing process is correct. Or have to write anything more. my tests.py In the test of creating an order. class ItemsBuyTestCase(TestCase): def test_buy_items(self): user = self.create_user("test") buy = G(Items) order = create_order([buy], user=user) order.paymentreceived() Thanks. -
how are request handler when we use opencv with django
I am trying to make a Face detection and facial recognition system using Django so, I used OpenCV to handle all recognition thing but I am a bit confused about how the request is handled when we make a request, in views.py for each request does it generate a new OpenCV thread. def index(request): ..... ..... cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() ........... ......... and if my application is deployed somewhere and a user makes a request, does he able to use this. what will happen if a user makes a request when the Django application is deployed somewhere ? -
Is it okay to use the same working directory for development and production in docker container?
I am developing a Django project. I am new to Docker and other things related to it. I was wondering whether it is right to use the same working directory for development and production. Thanks for your time and consideration. -
How to properly submit modal forms from django with ajax?
Here I have a modal form in my template.I want to assign my group to the user from this modal form. After submitting the form I want to show the updated results in the template without refresh. For this I tried like this. But the problem here is it performs all the task pretty good but it doesn't close the modal form after submit but the submitted group goes to the ul list without refresh. Also I want to know instead of rendering html data and doing stuff like this(i think it is not good practice) Will it be better to send JsonResponse from django view to the template instead of html.If it is the good practice how can I do this and How can I handle the json data in ajax call in the template.I am very new to ajax/jquery stuff so any suggestions? def assign_group_to_user(request, pk): group = request.POST.get('group') user = get_object_or_404(get_user_model(), pk=pk) user.groups.add(group) return render(request, 'dashboard/ajax_groups_list.html') modal form <div class="modal--group"> <div class="modal fade" id="addGroup" tabindex="-1" role="dialog" aria-labelledby="addGroupTitle"> <div class="modal-body"> <form method="post" id="group-ajax-form" data-url="{% url 'dashboard:assign_group' user.pk %}"> {% csrf_token %} <div class="form-group"> <label>Group Name</label> <select name="group" class="form-control> {% for group in groups %} <option value="{{group.pk}}">{{group.name}}</option> {% endfor … -
select values from jsonfield in query set
class EMI(models.Model): emi = JSONField(default=dict) json values {"1": {"days": 1, "interest": 15, "penalty": 0.01, "amount": 32.0}, "2": {"days": 6, "interest": 6, "penalty": 0.01, "amount": 80.0}} and i want ammount in values -
How to extend the fire-base token expiry timings in django are python am using the drf firebase auth
am using fire-base auth user for login and register in my website how to extend the token expire for fire base token in django i tried by creating custom token authentication but its not useful for me -
Pillow cropper resizing instead of cropping
I am using a JQuery image cropper which uses Pillow on the back-end to crop and resize the images. I have this code working in a test project but I cannot get it to work correctly in my main project. Currently, when I crop the image it should grab the region and crop it 200x200 but what it seems to be doing is resizing the image to random aspect ratios, making it very blurry, and surrounded by black. It looks to be 200x200 but the image is very small inside the 200x200 black region. Forms.py: class UserUpdateForm(forms.ModelForm): """ Employee update form, related to: :model: 'auth.Employee', :model: 'auth.Groups' """ phone = forms.CharField(min_length=10) email_notifications = forms.BooleanField(required=False) sms_notifications = forms.BooleanField(required=False) x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = Employee fields = [ 'username', 'first_name', 'last_name', 'email', 'phone', 'badge_num', 'email_notifications', 'sms_notifications', 'image', 'x', 'y', 'width', 'height', ] widgets = { 'employee_type': forms.HiddenInput(), 'image': forms.FileInput(attrs={ 'accept': 'image/*' # this is not an actual validation! don't rely on that! }) } def save(self, commit=True): photo = super(UserUpdateForm, self).save() x = self.cleaned_data.get('x') print(x) y = self.cleaned_data.get('y') print(y) w = self.cleaned_data.get('width') print(w + x) h = self.cleaned_data.get('height') print(h + y) … -
Alternative of Flower for Celery stats if broker is AWS SQS
Flower can't be use if broker is aws SQS, for aws SQS for celery stats what can be used. -
'str' object has no attribute 'save' Django
class AgentForm(forms.ModelForm): def __init__(self, *args, **kwargs): # agents = dashboard_userlink.objects.filter(username__in=Subquery(task_router_calldetail.objects.values('agent').distinct())).values_list('username').annotate(full_name=Concat('first_name', Value(' '),'last_name')).order_by('first_name') agents = dashboard_userlink.objects.values('username').distinct().values_list('username').annotate(full_name=Concat('first_name', Value(' '),'last_name')).order_by('first_name') for i in agents: agent_name = i[0] agent_value = i[1] if agent_value == ' ': agent_value = agent_name agent_value.save() agent_list = [('','Select')] + list(agents) super(AgentForm, self).__init__(*args, **kwargs) self.fields['agent'] = forms.ChoiceField( choices=agent_list ) -
Get the values for selected multiple checkbox in Django
I am building an app with django. Now i am facing a problem with checkbox. I can retrive the values from request.POST.get(checkbox[]). But its comming with a list. Then i am making a for loop to use the slug to get the prices but here i faced like how to store it with a separate variable for each check box. As it is in loop, for different values with different variables is not possibe? How could i do it ? In my model I have one table with extras. It has SSL, SECURITY, BACKUP. If the check box of SSL and SECURITY selected then by the slug I will get the price. But i want that to add to Order model which has a fields like SSL and SECURITY . I am getting totaly confused. How should I make the model architecture. With Hosting user can buy SSL, SECURITY, BACKUP or any of them. def checkout(request): if request.method == "POST": extras_slugs = request.POST.get("checkbox[]") for slug in extras_slugs: -
process multiple csv file in python
I have multiple csv file in the following manner: items | per_unit_amount | number of units book 25 5 pencil 3 10 .. How can I calculate Total amount of the bills for all csv file in multi threaded manner ? -
My custom validators are not working django
def validate_fname(value): if value == " ": raise serializers.ValidationError("First name may not be blank") return value class UserSerializer(serializers.Serializer): username = serializers.CharField(max_length = 50, required=True, validators=[UniqueValidator(queryset=User.objects.all(),message="This username is already taken")]) first_name = serializers.CharField(validators=[validate_fname]) last_name = serializers.CharField(required=True) email = serializers.EmailField(max_length = 50, required=True, validators=[UniqueValidator(queryset=User.objects.all(),message="This email is already taken")]) password = serializers.CharField(required=True) pass2 = serializers.CharField(required=True) -
How to render nested formset and save in django?
Problem: I have a problem with third form that has nested form at first it renders properly when I delete any child form that nested from all the form gets deleted. how can I fix that End Goal: I wanted to built signup form that consists of three forms first form is basic login info, second form can have multiple instances of the single form where the user can add more form or remove it. and third form if nested from where the user also can add from or remove it. all these in under a single submit button. What I have done: At this point i'm able to build all of the forms and stored first two forms that are basic signup info and second form that have multiple instances. # model.py class Vendor(BaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) address = models.CharField(max_length=100) mobile_no = models.CharField(max_length=12) gst = models.CharField(max_length=20) code = models.CharField(max_length=20) def __str__(self): if (self.user.first_name != None): return self.user.username else: return self.user.first_name # Material/s that vendor can process class VendorMaterial(BaseModel): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) material = models.ForeignKey(Material, on_delete=models.CASCADE) class VendorProcess(BaseModel): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) process = models.ForeignKey(ProcessType, on_delete=models.CASCADE) def _get_full_name(self): return self.process full_name = property(_get_full_name) def __str__(self): return self.process.name …