Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a Django template variable in another Django template variable?
I have a Model: myModel and a list: myList Every item of the list is a field of myModel. I want to access that item as a field in the template. The only way I could think of doing this was: {% for item in myList %} {{myModel.{{item}}}} {% endfor %} or {% for item in myList %} {{myModel.item}} {% endfor %} Neither of which worked. How do I accomplish this? Using "with"? A filter? -
cant install "mysqlclient" properly
I want to learn Django, and for it I need to connect the django platform with some DB. So I decided to connect it to a MySql DB. I downloaded what needed on the side of the server, and I just left with the python staff, so when I migratting Django with the DB, it will work well. I left with the need to install MySQLdb module by using the pip command line: pip install mysqlclient But then I get this problem: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command c:\users\me\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\D4CC~1\\AppData\\Local\\Temp\\pip-install-j_b9acy5\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\D4CC~1\AppData\Local\Temp\pip-wheel-vsi0qh0m --python-tag cp37: c:\users\me\appdata\local\programs\python\python37-32\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> … -
df.style does not correctly render pivot table generated from a pandas dataframe in Django
I am trying to render a pandas DataFrame to a Django template with some style options. My problem may be related to this issue: https://github.com/pandas-dev/pandas/issues/13140. I have gone through these answers in stack overflow regarding this question: Apply CSS class to Pandas DataFrame using to_html Publishing a pandas pivot table via html How do I preserve hierarchical tables with pandas pivot_table and dataframe styles? Here is my models.py class Fruit(models.Model): fruit_name = models.CharField(max_length=20) car_name = models.CharField(max_length=20) week = models.DecimalField(max_digits=3, decimal_places=1, blank=True) price = models.DecimalField(max_digits=3, decimal_places=1, blank=True) def __str__(self): return '%s & %s' % (self.fruit_name, self.car_name) And views.py def get_fruit(request, *args, **kwargs): df = pd.DataFrame(list(Fruit.objects.all().values('fruit_name', 'car_name', 'week', 'price'))) df2 = df cols = ['week', 'price'] df2[cols] = df2[cols].apply(pd.to_numeric, errors='coerce') df3 = pd.pivot_table(df2, index='car_name', columns=['fruit_name', 'week'], values='price', fill_value='') df3_index = df3.index html = df2.style.applymap(color_red, subset=['price']).render() df3_html = df3.style \ .applymap(color_red, subset=df3_index) \ .render() context = {'html': html, 'df3_html': df3_html } return render(request, 'get_fruit.html', context) def color_red(s): color = 'red' if (-5.0 <= s >= 5.0) else 'black' return 'color: %s' % color get_fruit.html {% extends "base.html" %} {% block content %} <h1> Table</h1> {{ html | safe}} <br> <h1>Pivot table</h1> {{ df3_html | safe }} {% endblock %} The template renders as:get_fruit … -
In Django, given a model instance, how can I determine if a ForeignKey field has been fully hydrated or not?
Context: I maintain legacy Django code. In many cases my code receives multiple model objects, each of which has a ForeignKey or a manually cached property that represents the same data entity. The data entities referred to thus do not change. However, not all objects I receive have ever accessed those ForeignKey fields or cached properties, so the data may not be present on those objects, though it will be lazy-loaded on first access. I do not easily have access to/control over the code that declares the models. I want to find any one of the objects I have which has a primed cache, so that I can avoid hitting the database to retrieve the data I'm after (if none have it, I'll do it if I have to). This is because the fetch of that data is frequent enough that it causes performance issues. Django 1.6, Python 2.7. Problem I can interrogate our manually cached fields and say internal_is_cached(instance, 'fieldname') without running a query. However, I cannot do this with ForeignKey fields. Say I have a model class in Django, Foo, like so: class Foo(models.Model): bar = models.ForeignKey('BarModel') Question If I get an instance of the model Foo from … -
How to change category slug and product slug in Django Oscar?
I can't find the option to change slugs in the dashboard. Does oscar have this function bulti-in? If not, is there a library for this? Thanks! -
Django not displaying image from model
I cannot get the image to show up in my HTML template. Right now it just displays a broken image. urls.py from django.conf.urls import url, include from django.contrib import admin from home import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.index), url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) profile_picture = models.ImageField(upload_to='profile_pics', blank=True) profile.html <div class="container"> <br> <h2>{{ user }}</h2> <br> <p>Name: {{ user.first_name }} {{ user.last_name }}</p> <img src="{{ user.userprofile.profile_picture.url }}"> <p></p> <p>About Me: {{ user.userprofile.description }}</p> <p>Phone Number: {{ user.userprofile.phone }}</p> <a href="{% url 'edit_profile' %}">Edit Profile</a><br> <!-- if profile is updated succesfully --> {% if messages %} {% for message in messages %} <br><br>{{ message }} {% endfor %} {% endif %} </div> Output: https://i.gyazo.com/916ea7aad9fabb08a6cdacba67dbaf24.png I'm not sure what I'm doing wrong here. I believe that I have the medial_url/media_root set up correctly, and I can see the correct path in my directory with the image inside of it. Any help is greatly appreciated. -
Is it possible to execute npm commands using Django's execute_from_cammand_line function?
Hopefully an easy question, but I'm wondering if you can run non python core commands from a script (such as $ npm build or $ npm serve etc) using Django's execute_from_command_line() function? Surely yes! But how? What are the rules...? -
Custom Login form in Django
I'm creating a system in Django with admins(not superuser) and employees working under them. I've created admins registration and login using Django's built-in models. Now I have created custom model for employee's profile. The admin can only register the employee using his dashboard. This part has been done. Now I want to know that how to authenticate the employee's credentials so that the he/she can login to his/her own dashboard? Note that the admin and superuser are different in this case. Admin cannot access superuser's panel. I have already tried custom authentication using backends but it failed. I'm new to Django and this is the part of my first project in Django. Thank you in advance. -
How I can code the queryset then at the profile section user can see only their own post
I'm working on a project by using Django 2.06. I have multiple users and they can post and other people can read their post which is very normal. At the user profile page User should see their own post. this is where I'm stuck, How i can code the queryset then at the profile section user can see only their own post. code demo class ProfileView(ListView): template_name = "profile.html" queryset = QuickWord.objects.filter() context_object_name = 'quickword' def get_context_data(self, **Kwargs): context = super(ProfileView, self).get_context_data(**Kwargs) context['addproduct'] = AddProduct.objects.filter() context['article_view'] = Article.objects.filter() context['edit'] = Profile.objects.all().last() return context I know that I have to use filter value but do not know how to do that. Thanks -
save an integer change to a model in the database error
I am trying to add the possibility to add a quantity to the products I add to my cart. I added an integerfield to the product model as, which acts as a placeholder (want to reset it after checkout). I don't know if this is the best way to do this, but I think it might work haha :-) When I want to save the quantity, which prints fine in the terminal, it gives the following error.. How can I avoid this? AttributeError at /scan/stock/ 'int' object has no attribute 'save' Request Method: POST Request URL: http://localhost:8000/scan/stock/ Django Version: 1.11 Exception Type: AttributeError Exception Value: 'int' object has no attribute 'save' I cant figure out why quantity won't save to the database this way... def scan_to_cart(request): form = forms.ScanSessionForm() if request.method == 'POST': product = None barcode = request.POST.get('barcode_input') amount = request.POST.get('amount_input') queryset = Child.objects.filter(product_id_code=barcode) if queryset.exists(): try: # the queryset is already filtered by the barcode # now we apply an extra filter to check if this user has the product product = queryset.get(user=request.user) except Child.DoesNotExist: # here we are sure this product exists, but this user doesnt have it in the stock. messages.error(request, 'I can\'t find any inventory … -
How to show ManyToMany field while trying to django-import-export?
I have an Order model that has cart = models.ForeignKey(Cart) linking to class Cart(models.Model): items = models.ManyToManyField(Variation, through=CartItem)` that links to class CartItem(models.Model): cart = models.ForeignKey("Cart") item = models.ForeignKey(Variation) quantity = models.PositiveIntegerField(default=1) I will have all Variations for Order and I want to show quantity for each column . How do I do this? -
Django admin: best practices for keeping it secure
I'm about to release my django app to the world, but I'm worried about the admin tab. What are some best practices for keeping the admin secure? I saw thiswebsite . It mentioned changing the admin url among other things. Are there any other best practices? -
Django Authentication LDAP
I have a Django project in which I want to authenticate users against an Active Directory. Therefore, I am using the django-python3-ldap framework. I am able to sync users(./manage.py ldap_sync_users), grant superuser admin access, and login to the default Django admin page using the framework as backend. However, when I try to authenticate on my site, the user state remains AnonymousUser. views.py def login(request): try: username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user, backend=django_python3_ldap) context = {'user': user} return render(request, 'website/home.html', context) else: context = {'': ''} return render(request, 'website/login.html', context) except: print() login.html <!-- Main content --> <section class="hero is-success is-fullheight"> <div class="hero-body"> <div class="container has-text-centered"> <div class="column is-4 is-offset-4"> <div class="box"> <figure class="avatar"> <img src=""> </figure> <form method="post"> {% csrf_token %} <div class="field"> <div class="control"> <input class="input is-large" type="text" placeholder="Username" autofocus=""> </div> </div> <div class="field"> <div class="control"> <input class="input is-large" type="password" placeholder="Password"> </div> </div> <div class="field"> <label class="checkbox"> <input type="checkbox"> Remember Me </label> </div> <button class="button is-block is-danger is-info is-large is-fullwidth">Login</button> {% endblock %} </form> </div> </div> </div> </div> </section> -
"make" command permission denied
I have a Django application which has a custom folder I named codefiles. Inside it, are many subfolders with random names. Further, inside each of those folder, is a Makefile. I'm currently confused why it says OSError: [Errno 13] Permission denied when I call the following code: p = subprocess.Popen(["make", "-f", os.path.join(directory, "Makefile")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True, shell=True) What might be the problem here? -
Image encoding in django views
I have a Django project that receives an image, process it and return a response. I am writing a script to test my API, but the bytes that client sends is not the same that the server receives. Client code: # client.py from urllib.parse import urlencode from urllib.request import Request, urlopen import cv2 img = cv2.imread(image_file) data = {'image': img.tobytes(), 'shape': img.shape} data = urlencode(data).encode("utf-8") req = Request(service_url, data) response = urlopen(req) print(response.read().decode('utf-8')) Views code: # service/app/views.py import ast import numpy as np from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def process_image(request): if request.method == 'POST': shape = ast.literal_eval(request.POST.get('shape')) img_bytes = request.POST.get('image') # Reconstruct the image img = np.fromstring(img_bytes, dtype=np.uint8).reshape(shape) # Process image return JsonResponse({'result': 'Hello'}) When i run cliente code i get ValueError: total size of new array must be unchanged. I did the following checks, with a 8x8 RGB image: # client.py >> print(img.shape) (8, 8, 3) >> print(img.dtype) uint8 >> print(len(img.tobytes())) 192 # service/app/views.py >> print(shape) (8, 8, 3) >> print(len(img_bytes)) 187 The shape field is ok, but the image filed has different size. As the image is small, i printed the bytes from client and server, and i did not get the same, … -
celery: how to read celery beat config from django settings?
The celery app has function a config_from_object which I use to load configurations from the Django settings: app.config_from_object('django.conf:settings', namespace='CELERY') But with such namespace celery only load settings that starts with CELERY_ and ignores: CELERYD_CONCURRENCY, CELERYBEAT_SCHEDULER, etc. -
API Server and Content Server hosted on different domains, can't save cookies
I have a Django server hosted on localhost:8000 and I also have my contents served by another server at localhost:80. My server has a method called get tokens which returns a csrf token and also a session token. However the browser does not save the cookie even I can see the cookies at the get request response. It just ignores it. My cors is open to localhost:80. How do you save cookies if your api server and content servers are hosted in different places? What if I wanted to deploy my front end on a cdn and host my django backend on aws, how would i make the cookies work? -
Django FormSet and PEP8 naming conventions
I am wondering how I should name my formset definitions. Say I have a form called UserForm, then I would define a complementing form set like: UserFormSet = modelform_factory(User, UserForm, extra=0) Everyone post here regarding formsets seem to name theirs like the above. But PyCharm tells me thats bad because UserFormSet is not a class definition. Whats the correct way? -
Django single object update in for loop
Hi I'm wondering if it possible or how to update single model object name inside for loop by his id using object.filter(pk=id).update(name='name') function I try to do this but its not working in for loop. It's working only outside loop -
Unable to display the image through the result of CRUD operations in django
i am working on hotel booking app , in this i want to display the image of a hotel, based on user entered location . In this if i am displaying all hotels , i am able to display an image , if i am trying to displaying an image through some CRUD operations, i am unable to display it. Here are my code snippets. class Customer_details(models.Model): Name = models.CharField(max_length=128) Age = models.IntegerField() Mobile_number = models.IntegerField() Email = models.EmailField() Address = models.CharField(max_length=50) Special_request = models.CharField(max_length=50, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.Name hotel_rating_choices = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ('6','6'), ('7','7'), ) class Hotel(models.Model): Hotel_Name = models.CharField(max_length=50) location = models.CharField(max_length=20) no_of_rooms = models.IntegerField() rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3) hotel_img = models.ImageField(upload_to='hotel_images/') uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.Hotel_Name class Hotel_image(models.Model): hotel_img = models.ImageField(upload_to = 'hotel_images/') hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) def __str__(self): return self.hotel Ignore the remaining models just concentrate on Hotel model . `Below code snippet is my view regarding to query. def get_hotels_by_location(request): location = request.POST.get('location') print(location) location = location.lower() result = Hotel.objects.values('Hotel_Name', 'rating', 'hotel_img').filter(location=location) context = {'hotels': result, 'header': ['Hotel_Name', 'Rating', 'image'] } return render( request, template_name='display_hotel_by_location.html', context=context ) And below … -
why i failed to use distinct only tom remove the duplicates but instead i used values_list()
I tried to use distinct only in the following queryset, but I failed to remove the duplicates qs2=ProductColor.objects.filter(product__Name='product1').distinct() Result: <QuerySet [<ProductColor: product1>, <ProductColor: product1>]> when I used the value_list() it worked fine. qs=ProductColor.objects.filter(product__Name='product1').values_list('color',flat=True).distinct() please, any explanation why I failed to use only distinct to remove the duplicates. -
Celery task getting SoftTimeLimitExceeded
I have two tasks, where I need to call two different API to send a SMS and an email. views.py def ...: ... send_payment_failed_sms.delay(payment_log.id, 1) task_send_booking_failed_email(payment_log.id, 1) But I always get the folowing error on the task to send SMS, but the task sending email works fine: [2018-07-12 20:47:03,519: INFO/MainProcess] Received task: payments.tasks.send_payment_failed_sms[ac4f1c2a-f09d-4e79-89c9-dfe1ab26b25d] [2018-07-12 20:47:18,548: WARNING/MainProcess] Soft time limit (15s) exceeded for payments.tasks.send_payment_failed_sms[ac4f1c2a-f09d-4e79-89c9-dfe1ab26b25d] [2018-07-12 20:47:18,563: WARNING/ForkPoolWorker-1] on_failure [2018-07-12 20:47:18,563: WARNING/ForkPoolWorker-1] ac4f1c2a-f09d-4e79-89c9-dfe1ab26b25d [2018-07-12 20:47:18,564: WARNING/ForkPoolWorker-1] 'ac4f1c2a-f09d-4e79-89c9-dfe1ab26b25d' failed: SoftTimeLimitExceeded() [2018-07-12 20:47:18,564: ERROR/ForkPoolWorker-1] Task payments.tasks.send_payment_failed_sms[ac4f1c2a-f09d-4e79-89c9-dfe1ab26b25d] raised unexpected: SoftTimeLimitExceeded() Traceback (most recent call last): ... billiard.exceptions.SoftTimeLimitExceeded: SoftTimeLimitExceeded() tasks.py @shared_task(bind=True, base=MyBaseClassForTask, max_retries=5, default_retry_delay=1 * 60, soft_time_limit=15, time_limit=30) def send_payment_failed_sms(self, payment_id, reason): try: try: payload = "" headers = {'content-type': 'application/x-www-form-urlencoded'} url = 'https://sms-site.com/apikey=' + api_key + '&to=%s&var1=%s' % ( mobile, payment_log.id ) response = requests.request("GET", url, data=payload, headers=headers) response = response.json() if response['Status'] == 'Success': print('Sent message'), response['Details'] else: print('Error:', response['Details']) except ConnectionError as exc: print('connection error @ failed sms') raise self.retry(exc=exc) except PaymentLog.DoesNotExist: ... Also, it does not retry for the max_retries, i.e., 5 times. Can you please tell me what I am doing wrong? -
Trace single request from start to finish in Django / Python
Is there a way in Django to uniquely trace a single request from start to finish? Specifically. I'd like to know that the request in BeforeViewMiddleware is the same as the one in ResponseMiddleware. Currently I use request.session: # executes at start of processing class BeforeViewMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): id = insert_data_into_table() request.session["id"] = id # executes when all processing is done class ResponseMiddleware(object): def process_response(self, request, view_func, view_args, view_kwargs): # Match the request with the request in BeforeViewMiddleware id = request.session["id"] update_table(id) However, this fails if two or more requests are made from the same session at about the same time. It then become race conditions where the one that started first might finish last and the IDs get mixed up. -
How do I get the request argument from django-filters.FilterList
I'm still struggling with django-filter. I have my filter defined below class MasterListFilter(django_filters.FilterSet): project = django_filters.ModelChoiceFilter( label='Projects', name='project_fkey', queryset=Project.objects.filter(deleted__isnull=True) ) class Meta: model = Task fields = ['project'] @property def qs(self): parent = super(MasterListFilter, self).qs user = get_current_user() return parent.filter(master=True, deleted__isnull=True, user_fkey=user.id) This works perfectly fine. However I also want to filter the dropdown filter (ie the Project queryset) by the current user. As my user is logged in and authenticated, I believe the user details should be attached to the request. According to the django-filter docs The FilterSet may be initialized with an optional request argument. If a request object is passed, then you may access the request during filtering. This allows you to filter by properties on the request, such as the currently logged-in user or the Accepts-Languages header. So it would seem that the request is there, but I can't work out how to access it as an argument of the FilterSet, nor have I been able to find any examples in the docs or anywhere else in my travels as to how to do it. So if anyone can give me any clues at all, I really would appreciate the help. Thanks in advance and happy … -
Integrating Bulma/Sass With Django
I have a Django project that I would like to integrate with Bulma/Sass using the django-sass-processor framework. Upon initial file creation I am able to compile .scss to .css, but when I try: sass website.scss --watch I get ERROR: --watch is not allowed when printing to stdout. Why am I receiving this error? Please let me know if any other information is needed. root -> website -> static -> css - website.css - urls.py - views.py - website.scss `