Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Clarification of guide to Heroku Celery
I'm trying to figure out the woeful instructions here Under the section "Configuring a Celery app" I'm not sure where i put the code: import os app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) Any clarification of these instructions is greatly appreciated. -
Get values in column between two dates in another columns in Python Django
kindly request function to get and calculates values in between time period with Python-Django function the database example will be as below **Case(1) start_time = 01-11-2019 end_time = 15-12-2019 rate = 35.00 Case(2) start_time = 16-12-2019 end_time = 31-12-2019 rate = 50.00** i need function to calculate the rate as following : user will request the period from 13-12-2019 till 18-12-2019 rate calculated [(13, 14, 15 December) = 35+35+35 = 105] + [(16, 17 , 18 December = 50+50+50 = 150] with total rate finally 255 class Items(models.Model): name = models.CharField(max_length=200, db_index=True) class Item(models.Model): name = models.ForeignKey(Items, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() rate = models.DecimalField(max_digits=3, decimal_places=2) -
Does Django Support computing the most common value of a group by expression?
What would be the beaten path to computing the most common value in a group by? We're using the postgresql engine, which supports computing the most common value in a group by with mode() WITHIN GROUP (ORDER BY sort_expression). Do we have to go to SQL or Func expressions to access this function? Or is there some better way? -
How to render a User's name as text without refreshing the page in Django?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. My page currently loads, but when I check the network using F12, there is never a call to the function/url that searches for the name to display it on the page. I'm not sure where I might be missing the part that connects these two areas of the code, but I … -
Hidde url media Django Rest
Hello i have my django rest project in production with the url url/api/media/ with all my media files, but y need hidden this url and only leave his own files available I want to hide url/api/media. Need the url return 404 o 301 and url/api/media/file_owner_01.png return the file -
Why does `migrate` won't run after installing PostgreSQL database?
I installed PostgreSQL, set up a server and adapted my Django project settings to use that DB. Now when I try to migrate the changes made, I end up with the following error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Program Files\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Program Files\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Program Files\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Program Files\lib\site-packages\django\core\management\commands\migra te.py", line 232, in handle post_migrate_state = executor.migrate( File "C:\Program Files\lib\site-packages\django\db\migrations\executor.py", li ne 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_i nitial=fake_initial) File "C:\Program Files\lib\site-packages\django\db\migrations\executor.py", li ne 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_ initial) File "C:\Program Files\lib\site-packages\django\db\migrations\executor.py", li ne 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Program Files\lib\site-packages\django\db\migrations\migration.py", l ine 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, projec t_state) File "C:\Program Files\lib\site-packages\django\db\migrations\operations\field s.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Program Files\lib\site-packages\django\db\backends\base\schema.py", l ine 534, in alter_field self._alter_field(model, old_field, new_field, old_type, new_type, File "C:\Program Files\lib\site-packages\django\db\backends\postgresql\schema. py", line 122, in _alter_field super()._alter_field( File … -
Add Product by Category in Django with out using form.py
I am trying to insert my product by category in django.I have two model Product and Category.I want to add Product in Product table.when i add product category comes in select box and select category .Category id in category value. which is insert in product table.Category is ForeignKey. But show this erroer: Cannot assign "'1'": "Product.p_c_name" must be a "Category" instance. 1 is the value of category id. model.py: from django.db import models from django import forms # Create your models here. class Category(models.Model): c_name = models.CharField(max_length=50) def _str_(self): return self.c_name class Product(models.Model): p_name = models.CharField(max_length=255) p_desc = models.TextField() p_price = models.CharField(max_length=255) p_date=models.DateTimeField(auto_now_add=True) status = models.BooleanField() p_c_name = models.ForeignKey(Category, on_delete=True) image = models.ImageField() def __str__(self): return self.p_name my view.py: # Product Start form here def product_add(request): print(request.POST) cats = Category.objects.all() if request.method == 'POST' and request.FILES['image']: p_name = request.POST['p_name'] p_desc = request.POST['p_desc'] p_price = request.POST['p_price'] p_c_name = request.POST['p_c_name'] status = 0 myfile = request.FILES['image'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) data = Product(p_name=p_name,image=filename,p_desc=p_desc,p_price=p_price,p_c_name=p_c_name,status=status) data.save() return redirect('/product/product-list',{ 'uploaded_file_url': uploaded_file_url }) else: return render(request,'product/add.html',{'cats':cats}) my form.html: <form class="text-center border border-light p-5" method="POST" action=""enctype="multipart/form-data"> {% csrf_token %} <!-- Name --> <input type="text" id="defaultContactFormName" class="form-control mb-4"name="p_name" placeholder="Product Name"> <input type="text" … -
Pass data between different views in Django
I have a basic view that retrieves some data, renders my page and sends some data to this page: def myview(request) one = values.objects.get(user=request.user).address two = values.objects.get(user=request.user).number return render(request, "main/mytemplate.html", context={'address': one, 'numbers': two}) So the values retrieved by those two queries are shown on my page. Now, on the same page, called mytemplate.html, i'm using another view, which is supposed to handle a form and some other operations: def secondview(request): if request.method == 'POST': if 'button1' in request.POST: form = MyForm(request.POST) # check whether it's valid: if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() return HttpResponseRedirect(request.path_info) else: form = MyForm() return HttpResponse('it works!') How can i use the data retrieved by those two queries in the second view? The queries are executed when the page is loaded by the first view. Then, in the same page the second view is used. I want to use the two variables one and two in the second view. Is there a way to do this in Django? Why don't you make the same queries in the second view? Because i would like the second form to be as fast as possible in terms of reload, without having to do a DB … -
python requests library .json() + django 500
When I use the requests library with django and I get a 500 error back. response.json() gives mi this error: response = requests.post(....) print("-----------------------block found!!!-----------------------") print(response.status_code) print(response.json()) json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Is there a way to represent a django 500 response with the requests library in a readable manner? -
is there seemlier way in django like MVC to request function like this AllowAnonymous Attribute in ASP.NET MVC 4
is there attribute allowanonymous in python like in mvc AllowAnonymous Attribute in ASP.NET MVC 4 -
Passing an base64 throught a hidden form and decoding it results in a black image with a square
I have a simple drawing app made with konva js, and i want to save the image to the db. I have set up an hidden form that receives the base64 from Javascript but i think there is some problem with the passage of information from javascript to the form -
eventlet with django and python socket io
whenever i try connecting client to ther server, it connects succesully and when client fires an event 'chat' with some data, it gets response back as: "received your msg" + data sent "welcome" Whenever client fires 'chat' event server(sio) also fires 'chat' event but in case server itself want to fire an event 'chat' to the client it doesn't work I tried different things like import eventlet eventlet.monkey_patch() then I tried sio.start_background_task() after that I also tried normal threading but that doesn't worked too. apart from that I also tried eventlet.spawn() but still no improvement. How should I proceed? socketio_app/views.py import threading import time import eventlet eventlet.monkey_patch() from django.shortcuts import render # Create your views here. import socketio sio = socketio.Server(async_mode='eventlet') @sio.event def connect(sid, environ): print('connected to ', sid) return True @sio.event def disconnect(sid): print("disconnected", sid) @sio.on('chat') def on_message(sid, data): print('I received a message!', data) sio.emit("chat", "received your msg" + str(data)) sio.emit("chat", "welcome") @sio.event def bg_emit(): print("emiitting") # sio.emit('chat', dict(foo='bar')) sio.emit('chat', data='ment') def bkthred(): print("strting bckgroud tsk") while True: eventlet.sleep(5) bg_emit() def emit_data(data): print("emitting strts") # sio.start_background_task(target=bkthred) eventlet.spawn(bkthred) supervisord.conf [program:gunicorn] command=gunicorn --name ProLogger-gunicorn --workers 2 ProLogger.wsgi:application --bind 0.0.0.0:8000 --timeout 100 -k eventlet #directory=/home/ubuntu/ProLoggerBackend/ directory=/home/nimish/PycharmProjects/ProLoggerBackend/ProLogger/ stdout_logfile=/home/ubuntu/logs/gunicorn_output.log stderr_logfile=/home/ubuntu/logs/gunicorn_error.log autostart=true autorestart=true startretries=10 environment=PYTHONUNBUFFERED=1 … -
How to create interactable filters on the template that filters the queryset based on model attributes immediately for display in a Django app?
I'm new to django and I'm trying to create a webapp that displays products in the database and allows users to filter through them. For example, consider a model class Products and it has attributes like brand, color etc. I am querying for all objects in Products in a view function and passing them to the html templates to display them. I want to achieve the functionality for the website to be able to filter the products by brand, color using something similar to checkboxes or radio buttons like this. So, As soon as I check/uncheck the checkboxes, the products displayed should change on the same page based on the attributes the user has checked. However I have no idea as to how I can achieve this kind of functionality. I was hoping someone with more experience would help me point out what I should be looking at. Just in case the text isn't clear, Here's my sample code. Products Model class from django.db import models class Brands(models.Model): name = models.CharField(max_length=50) class Colors(models.Model): name = models.CharField(max_length=50) class Products(models.Model): name = models.CharField(max_length=100) brand = models.ForeignKey(Brands, on_delete=models.CASCADE) color = models.ForeignKey(Colors, on_delete=models.CASCADE) Views function def show_all_products(request): all_products = Products.objects.all() return render(request, 'app/products.html', context={'all_products': … -
Password reset Confirm Mail in Django2 Not giving good URL
I am trying to make use of password_reset_confirm in built function in Django2.0 but send the sending message to email, I was getting error in my url. Please, is uidb64 not working on Django2.0 url.py #path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm'), The e-mail http://127.0.0.1:8000{% url "password_reset_confirm" uidb64=uidtoken=token %} -
Count on filefield with None value is not zero
I have referred to the similar questions below: Django - FileField check if None How to save FileField with None in Django? Yet I am unable to solve my case. My model FileField looks like: document = models.FileField(upload_to=habCompletionDocPath, null=True) I uploaded a file and deleted. q = ProgressQty.objects.get(id=id) q.document = None q.save() Now the value of the field is showing None: In [80]: q.document Out[80]: <FieldFile: None> I need to count the number of files uploaded in the table. However, I am unable to do so because of this: ProgressQty.objects.exclude(document=None) <ProgressQty: 269891toubul> as I was expecting <QuerySet []> How do I get correct result from this code: objects.annotate(doc=Count('document')) -
I've got error message : TypeError: unsupported operand type(s) for %: 'DeferredAttribute' and 'dict' in django
I created new model in my django rest freamework app and I've got this error message : TypeError: unsupported operand type(s) for %: 'DeferredAttribute' and 'dict' here is the error screenshot: I can't understand what's the problem? Here is my models.py: from django.db import models class TblUserAccounts(models.Model): uid = models.AutoField(primary_key=True) username = models.CharField(unique=True, max_length=20) alias_username = models.CharField(unique=True, max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'tbl_user_accounts' ordering = ['uid'] class TblUserDetails(models.Model): detail_id = models.IntegerField(primary_key=True) useraccount = models.ForeignKey(TblUserAccounts, models.DO_NOTHING, related_name=TblUserAccounts.uid) first_name = models.CharField(max_length=25, blank=True, null=True) last_name = models.CharField(max_length=45, blank=True, null=True) birthdate = models.DateTimeField(blank=True, null=True) record_time = models.DateTimeField() creator = models.ForeignKey(TblUserAccounts, models.DO_NOTHING, related_name=TblUserAccounts.uid, db_column='creator') class Meta: managed = False db_table = 'tbl_user_details' ordering = ['record_time'] class TblUserPassword(models.Model): id_password = models.AutoField(primary_key=True) useraccount_id_pwd = models.ForeignKey(TblUserAccounts, models.DO_NOTHING, related_name=TblUserAccounts.uid, db_column='useraccount_id_pwd') salt = models.CharField(max_length=200, blank=True, null=True) hash = models.CharField(max_length=200, blank=True, null=True) record_time = models.DateTimeField() creator = models.ForeignKey(TblUserAccounts, models.DO_NOTHING, related_name=TblUserAccounts.uid, db_column='creator') class Meta: managed = False db_table = 'tbl_user_password' ordering = ['record_time'] Of course you should know that I'm new to Python programming. I guess that the problem is in TblUserDetails model but I don't know what is it? Thanks a lot for your attentions. -
Django REST Framework PATCH request using a query instead of ID or PK
I have a Building model for which I have created a Serializer and ModelViewSet. I can update a model by sending a PATCH request and specifying a model ID as follows: curl http://127.0.0.1/dashboard/api/v1/buildings/3/ \ --request PATCH \ --header "Content-Type: application/json" \ --data '{"name": "School","address": "123 Some Street","description": "A place to learn"}' How do I update a building model by querying a field instead of passing a model ID? For instance: curl http://127.0.0.1/dashboard/api/v1/buildings/?name=hospital \ --request PATCH \ --header "Content-Type: application/json" \ --data '{"name": "School","address": "123 Some Street","description": "A place to learn"}' Note, building names are unique! This functionality would be very useful as the client often does not know the model ID, but rather attributes of the model it wishes to update. views.py class APIBuildingsViewSet(viewsets.ModelViewSet): queryset = Building.objects.all() serializer_class = BuildingSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'address'] models.py class Building(models.Model): building_id = models.AutoField('ID', auto_created=True, primary_key=True) name = models.CharField('Name', max_length=125, null=True, blank=False, unique=False) address = models.CharField('Address', max_length=256, null=False, blank=False) user_id = models.ForeignKey('accounts.User', on_delete=models.CASCADE, default=1) def __str__(self): return self.name serializers.py class BuildingSerializer(serializers.ModelSerializer): class Meta: model = Building fields = ('building_id', 'name', 'address', 'user_id') urls.py router = DefaultRouter() router.register(r'buildings', views.APIBuildingsViewSet, base_name='buildings') urlpatterns = [ url(r'^api/', include(router.urls)), ] -
Django Session Authentication With CSRF Middleware logins successfully but returns 403 on next requests
I am using Django session auth with csrf middleware. And using angular for frontend. Front end makes a login request and my backend login logs in the user & csrf token is set in cookie, and passed in the further requests. I am able to login and can see the cookie being passed on next requests, but I am getting 403 with Authentication credentials were not provided. Here are my setttings.py && views.py. MIDDLEWARE = [ 'reversion.middleware.RevisionMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) Here is my view.py class LoginView(APIView): serializer_class = CustomUserSerialzer def post(self, request, *args, **kwargs): data = request.data email = data.get('email', None) password = data.get('password', None) try: user = authenticate(request, username=email, password=password) if user is not None: login(request, user) return Response(self.serializer_class(user).data) raise Exception('Account has no access') except Exception as e: return Response({ 'status': 'Unauthorized', 'message': str(e) }, status=status.HTTP_401_UNAUTHORIZED) I cannot think of any reason why it would fail on requests after successful login though csrf token passed. I am sure I am missing something in my settings. Can someone suggest what my mistake is? -
django sitemap DoesNotExist at /sitemap.xml
when i add sitemap to my Django project i got this error .. DoesNotExist at /sitemap.xml Site matching query does not exist. sitemap.py : from django.contrib.sitemaps import Sitemap from .models import Homepage class DynamicSitemap(Sitemap): changefreq = "monthly" priority = 0.5 def items(self): return Homepage.objects.all() url.py : from first_app.sitemaps import DynamicSitemap from django.contrib.sitemaps.views import sitemap sitemaps = {'dynamic': DynamicSitemap()} urlpatterns = [ path('sitemap.xml', sitemap , {'sitemaps': sitemaps}, name='sitemaps'), ] settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tinymce', 'first_app', 'django.contrib.sitemaps', ] any help and thanks -
Searching in Django
I need to create searching in django. I can get input from search bar but I don't know how to filter it out. views.py def get_blog_queryset(query=None): queryset = [] queries = query.split(" ") for q in queries: posts = Product.objects.filter( Q(title__icontains=q) | Q(body__icontains=q) ).distinct() for product in pd: queryset.append(product) return list(set(queryset)) def product_all(request, type): query = "" if type == 'all': product_list = Product.objects.filter(del_flag=False) else: product_list = Product.objects.filter(category=type, del_flag=False) for pd in product_list: if (pd.product_price).is_integer(): pd.product_price = int(pd.product_price) pd = { 'product_list': product_list, 'query' : '', } pd.update(context) if request.GET: query = request.GET['q'] pd['query'] = str(query) return render(request, 'polls/product_all.html', pd) product_all.html <div class='menusearch'> <div class="search-bar mt-sm-2 mr-2"> <form method="get"> <input type="text" class="form-control" name="q" id="id_q" placeholder="Search..."> </form> </div> </div> PS. I'm weak in english, sorry. -
Test multiple objects getting returned in Django (Mock?)
I have a model that I need to return duplicates for - because in production there are issues where people may in fact return multiple objects and I need to ensure that the error displays appropriately. The issue is that the objects are being retrieved with a .get() method - so I'm trying to test what happens by creating 2 objects but am getting an error when trying to set it up: django.db.utils.IntegrityError: UNIQUE constraint failed: MyModel.user_no The model is 'unmanaged' in that it's a pre-populated view that I read off of. class MyModel(models.Model): user_no = models.IntegerField(db_column="user_no", primary_key=True) name = models.CharField(max_length=25) abbreviation = models.CharField(max_length=5) some_date = models.DateTimeField() In my test I have created a user and can login this user, but when they get to the site I want to ensure it kicks off a 500. The issue is that when I try to create 2 of those models in my test - it yells at me because of the UNIQUE constraint. Is there a way I can mock/fake that model creation in my setup to get around that UNIQUE constraint error? I currently use FactoryBoy to create the model: factory.MyModelFactory( #user is userone user_no=user.user_no, name='Test', abbreviation='TST', some_date=test_date ) If … -
What is the correct way of finding the balance in an expense management django app?
I am making an expense management app in Django which has the following models: 'Expenditure' to track expenses. 'Income' to track income. 'User' I want to know which of the following method is better to find the balance: Using aggregate to find total expenditure, total income and then calculate the balance by subtracting them. To show the balance of a user, create a new method in the 'User' model to return balance. By denormalizing the database and adding the "balance" field in the user model and calculate it after every new record is created in expense and income. Will a large number of records overload the database while using aggregate? Which of them is the more efficient and correct practice? -
Django tell website to load file without request
I have the following fundamental question: I have a Django project which provides the backend for a website. I also have a python application that generates images. It has its own UI independent from the website and Django. If this app has generated an image I would like to reload the website. I have already implemented a request that sends a post request to the Django backend. So the backend is informed that there is a picture that should be shown in the frontend. Now my question is whether it is possible to tell the frontend from the backend to load the new image without the frontend having sent a request at all. -
Appending an owner to an item (Django)
I'm very new to Django, so it may be a very simple answer, but I'm essentially making an ebay type website with Django. I can create items, but I'm trying to get the owner to be on the item. Here's the model for the item: class Item(models.Model): item_name = models.CharField(max_length=50) item_description = models.TextField(blank=True, null=True) brand = models.CharField(max_length=50, blank=True, null=True) size = models.IntegerField() original_price = models.IntegerField() image = models.ImageField(upload_to="img") date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(UserProfile, related_name="items", on_delete=models.CASCADE) I've been told I now need to append the owner to the item, but I'm struggling to understand how or where. I assume this is on the views.py file of the app, but fiddling around with it has proved unsuccessful. Here's my view: def create_item(request): if request.method == "POST": form = NewItemForm(request.POST) owner = request.user if form.is_valid(): item = form.save() return redirect(get_items) else: form = NewItemForm() return render(request, 'newitemform.html', {'form' : form}) I figured it would be item.append(owner) underneath item = form.save(), but that didn't seem to work. Any help would be greatly appreciated! -
How to integrate ionic 4 with django rest?
Is there a way to integrate ionic 4 with djnago rest? using react as framework for ionic project. +if yes plz provide tutorial link or info.Thank you!