Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get limited results per page in django using pagination?
I am following a udemy course where I am making a real estate website using Django. I have come so far and have been fighting with the errors but I am stuck with the pagination error that I am facing right now. I see everything is working fine in the video but when I follow it exactly it does not work. The issue is that when I set a limit on items per page, it does not seem to be working as I see all the results on the same page. Here is my views.py from django.shortcuts import render from django.core.paginator import Paginator from .models import Listing def index(request): listings = Listing.objects.all().order_by('-id') paginator = Paginator(listings, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'listings': listings } return render(request, 'listings/listings.html', context) It's my Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='listings'), path('<int:listings_id>', views.listing, name='listing'), path('search', views.search, name='search') As you can see, I have set maximum 3 listings per page but I am getting all of them on a single page which is not what I want. It would be great if anyone could help. Thanks for your time and efforts. -
How can I redefine my .wav file as HTML file?
I am uploading my .wav audio media from my Django admin page and accidentally specified Pycharm to read my .wav as TEXT files. I want to redefine it as HTML; how can I do it in Pycharm? -
django NoReverseMatch at / TypeError - missing required positional arguments
path('administration/delete-post/', administration_views.delete_upload, name='delete_upload'), path('administration/delete-post/<slug:post_slug>', administration_views.delete_upload, name='delete_upload'), For some reason, when I added delete class, I had to add two url patterns. When I comment out the first path, It gives me an error of Reverse for 'NoReverseMatch at /administration/ delete_upload' with no arguments not found. 1 pattern(s) tried: ['administration/delete\\-post/(?P<post_slug>[-a-zA-Z0-9_]+)$'] I even stated the slugs on html. {% for post in posts %} <a href="{% url 'delete_upload' %}{{ post.slug }}">Delete Upload</a> {% endif %} With two same url patterns, it worked fine somehow, but now I want to add a confirmation page, and it's causing an error again. views.py def delete_upload(request, post_slug): post = get_object_or_404(VideoPost, slug=post_slug) if request.method == "POST": post.delete() context = { "post": post } return render(request, "administration/confirm_delete.html", context) confirm_delete.html {% block content %} <form action="." method="POST">{% csrf_token %} <h1>Are you sure you want to delete</h1> <p>{{post.title}}</p> <a href="../">Cancel</a><input type="submit" value="Confirm"> </form> {% endblock %} error TypeError at /administration/delete-post/ delete_upload() missing 1 required positional argument: 'post_slug' It directs me to confirm_delete page correctly with the slugs on url, but when I click confirm, the slug is gone on the url and it's causing the error it seems. I see the problem, but I can't fix it... please help. Thank … -
Python Django - HTML for REST API JSON data in Async
I am making a Django web app. So far I have used templates for creating HTML in response to a POST request. I use 'context' to pass data to the template and fill the HTML with that data. This does not require any client-side work. Now I added a REST API to the app to be used Async, and I want all data to be processed by the API and return only in JSON format. This creates a problem, I cant use the templates anymore since I can't use 'context' to fill in the data in the HTML, I have to use client-side JS to do the filling but now I am missing the HTML appropriate to the data received. The web app consists - 1 REST API JSON format 2 Public website 3 Android and iOS app What are the ways in Django for generating HTML for an API JSON response in Async architecture? Are there any alternatives for the templates, solutions, frameworks, JS libraries to get this done in less coding? I do not want to return HTML via API to keep things client mobile app/browser independent. I am hesitant of creating a new frontend like React. I … -
What is the efficient way to resize/process image and upload to s3 in django?
I am fairly new to django. I was wondering what would be the best approach to process an image file and upload to s3. I could think of a couple of approaches but not sure which one to pick. They are as follows: 1) Upload raw unprocessed image directly to s3 from client(mobile app), resize/process it (using Celery) and then replace the original file with the processed one. 2) Send raw image to django, process it and then upload to s3. Thank you. -
Error connecting django to a remote mysql database on aws
I have a django project set up and I’m trying to connect the app to a database being hosted on aws. I’m getting an issue when I run python manage.py check, I get this error: django.db.utils.OperationalError: (1049, "Unknown database 'database-1") I’m able to connect database through mysql command: mysql -u admin -p -h http://database-1.endpoint.us-east-2.rds.amazonaws.com I have my settings.py file configured like: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'database-1.endpoint.us-east-2.rds.amazonaws.com', 'NAME': 'database-1', 'USER': 'user', 'PASSWORD': 'pass', 'PORT': '3306', } } -
Django custom user registration form when creating new superuser from terminal raises error TypeError: create_superuser() got an unexpected
Making custom user registration and when creating superuser account from terminal getting this kind of error message TypeError: create_superuser() got an unexpected keyword argument 'first_name' models.py: class AccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, nickname, country, password=None): if not email: raise ValueError("Users must have an email address") ... user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user Any solutions? -
Django alter admin save to alter another table field
I am creating a django site that includes a rudimentary inventory system. Which includes the following models class Stock(models.Model): # Fields location = models.ForeignKey(Location) product = models.ForeignKey(Product) quantity = models.IntegerField() class Transfer(models.Model): # Fields location1 = models.ForeignKey(Location, related_name='location1') location2 = models.ForeignKey(Location, related_name='location2') date_transferred = models.DateField(default=timezone.now) class TransferLine(models.Model): # Choice set direction_set = ( ('1TO2', 'From 1 to 2'), ('2TO1', 'From 2 to 1') ) # Fields transfer = models.ForeignKey(Transfer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField() transfer_direction = models.CharField(max_length=4, choices=direction_set, default='1TO2') When I create a new transfer I want to be able to automatically deduct and add the product in the TransferLine from the quantities in the Stock model. I have figured out how to override the save_model method in the admin.py file for the TransferAdmin class, but I cannot figure out how to access the Stock model from within the SaleAdmin class. Is this something that can be done in the admin? Will I have to create my own form? I really wanted to do this from admin because inlinetabular is really easy to do within admin compared to within a custom built form. (At least from what I can find.) Any help on this would be … -
AttributeError at /edit-menu/edit/ 'Product' object has no attribute 'is_valid'
I am trying to pull all of the product names from the Product model, display them and their prices on the screen, and then be able to change the product price of any of these items. I have it so it lists them out and has an input field for the price, but get this error when I submit. AttributeError at /edit-menu/edit/ 'Product' object has no attribute 'is_valid' Please help. views.py: def edit_menu(request): queryset = Product.objects.all() context = { "object_list": queryset } if request.method == 'POST': post=Product() if request.POST.get('price'): if post.is_valid(): post.price= request.POST.get('price') post.save() return redirect('mis446/edit-menu.html', context) else: return redirect(request, 'mis446/edit-menu-item.html', context) else: return render(request, 'mis446/edit-menu-item.html', context) else: return render(request, 'mis446/edit-menu-item.html', context) Models.py: class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() slug = models.SlugField() def __str__(self): return self.name html: <div class = "container"> <form method = "post"> {% csrf_token %} {% for instance in object_list %} {{ instance.name}}: <input type="number" name="price" value = '{{ instance.price }}'/><br> {% endfor %} <button type ="submit">Submit Changes</button> </form> </div> -
Hide edit/add/remove buttons in Django admin table when field in list_display
I want to hide the edit, add, and remove icons from the Django admin tool for a foreign key field. Is it possible to achieve this? If so, how? This is my code so far: @admin.register(Request) class RequestAdmin(admin.ModelAdmin): list_display = ( "name", "contact_method", "neighborhood", "adults", "children", "prescriptions", "volunteer", "status", "due_date", ) list_editable = ("status", "volunteer") def neighborhood(self, obj): if obj.address and obj.address.get("neighborhood", False): neighborhood = obj.address["neighborhood"] if obj.address.get("details", False): return f"{neighborhood} - {obj.address['details']}" return neighborhood It seems the problem is that I have also registered another model Volunteer. @admin.register(Volunteer) class VolunteerAdmin(admin.ModelAdmin): list_display = ("name", "contact_method", "neighborhood", "valid_ID") def neighborhood(self, obj): if obj.address and obj.address.get("neighborhood", False): return obj.address["neighborhood"] However, I need to keep this model too. So, how can I achieve this? -
Django select related with max field value for each result
I have two models. models.py: class Drink(models.Model): account = models.ForeignKey(Account, null=False, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=False, blank=False) # some other fields that don't matter now... class DrinkStock(models.Model): ingredient = models.ForeignKey(Ingredient, null=False, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=14, decimal_places=3, null=False, default=0.000) date = models.DateTimeField(auto_now_add=True) Let me explain why I have two models before someone post a different solution. The idea is to have a stock history. And when I show all the drinks, I need to display them only with their last related stock (the one with the latest date). views.py def drinks(request): drinks = Drink.objects.select_related('stock').filter(account__id=request.session['account_id']) But how can I append the related stock of each drink with the lastest date? -
How to setup permissions to graphql relay queries in Django Graphql that uses JWT authentication
This is a recent problem I encountered in Django I setup a django backend server that serves a graphql api and I used Django Graphql JWT that offers auth functionnality the documentation is here the package offers decorators that can be setup with resolvers and it works perfectly with that, the issue occurs when I try to setup a relay query and would like to authorize that to logged users. Since the syntax to use relay in django excludes the use of a resolver method and therefore really don't know how to setup the authorization. Thanks in advance. -
Error messages when i want to pip install mysql-python and mysqlclient with MacOS
I'm currently working on a project using Django with python2.7 but each time I try pip install mysqsl I get this error messages "" ERROR: Command errored out with exit status 1: command: 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/setup.py'"'"'; __file__='"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/pip-egg-info cwd: /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/ Complete output (10 lines): sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-FpxjOl/mysql-python/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 43, in get_config libs = mysql_config("libs_r") File "setup_posix.py", line 25, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output."" Any help please -
Intergrating Firebase with Django Rest Framework
So I have a Django back-end with a Firebase database and a React front-end. I want to POST data from the React to the Django which will Post to Firebase (I know i can do it all in JS to Firebase but i figure it might help more to have a python back-end for the future). I see tutorials using Django Rest Framework and I have been able to get that work but it uses SQLite3 and not Firebase. How can i implement Firebase into Django Rest Framework? -
An alternative to Chrome Dev Mobile Emulator?
I've known for a while now that the chrome mobile emulator can't get 100% accuracy, but it's driving me particularly nuts for a Django website I've been putting together. I know Safari has the option of using a Web Inspector on your phone by connecting to your laptop, but from what I've seen, that's only for Macs (unless I'm wrong, correct me if I am), and I do not have a Mac. Is there any alternative that allows me to get at least a closer percent of accuracy for mobile screens? Here are a few screenshots to show the problem. iPhone vs Chrome Dev Tools -
'url' tag for while using tornado (python), just like in Django Template Language
Like in Django, we can use DTL {% url 'url_name' %} instead of hard coding URL names. Is anything of that sort is available while using Tornado (python)? -
django- How do I get the drop down list of boards for the add task form to only show boards the user has created?
How do I get the drop down list of boards for the add task form to only show boards the user has created? The form shows all the boards that are in the database. How can i limit the dropdown list to just be the boards the user has created. models.py class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(unique=True) admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board") name = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) class Task(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) admin = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField(default=False) assigned_to = models.CharField(max_length=30) forms class CreateNewBoard(ModelForm): - some code- class CreateNewTask(ModelForm): text = forms.CharField(max_length=300, help_text="Please enter a task") assigned_to = forms.CharField(max_length=30, help_text="Assigned to") complete = forms.BooleanField(help_text="complete?") class Meta: model = Task fields = ('board', 'text', 'complete', 'assigned_to') views.py def create_task(request,username): form = CreateNewTask() if request.method == "POST": if username == request.user.get_username(): form = CreateNewTask(request.POST) if form.is_valid(): temp = form.save(commit=False) temp.admin = request.user temp.save() return redirect("/dashboard") return render(request, 'boards/task.html', {'form': form}) Task.html {% block title %}Task - {% site_name %}{% endblock %} {% block content %} <div class="mt-3"> <h1>Add a Task</h1> <form method="post" action="/{{ user.get_username }}/task/create/" id="create"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ … -
Threads can only be started once in Django channels
I created a simple Django Channels consumer that should connects to an external source, retrieve data and send it to the client. So, the user opens the page > the consumer connects to the external service and gets the data > the data is sent to the websocket. Here is my code: import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer, AsyncJsonWebsocketConsumer from binance.client import Client import json from binance.websockets import BinanceSocketManager import time import asyncio client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') bm = BinanceSocketManager(client) class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') bm.start_trade_socket('BNBBTC', self.process_message) bm.start() def process_message(self, message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] asyncio.create_task(self.send_json(Rate)) print(Rate) This code works when i open one page; if i try to open a new window with a new account, though, it will throw the following error: File "C:\Users\User\Desktop\Heroku\github\master\Binance\consumers.py", line 54, in connect bm.start() File "C:\Users\Davide\lib\threading.py", line 843, in start raise RuntimeError("threads can only be started once") threads can only be started once I'm new to Channels, so this is a noob question, but how can i fix this problem? What i wanted to do was: user opens the … -
How to add background image through css in django?
How to get the path to work so it shows the background image through css? If it could be done with a relative path then how? /*mobile view*/ .index-banner { background: url('static/mysite/images/home.svg') no-repeat; background-position: center; background-size: cover; width: 100%; height: 380px; } {% block content %} <section class="index-banner"> <h2>Test<br>Condiitons</h2> <h1>lorel ipsum</h1> <h1>sdfjls upueh ndsfoi bbownl</h1> <img src="{% static 'mysite/images/home.svg' %}" class="mysite-img" style="display: none;"> </section> {% endblock %} -
Django CMS Carousel
I am learning/developing my company website. and I really don't know how to add the correct plug-ins on this Carousel that I have and also integrate with all the translations. But static code bellow works fine, but I would like to convert that to the django-cms plugin format <header> <div class="container-fluid"> <div class="slider-container"> <div class="owl-slider owl-carousel"> <div class="item"> <div class="owl-slider-item"> <img src="{% static 'home/images/slide-1.png' %}" class="img-responsive" alt="portfolio"> <div class="intro-text"> <div class="intro-lead-in">Text1 Lead</div> <div class="intro-heading">Text1 Heading</div> </div> </div> </div> <div class="item"> <div class="owl-slider-item"> <img src="{% static 'home/images/slide-2.png' %}" class="img-responsive" alt="portfolio"> <div class="intro-text"> <div class="intro-lead-in">Text2 Lead</div> <div class="intro-heading">Text2 Heading</div> </div> </div> </div> <div class="item"> <div class="owl-slider-item"> <img src="{% static 'home/images/slide-3.png' %}" class="img-responsive" alt="portfolio"> <div class="intro-text"> <div class="intro-lead-in">Text3 Lead</div> <div class="intro-heading">Text3 Heading</div> </div> </div> </div> </div> </div> </div> </header> -
user=User.objects.get_or_create(first_name=fk_first_name,last_name=fk_last_name,email=fk_email)[0] why [0] is used
in this python code which is creating fake name with email : from faker import Faker from .models import User fk=Faker() def populate(N=5): for entry in range(N): fk_name=fk.name().split() fk_first_name=fk_name[0] fk_last_name=fk_last[1] fk_email=fk.email() user=User.objects.get_or_create(first_name=fk_first_name,last_name=fk_last_name,email=fk_email)[0] if __name__=='__main__': inp=int(input("please enter the integer value for population")) print('Populating ......................') populate(inp) print("population is done \n") in this user=User.objects.get_or_create(first_name=fk_first_name,last_name=fk_last_name,email=fk_email)[0] why [0] is used -
Pillow is not installing in Django when I creating a new Project
[ error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe' failed with exit status 2 ] When I created my first project Pip install pillow installed successfully but when I created a new project then pip install pillow was showing this error. I don't know what is happening with this. -
share dynamic object (not stored in DB) between views Django
my views.py from django.shortcuts import render from django.http import JsonResponse from home_page.models import UploadNet from home_page.forms import NetForm, ConfigForm from backend.NetListBuilder import NetListBuilder from backend.ConfigBuilder import ConfigBuilder def set_configuration(request, net_file=None): if "upload_net" in request.POST: net_path = os.path.join("media/net_files", net_file.name) netlist = NetListBuilder(net_path) config = ConfigBuilder(netlist) context = {'config': config,} return render(request,'configuration.html', context=context,) return render(request,'configuration.html', {'net_file': None},) def save_config(request): if request.is_ajax(): response_data = {} json_data = {} json_data = request.POST['json_data']: response_data["result"] = "save file" return JsonResponse(response_data) context = {'net_file': None} return render(request, 'rules_list.html', context=context) I want to share netlist and config objects (without saving them in DB) in rules_list view. how can i do that? should i pass them into configuration.html file? -
Mutiple bokeh Charts in django template
I don't understand how I can set up several Bokeh Chart in my django template. I have read this page https://docs.bokeh.org/en/latest/docs/user_guide/embed.html which supposed to explain this but it is not clear at all. Here is my view : def Bokehplot(request): source = ColumnDataSource(S.df) p = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc") p.line("date", "Te", source = source, line_width = 2,color = "green", alpha = 0.6) q = figure(x_axis_type = "datetime", title = "un truc", x_axis_label = "date" , y_axis_label = "autre truc") q.line("date", "Tr", source = source, line_width = 2,color = "red", alpha = 0.6) plots = {'Red': p, 'Blue': q} script, div = components(plots) return render(request, 'batterie/results.html', locals()) {{div|safe}} gives the 2 divs on a row. I would like to access div1 (first graph) and div2 (second graph) in order to put them in 2 different bootstrap columns ? Any help is welcome. Thanks! -
Django queryset join tables
I am really stuck with merging two tables. I have tables Item and Transactions class Item(models.Model): category_choices = [] item_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=100, choices=category_choices) image = models.ImageField(upload_to='media') stock = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) date_added = models.DateTimeField(default=timezone.now()) class Transactions(models.Model): transaction_id = models.AutoField(primary_key=True) order_id = models.UUIDField() item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='transactions') quantity = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) address_str = models.CharField(max_length=100) address_plz = models.CharField(max_length=100) address_place = models.CharField(max_length=100) address_country = models.CharField(max_length=100, choices=[(name[1], name[1]) for name in countries]) Now I want to render template with transactions and images and items info from Item model. I am trying to use prefetch_related, howeve rit does not work and I do not understand how this should be solved. def order_history(request): if request.user.is_authenticated: transaction = Transactions.objects.order_by('-transaction_date').\ filter(username=request.user).prefetch_related('item') context = {'orders': transaction} template_name = 'retail/order_history.html' return render(request, template_name, context=context) else: raise Http404('You are not authorised')