Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR:pinax-images 4.0.1 has requirement pillow>=7.1.2, but you'll have pillow 5.0.0 which is incompatible
this error occured when i was trying to install the requirements.txt from the pinax-project-blog app. pinax-images 4.0.1 has requirement pillow>=7.1.2, but you'll have pillow 5.0.0 which is incompatible. -
How to save full GET request in Django
I'm using Django 3.0.7, and i need to save full GET request, with authorization header query parameters etc. it is don't matter what format it should be: json, dictionary or just string. I've tried to do this somehow like this: if request.method == 'GET': serializer = MyHandlerSerializer(data=request.data) data = {} if serializer.is_valid(): getrequest = request return Response({"response_code":"OK"}) class MyHandlerSerializer(serializers.ModelSerializer): class Meta: model = MyHandler fields = ['getrequest', ] But its didn't work. Iwoulb apriciated if you help me with it. -
How to get value from nested <span> tags by .find method in beautifulsoup
I am trying to get an information stored in nested tag by beautifulsoup in my new python project of CRAIGLIST CLONE app using dJango framework. import requests from bs4 import BeautifulSoup from django.shortcuts import render from requests.compat import quote_plus from . import models BASE_CRAIGLIST_URL = 'https://ahmedabad.craigslist.org/search/?query={}' search = request.POST.get('search') models.Search.objects.create(search=search) final_url = BASE_CRAIGLIST_URL.format(quote_plus(search)) print(final_url) response = requests.get(final_url) data = response.text soup = BeautifulSoup(data, features='html.parser') post_listings = soup.find_all('p', {'class': 'result-info'}) final_postings = [] for post in post_listings: post_title = post.find(class_='result-title').text post_url = post.find('a').get('href') post_price = post.find('span', class_='result-price') final_postings.append((post_title, post_url, post_price)) stuff_for_front_end = { 'search' : search, 'final_postings': final_postings, } return render(request, template_name='myapp/new_search.html', context=stuff_for_front_end) I tried this code and i got "None" in output.See the 3rd line below the submit button -
What does Service Providers and Bootstrapping literally mean in Laravel?
This is an excerpt from official laravel docs "Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services are bootstrapped via service providers." What's service providers really? I can't understand the meaning of the words. Does bootstrapping the app happens everytime a request comes through the public/index.php or does it happen one time when apache or nginx gets activated? What does "deploying a laravel project" literally mean? (I know that it's putting on a server but is there more to it?) Why do we need bootstrapping the app? Isnt php just a script that takes the request and does something everytime it passes through? -
django multiField render and labels
i need to create a multifield that will hold the FirstNameMiddle Name and LastName for a person. the problem is that i cannot display the lables of those field on the form and the layout is terrible here is what i do class FullNameWidget(forms.MultiWidget): def __init__(self, *args, **kwargs): widgets=[ forms.TextInput(), forms.TextInput(), forms.TextInput() ] super(FullNameWidget, self).__init__(widgets, *args, **kwargs) def decompress(self,value): if value: return value.split(' ') return [None,None,None] class FullNameField(forms.MultiValueField): widget=FullNameWidget def init(self, *args, **kwargs): fields = ( forms.CharField(label='الاسم الاول',widget=forms.TextInput(attrs={'placeholder':'الاسم الاول','id':'FName'})), forms.CharField(label='اسم الاب'), forms.CharField(label='اسم العائلة') ) super(FullNameField, self).__init__(fields,*args, **kwargs) def compress(self, data_list): return ' '.join(data_list) in the the main class of the form: empName=FullNameField(label='الاسم الثلاثي') in the form.html <div class="form-group"> {{form.empName | as_crispy_field}}</div> the out put is like this enter image description here how can i add labels to each field and how can i have spaces btween them -
django returning the total number of items in a model
I would like to return the total number of items I have in a databse from the following simple model: class EquipmentType(models.Model): type = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=250, default='') date_posted = models.DateTimeField(auto_now_add=True) # auto_now = timezone.now image =models.ImageField(default='default.jpeg', upload_to='equipment/equipment_type') active =models.BooleanField(default=True) Below the model I've defined the following function: @property def get_total_num(self): total = 0 equipmentType = EquipmentType.objects.all() for type in equipmentType: total = total + 1 return total which I call in the template with a simple for testing: <h3>numero tot: {{get_total_num}}</h3> The db has about 44 objects, thus I would expect the function, once called, to return that number. Unfortunately it returns nothing (just the string 'numero tot'). This is the class based view I'm using: class EquipmentType_ListView(LoginRequiredMixin, ListView): model = EquipmentType template_name = 'equipment/equipmentType_list.html' # default = <app>/<model>_<viewtype>.html context_object_name = 'obj_list' def get_queryset(self): return EquipmentType.objects.filter(active = True).order_by('type') Any suggestion on what is actually missing? Thank you very much. Carlo -
Receive call back in view method django
I build a Django app which is work as a broker between user and payment gitway and user send data using query string some of this data will be needed after I call gitway api and I receive callback from it. My question is how can I receive callback and still inside my view method to keen the data that user send with me which I will use it depend on data callback?! Note: from documentation of gitway I know that I need to add link in my gitway dashboard which will be called when respond be ready and some people told me that I need to use what is called web hook but my broblem is how can I use it with out lose the data that user send ?! -
How do I use SELECT and WHERE by Django ORM?
So what I"m trying to do in SQL is this: FROM TABLE SELECT question WHERE number === 3 AND type === "text" Obviously, I have to columns-question and number and type. How do I write this in Django? Thank you very much. -
Django logout after inactivity AND when web browser tab is closed: unable to set browser close behavior
I try to implement a 'normal' behavior for web site: when user is inactive for x minutes he should be logout and redirect to the login page when user close web browser tab, he is logout and have to login when access the web site again But I did not manage to get this behavior. Currently, if user is inactive for 1 minute he is logout but not automatically redirected to login page so user think he is still login. He will be redirected to login page when try to navigate after 1 minute of inactivity. And if user close his web browser tab before 1 minute of inactivity and access again the web site he don't have to login again. settings.py: TIME = 60 SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' SESSION_COOKIE_AGE = TIME SESSION_IDLE_TIMEOUT = TIME SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True I have tryed to implement a custom middleware (stackoverflow post here Is there a way to combine behavior of SESSION_EXPIRE_AT_BROWSER_CLOSE and SESSION_COOKIE_AGE) but doesn't change behavior. I also try to install django-session-security but neither works like I would like. As DJango simplify every things, I surprised it is so complicated to implement this normal behavior -
Django order tracking timeline
So , I have created a function for customers to track their orders. The admin can change the status of the order by selecting from the select list and the customers can simply enter their order id and can check their order status updated by the admin. Now I want to create a timeline of status changes with status and timestamp fields in order model. I know I have to create another model for that to save the changes in it, but I'm confused what fields I need to add in the new model and how can I connect it to the order table and what changes I have to make in my views function. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") timestamp = models.DateTimeField(default=timezone.now(), blank=False) def order_tracker(request): if request.method=="POST": orderId = request.POST.get('orderId', '') try: order=Order.objects.filter(pk=orderId) if len(order)>0: update = Order.objects.filter(pk=orderId) updates = [] for order in update: if order.status == 'In Progress': order.status = 'Scheduled' order.save() updates.append({'status' : order.status, 'time': order.timestamp}) response = json.dumps(updates, default=str) return HttpResponse(response) else: … -
heroku logs --tail > ModuleNotFoundError: No module named 'whitenoise' on the
These questions don't seem to get much attention but i want to try anyway. I'm having a very hard time trying to deploy my website with some static files on heroku. The deployment went well but when i run the heroku logs --tail this is what i get: heroku logs --tail [(ruby-2.7.0)] 2020-07-21T06:57:52.130087+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2020-07-21T06:57:52.130087+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2020-07-21T06:57:52.130088+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2020-07-21T06:57:52.130088+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2020-07-21T06:57:52.130088+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 783, in exec_module 2020-07-21T06:57:52.130088+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-07-21T06:57:52.130089+00:00 app[web.1]: File "/app/mywebsite/wsgi.py", line 16, in <module> 2020-07-21T06:57:52.130089+00:00 app[web.1]: application = get_wsgi_application() 2020-07-21T06:57:52.130089+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-07-21T06:57:52.130090+00:00 app[web.1]: django.setup(set_prefix=False) 2020-07-21T06:57:52.130090+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2020-07-21T06:57:52.130090+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2020-07-21T06:57:52.130090+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate 2020-07-21T06:57:52.130091+00:00 app[web.1]: app_config = AppConfig.create(entry) 2020-07-21T06:57:52.130091+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 116, in create 2020-07-21T06:57:52.130091+00:00 app[web.1]: mod = import_module(mod_path) 2020-07-21T06:57:52.130092+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2020-07-21T06:57:52.130092+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-07-21T06:57:52.130092+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2020-07-21T06:57:52.130092+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2020-07-21T06:57:52.130093+00:00 … -
Creating a form to upload text and images in Django
I am creating facebook clone, i want to create a form for creating posts for the wall, which will allow to upload text and multiple images (not limited, but could be no images too) . The code presented below does not work, after filling the form, images field is clearing and there is an info that this field is required, but as i guess, i am not even close to solve this problem correctly. Here are my files: models.py (a part that is useful) from django.db import models from homepage.models import MyUser def post_directory_path(instance, filename): return f"users/{instance.post.user.id}/posts/{instance.post.id}/{filename}" class Post(models.Model): published = models.DateTimeField(auto_now_add=True) text = models.TextField() user = models.ForeignKey(MyUser, on_delete=models.CASCADE) def __str__(self): return f'{self.published} by {self.user}' class Image(models.Model): image = models.ImageField(upload_to=post_directory_path, blank=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return f'{self.id}' forms.py from django import forms from .models import Post, Image class PostForm(forms.ModelForm): text = forms.CharField(widget=forms.Textarea, label='', max_length=10000) class Meta: model = Post fields = ['text'] class ImageForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}), label='') class Meta: model = Image fields = ['image'] views.py (a part that is useful) from django.shortcuts import render, redirect from homepage.models import MyUser from . models import UserProfile from .forms import PostForm, ImageForm def wall(request): if request.method == "POST": … -
Django - Conflict between my django models.py files
I don't see any conflicts with the following. What am I doing wrong? I get the following error ImportError: cannot import name 'Business' from 'business.models' I assume maybe I am doing some type of circular loop, but I do not see it.: #links/models.py from django.db import models class LinkType(models.Model): link_type = models.CharField(max_length=30) def __str__(self): return self.link_type from business.models import Business class Link(models.Model): name = models.CharField(max_length=60) business = models.ForeignKey(Business, on_delete=models.CASCADE) link_type = models.ForeignKey(LinkType, on_delete=models.CASCADE) class Meta: unique_together = ['business', 'link_type'] def __str__(self): return self.name #business/models.py from django.db import models from links.models import LinkType class Business(models.Model): name = models.CharField(max_length=255) main_link_type = models.ForeignKey(LinkType, on_delete=models.CASCADE) def __str__(self): return self.name -
Get a QuerySet only linked to the particular slug
I want to display a QuerySet("link" parameter in below html) only linked to the particular slug. However I am getting all QuerySets by below codes. I feel I need to use a filter function but not sure where I need to place exactly. Could you advise the solution? models.py class Conversation(models.Model): title_in_English = models.CharField(max_length=255) titleslug = models.SlugField() def __str__(self): return self.titleslug class Meta: ordering = ["titleslug"] class Conversationtext(models.Model): title = models.ForeignKey(Conversation, on_delete=models.CASCADE) english_conversations = models.CharField(max_length=255) #I want display only liked to the "particular title_in_English" english_pronunciation = models.CharField(max_length=255) #I want display only liked to the "particular title_in_English" views.py def blog_conversation(request, conversation): posts = Conversation.objects.filter(titleslug__contains=conversation).distinct() lists = Conversationtext.objects.distinct() context = {"conversation": conversation, "posts": posts, "lists": lists,} return render(request, "blog_conversation.html", context) html {% for i in posts.all %} <p>{{i}} <p>{{i.title_in_English}} {% endfor %} {{ lists }} {% for i in lists %} <p>English --> {{i.english_conversations}} -> I got all english_conversations queries <p>English --> {{i.english_pronunciation}} -> I got all english_pronunciation.queries {% endfor %} -
Django Serializer - non django model fileds include
i want to list my all employee details. i am using Django serializer. my models class RFID(models.Model): RFID = models.AutoField(primary_key=True, db_column='RFID') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, db_column='EmployeeId') RFIDCode = models.BigIntegerField(unique=True, default=None, null=False, blank=False) class Meta: db_table = "RFID" class Employee(models.Model): EmployeeId = models.AutoField(primary_key=True, db_column='EmployeeId') EmployeeCode = models.CharField(max_length=50, unique=True, null=False, blank=False) EmployeeName = models.CharField(max_length=50) EmployeeStatus = models.SmallIntegerField(default=1, null=True, blank=True) Security = models.SmallIntegerField(default=0, null=True, blank=True) Device = models.ManyToManyField(Device, through='EmployeeDevice') class Meta: db_table = "Employee" my serilalizer class RFIDSyncSerializer(serializers.ModelSerializer): class Meta: model = RFID fields = ['RFID', 'RFIDCode'] class EmployeeSerializer(serializers.ModelSerializer): rfid_set = RFIDSyncSerializer(read_only=True, many=True) class Meta: model = Employee fields = ['EmployeeId', 'EmployeeName', 'EmployeeCode', 'EmployeeStatus', 'Security', 'rfid_set'] my views.py @api_view(['GET']) @permission_classes([IsAuthenticated]) def employee_list(request): try: employee = employee = Employee.objects.filter(~Q(EmployeeStatus=2)) serializer = EmployeeSerializer(employee, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as ex: return Response({msg: repr(ex)}, status=status.HTTP_400_BAD_REQUEST) currently my result [ { "EmployeeId": 21, "EmployeeName": "ss", "EmployeeCode": "10", "EmployeeStatus": 1, "Security": 0, "rfid_set": [] }, { "EmployeeId": 1, "EmployeeName": "namechagnge", "EmployeeCode": "Emp-01", "EmployeeStatus": 1, "Security": 0, "rfid_set": [ { "RFID": 74, "RFIDCode": 408 } ] } ] i want to include an extra data to this.. i want to add an extra field Rfid = true , if RFID present and Rfid= false if Rfid not present … -
Django Model hh:mm field
I have a Django model which I want to add a start time and an end time, hh:mm. I am not sure what field type is best for this, string with regex? The DateTimeField seems to just add the full date/time (as it suggest :)). Any tips greatly appreciated -
How do I load images in React with Django?
├───migrations │ └───__pycache__ ├───src │ ├───actions │ ├───components │ │ ├───accounts │ │ ├───common │ │ └───Layout │ ├───reducers │ └───validations ├───static │ └───frontend │ └───images ├───templates │ └───frontend └───__pycache__ The image I want to load in in the Layout folder and it's logo.png. I want to import that image to the same directory with Layout.js I did something like this. import spinner from "../spinner.gif"; This is my webpack.config.js module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, }; When I'm using create-react-app I can import that image but when I'm using this custom way I can't. -
Django Populating Table From Database
I can't get a table to populate with integers from database every time I click button (not really a button but with ajax inputs into db fine). Here is the code. Html: {% if past %} <table border="1"> <thead> <th>Past</th> </thead> {% for nums in past %} <tbody> <tr> <td>{{ nums.numbers }}</td> </tr> </tbody> {% endfor %} </table> {% else %} <p>error</p> {% endif %} Views.py: def main(request): prev_rng = 'X' if request.method == 'POST': rolled_num = PastRng(numbers=request.POST['rngInput']) rolled_num.save() prev_rng = PastRng.objects.all() login_names = Players.objects.all() context_dict = {'past': prev_rng, 'names': login_names} print(context_dict) return render(request, 'main/rngmain.html', context=context_dict) urls.py: from django.urls import path from main import views app_name = 'main' urlpatterns = [ path('rules/', views.rules, name='rules'), path('main/', views.main, name='main'), path('', views.index, name='index'), ] main.models: class PastRng(models.Model): numbers = models.IntegerField(unique=False) def __int__(self): return self.numbers Everything works fine accept the actual display of the database info in the table. Pretty sure views.py is the problem. Any help would be awesome! -
Hashing In Django Views
I'm passing data through ajax by attaching it to my element. The data is sensitive that if a user changes it they could change the associated field of another user (not sensitive like a password). I want to hash this data (student_id) prior to inserting it into the template, then unhash it in my view when I receive it from ajax. I can't find how to do this in Django. <form> {% csrf_token %} # student_id is the sensitive data <td class='class_complete' student_id='{{ student.student.id }}' name='completed' value='{{ class.id }}'>{{ item.completed }}</td> </form> def post_form_api(request): data = {} if request.method == "POST": class_id = request.POST.get("class_id") student_id = request.POST.get("student_id") student_class_data_entry = get_object_or_404(StudentClassData, student_id=student_id, class_id=class_id) form = StudentClassDataForm(request.POST, instance=student_class_data_entry) [.. other logic .] if form.is_valid(): form.save() data = {'result' : True} if request.is_ajax(): return JsonResponse(data) else: return HttpResponseBadRequest() $(".class_complete").click(function(e){ var csrfToken = $("input[name='csrfmiddlewaretoken']"); class_id = $(this).attr('value'); student_id = $(this).attr('student_id'); var checked = $('#'+e.target.id).is(":checked"); $.ajax({ url: "/api/post_form/", type: "POST", dataType: "json", data: {'completed':checked, 'student_id':student_id, 'class_id':class_id, 'csrfmiddlewaretoken':csrfToken.val()}, cache: false }).done(function(data) { if (data.result === true){ } else { } }); }); Thank you. -
django url pattern strips forward slash when running in nginx+uwsgi
For the following url pattern: re_path(r'proxy/(?P<url>.*)', myview) When I send proxy/http://www.google.com myview function receives url as http:/www.google.com (with single /) It happens with uwsgi+nginx setup , when running with runserver url is http://www.google.com . -
How to print a file to an html page in django
I have a Django application where the logging is being printed to a file using the logging module. I want to be able to have the contents of the log file also display on an html page such if a new line gets printed to the log page, the html page will also actively update to display the new line without having to be refreshed. How can that be accomplished? -
How to send POST request after form submit 302 in Django?
I have an implimentation as follows, There is a payment form wherein user fills all the details.(API1), here I'm getting 302. On submit of that form one of the function in my views is called. In the backend implimentation ie. in views.py, I want to send a POST request to one of the gateways I have integrated.(API2) But the problem is coming as the request is going as GET and hence it is dropping all the form data I'm sending along with the request. Following is the code for the same, views.py --> headers = { 'Content-Type': 'application/x-www-form-urlencoded', } payload = { 'CustomerID': 'abc', 'TxnAmount': '1.00', 'BankID': '1', 'AdditionalInfo1': '999999999', 'AdditionalInfo2': 'test@test.test', } payload_encoded = urlencode(payload, quote_via=quote_plus) response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers) content = response.url return_config = { "type": "content", "content": redirect(content) } return return_config How do i send the 2nd request(API2) as POST request along with all params? What am i doing wrong here? Thank you for your suggestions. -
How to change one field on a model when another is changed? (an elegant way)
I have a model to store articles. This model has an HTML field to store article's content. This field contains tags and encoded images. I need to realise full text search using standart PostgreSQL mechanisms. Also it should use trigrams. I've already realised it, but it works quite slow cause inserted in an article's content images have big sizes and they are encoded as a text. So, I decided to make an additional field to store a content of an article with no tags and images. (clean it using striptags function on the level of app) It seems this solution works very well, but now I have another issue.) I need to sync values of the fields somehow. When I change the content I need to remove tags and change cleaned content field as well. It seems signals should be helpfull in that case but they don't work when I use update() method on model's manager. Could you reccomend smth to achieve this goal of fields sync more elegant way? -
Django -Join 2 model in query
class Item(models.Model): CATEGORY = ( ('Gudang Kering', 'Gudang Kering'), ('Gudang Basah','Gudang Basah'), ) name = models.CharField(max_length=200,null= True) stock = models.IntegerField(default='0', blank=False, null=True) category = models.CharField(max_length=200,null= True,choices=CATEGORY) description = models.CharField(max_length=200,null= True, blank= True) date_created = models.DateTimeField(auto_now_add= True) tags = models.ManyToManyField(Tag) class Issue(models.Model): STATUS = ( ('Pending', 'Pending'), ('Granted','Granted'), ('Denied','Denied'), ) customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) item = models.ForeignKey(Item, null=True, on_delete= models.SET_NULL) quantity = models.IntegerField(default='0', blank=False, null=True) date_created = models.DateTimeField(auto_now_add=True, auto_now=False) status = models.CharField(max_length=200,null= True, choices=STATUS) "Hello,sorry im tyring to learn django and want to ask,how to write a query to calculate objects where if the 2 have the same item and status granted ,it will calculate stock - quantity, i want to save the value to be new value of stock in database" -
How do I check if a day has passed, in Django?
I'm trying to make an application that gives user a quiz everyday. So I need to check if a day has passed in Django. I know I can do this in JavaScript, but is there a way in Django? Do I have to work in the views.py, or template tags? Thank you very much in advance.