Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework data display
I have a model that contains a ManyToManyField like for instance: class User(AbstractBaseUser, PermissionsMixin): login = models.CharField(unique=True) employee = models.ForeignKey( Employee, on_delete=models.CASCADE, null=True, blank=True, ) rooms = models.ManyToManyField( Room ) Now, I built a serializer that displays this data, but how can I change how the data looks like? Right now it looks like this: { "employee_id": 25, "rooms": [ { "location": "Berlin", "number": "25" }, { "location": "Berlin", "number": "12" } ] } and I would like it to look like this: { "employee_id": 25, "Berlin": ["25", "12"] } Any idea how could I achieve this? -
difference between django.shortcuts and rest_framework.generics
what is difference between two The following sentence from django.shortcuts import get_object_or_404 and from rest_framework.generics import get_object_or_404 -
Return Base64 code from Django ImageField Model in Django rest framework
I want to return a response of image field as base64 code in rest framework -
Error in python3 django while running sudo dpkg --configure -a command on ubuntu 18.04.4
I tried to run this command $ sudo dpkg --configure -a got this below error Setting up python3-django (1:1.11.11-1ubuntu1) ... File "/usr/lib/python3/dist-packages/django/contrib/admin/widgets.py", line 152 '%s=%s' % (k, v) for k, v in params.items(), ^ SyntaxError: Generator expression must be parenthesized dpkg: error processing package python3-django (--configure): installed python3-django package post-installation script subprocess returned error exit status 1 Errors were encountered while processing: python3-django Then I tried upgrading django but exception occured. What to do? -
Validation error 422 on the login page in fastapi login page
I am working on this code. I am getting validation error 422 on this code and am not able to figure it out the issue **main.py** @app.post("/loginsuccess/", response_class=HTMLResponse) async def login_success(request: Request, username: str = Form(...), password: str = Form(...)): p = await User_Pydantic.from_tortoise_orm(await User.get(username=username, password=password)) json_compatible_item_data = jsonable_encoder(p) if json_compatible_item_data is not None: logger.info("Logged in Successfully") return templates.TemplateResponse("homepage.html", {"request": request, "username":username}) else: status_code:int status_code = 500 logger.error("Invalid Credentials") return templates.TemplateResponse("index.html", {"request":request, "status_code":status_code}) The error i have given the screenshot below enter image description here -
Djano include foreign field to query only if exists
I have 2 tables (Product and CustomerPrice) CustomerPrice is the intermediate table between Customer and Product. It assigns customer specific pricing to certain products. Product table id name price 1 orange 1.5 2 apple 2.2 3 kiwi 3.5 CustomerProduct table id customer_id product_id price 1 233 1 1.2 2 233 2 2.0 I want to query the product with CustomerProduct.price if exists. The expected data in such format (example in json but want queryset): [ { id: 1 name: "orange" price: 1.2 // The price adjusted according to customer price } { id: 2 name: "apple" price: 2.0 // The price adjusted according to customer price } { id: 3 name: "kiwi" price: 3.5 // Price remain original because CustomerProduct not exists. } ] I totally have no idea how to accomplish this in Django. How to do that? -
Unable to load a new server in Django
I am currently working on two Django project at the meantime. However, I am not able to switch my server from one to another. When I am running the server of http://127.0.0.1:8000/, it keeps showing the old website but not able to access the new one. I have searched for a number of solutions and I found this python package "django-livereload-server" https://github.com/tjwalch/django-livereload-server I followed this method strictly but it doesn't work. The following error message was shown when I run python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace System check identified 1 issue (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): f lights. Run 'python manage.py migrate' to apply them. June 16, 2021 - 19:11:02 Django version 3.2.4, using settings 'airline.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Is it the problem of my code or what're the problems -
How to Get All Posts with post_status django rest api?
In my project, How can I get all posts with post_status like- publish, pending, draft, spam. I want to query with post_status. Post Model ` class Post(models.Model): title = models.CharField(max_length=255) slug = models.CharField(max_length=255, unique= True, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) subtitle = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(max_length=5555, null=True, blank=True) image = models.ImageField(blank=True, upload_to=post_image_path) image_caption = models.CharField(max_length=255, blank=True) post_status = models.CharField(max_length=255) comment_status = models.CharField(max_length=255) post_type = models.CharField(max_length=50) comment_count = models.IntegerField(null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) tags = models.ManyToManyField(Tag, blank=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title ` Serializer.py from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' read_only_fields = ['author'] How to implement in view? -
entrypoint.prod.sh file not found (Docker python buster image)
I'm getting this issue with my entrypoint.prod.sh file that it doesn't exist even though I have echoed "ls" command and it shows me that the file is present in the right location with the right permissions but still docker isn't able to find it. I have tried many solutions but none are working. Any suggestion/help would be much appreciated. Let me know if you guys need any extra information from me. so this is my main docker-compose.staging.yml file: - version: '3' services: django: build: context: ./ dockerfile: docker-compose/django/Dockerfile.prod expose: - 8000 volumes: - ./backend:/app - static_volume:/app/django/staticfiles environment: CHOKIDAR_USEPOLLING: "true" depends_on: - postgresql stdin_open: true tty: true env_file: - ./.env.staging postgresql: image: postgres:13.1 environment: - POSTGRES_USER=sparrowteams - POSTGRES_PASSWORD=sparrowteams - POSTGRES_DB=sparrowteams ports: - 5432:5432 volumes: - .:/data nginx-proxy: container_name: nginx-proxy build: nginx restart: always ports: - 443:443 - 80:80 volumes: - static_volume:/app/django/staticfiles - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - django nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy volumes: static_volume: certs: html: vhost: Then I have my Dockerfile.prod: - ########### # BUILDER # ########### # pull official base image FROM python:3.9.1-buster as builder # set work directory WORKDIR /app … -
Django PDF Render, aggregate template tag shows up with code included
In views.py, I have the following function to render a PDF view: def agent_render_pdf(request, *args, **kwargs): pk = kwargs.get('pk') agent = get_object_or_404(Agents, pk=pk) invoices = Invoice.objects.filter(agent=agent) invoice_total = invoices.aggregate(Sum('invoice_amount')) template_path = 'agents/statement.html' context = {'agent': agent, 'invoices':invoices, 'invoice_total': invoice_total,} #Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') #if download: #response['Content-Disposition'] = 'attachment'; filename"report.pdf"' #if display: response['Content-Disposition']='filename="report.pdf"' #find the template and render it template = get_template(template_path) html = template.render(context) #create a PDF pisa_status = pisa.CreatePDF( html, dest=response ) if pisa_status.err: return HttpResponse('We had some errors <pre>' +html +'</pre>') return response I am rendering that to 'statements.html' as follows: <body> {{ agent }} <div class="table"> <table> <th>Invoice Number</th> <th>Invoice Date</th> <th>Due Date</th> <th>Invoice Amount</th> <th>Invoice Age</th> {% for i in invoices %} <tr> <td>{{ i.invoice_number }}</td> <td>{{ i.invoice_date }}</td> <td>{{ i.invoice_due_date|date:"m/d/Y" }}</td> <td>{{ i.invoice_amount }}</td> <td>{{ i.InvoiceAge }}</td> </tr> {% endfor %} <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>total:</td> <td>${{ invoice_total }}</td> <td>&nbsp;</td> </tr> </table> </div> My view is basically rendering as expected, accept that the invoice_total is showing up as ${'invoice_amount__sum': Decimal('2500')} instead of just proving the total of invoices as $2,500. I'm clearly getting the information I want, I just don't understand what I'm doing wrong that's causing … -
ModuleNotFoundError: No module named 'home'
ModuleNotFoundError: No module named 'home' -
Openedx login query/page shows Page not found when using custom theme
Hi Im using Openedx KOA version. My Problem is when Im using the default theme login page is working. but when I use custom theme Login Page display Page not found. Ive already tried just copying the default header of the default theme but even with just that, login page not found. Ive already modified lms.yml to ENABLE_COMPREHENSIVE_THEMING: true, and set the path to my custom theme. Everything else seems to be working except login page -
How to show a Many-to-Many field in my django HTML Template?
I have one many to many field in my model.py class jira(models.Model): Jira_ID = models.CharField(max_length=100, blank=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developer = models.ManyToManyField(developer) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) def developer_assigned(self): return ",".join([str(p) for p in self.Developer.all()]) here's my admin.py @admin.register(jira) # class ImpExp(ImportExportModelAdmin): # pass class JiraAdmin(admin.ModelAdmin): list_display = ('id', 'Jira_ID' ,'Jira_Story', 'Short_Description', 'Story_Points', 'Sprint','DX4C_Object','Sandbox', 'developer_assigned') here's my template for that field {% for rt in JIRA %} <td>{{rt.Developer.all}} </td> {% endfor %} in that case i'm getting data as a queryset. But i want data as list. How to achieve that ? -
Series of error and there Fixes in Django if you are working in VS-CODE
problem:1 You might stuck in the configuring the first app in the which gives the a ERROR OF CANNOT IMPORT THE URLS OF YOUR FILE while running in the server. FIX: syntax error : V-S CODE recommend the urlpatterns in CAPS NOT with (s) inside your app please use the correct syntax to run your first app properly . problem:2 you might stuck along with above problem as : thrown django.core.exceptions.ImproperlyConfigured: The included URLconf 'sparta.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. FIX: This is probably cause along with above problem and a simple fix could you have not not added the app in the setting.py of the root directory INSTALLED_APP GOOD LUCK i WILL KEEP FIXING ISSUES DO GIVE IT UPVOTE -
how to do calculation and show on website using Django
I have a project on Hotel Booking Website. I have to create a website like Trivago using Django. When the customer searches the hotel rooms after giving check-in check-out dates and the number of persons, I need to show the price for each hotel on the website. Suppose Hotel1 has a price of 500/ person per day and Hotel2 has 800/person per day. I need to show on that webpage, these 2 available hotels with their final price on the right. The final price is calculated as Final Price= (number of days stayed)*(number of people). Do I need to use models and/or do calculations in views.py Please do tell me how to do this. P.S.- I don't have advanced knowledge of Django, so please suggest a simple approach and complete detail. Thank You very much.Here is the code of the webpage where I want to show -
How to construct django channels group name based on users location
I'm working on location based twitter-like app. Users are supposed to only see and send posts to other users within 10km radius of their location. Using the code below to filter posts it worked very well. def get_queryset(self): user = self.request.user user_coords = user.location.coords user_location = Point(user_coords[0], user_coords[1]) queryset = Post.objects.filter(location__distance_lt=(user_location, Distance(km=10))) return queryset Now I want to make users see posts in realtime. I am using websocket with Django Channels 3.0.3 for realtime. def connect(self): self.group_name = 'posts' # This is just a placeholder # Join group async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() # Sends message to group def send_post(self, message): async_to_sync(self.channel_layer.group_send)( self.group_name, { 'type': 'post', 'message': message, } ) Now I need a way to dynamically group users based on their location so that only users within 10km of each other can get the broadcast from the websocket. I need something like self.group_name = '10km radius of user' -
how to use ForeignKey in django view function
Pack1 - 10$ Pack2 - 40$ Pack3 - 100$ If I select pack2, in case I upgrade my pack I need to show to the output is👇 Pack1 -10$ - disable Pack2 -40$ - disable Pack3 - 60$ -
Trigger specific python function in API based on GET request
Right now, I have two servers; webpage and compute. The webpage consists of a Django application and compute should do all the heavy lifting such that we don't waste resources on webpage and reduces the performance. I'm thinking about making compute an API, where webpage sends requests to, and retrieves from. An example would be: #webpage import requests data = requests.get("https://my_api.com/my_func") # do something with data #compute def my_func(): data = pd.read_sql("SELECT * FROM database") return data def get_func_to_call(request): if request.data=="my_func" return my_func else: return 404 I'm fairly new to APIs, thus I'm searching for suggestions, tutorials, books on how to create an API that would accomplish it. -
How to map ForeignKey Relationship Django for 3 Models
I am planning write one query to get data using 3 models. Modle 1: Emp class Emp(models.Model): empID = models.AutoField(primary_key=True) empName = models.CharField(max_length=70, blank=False, default='') empCode = models.CharField(max_length=10, blank=False, default='') empDesc = models.CharField(max_length=200) class Meta: db_table = 'empolyee' def __str__(self): return self.empName Model 2: Dep class Dep(models.Model): depID = models.ForeignKey(primary_key=True) depName = models.CharField(max_length=200) Emp = models.ForeignKey(EMP, on_delete=models.CASCADE, null=True) class Meta: db_table = 'departmen Model 3: account class Account(models.Model): accountID = models.AutoField(primary_key=True) accountName = models.CharField(max_length=200) Emp = models.ForeignKey(Emp, on_delete=models.CASCADE, null=True) field = models.ForeignKey(Dep, on_delete=models.CASCADE, null=True) class Meta: db_table = 'accounts' I Need execute below native query (SQL): select em.empName as fromMaster, em1.empName as toMaster from dep dp join emp em on dp.depID = em.empID join account ac on dp.depID = ac.field join emp em1 on ac.empID = em1.empID where dep.empID ='1' But I tried with below example but I am getting differnet query. dataReceived = account.objects.select_related( 'field __Emp ', 'Emp ').filter(Emp='1') Could you please help me any one, how to achive this. Thanks in advance !!!! -
Django: ERROR: Command errored out with exit status 1:
I tried to download chatterbox and it started showing error while installing. Then I tried to download django-visits then it showed the same following error: (django_gs) C:\gsData\Workspace\venv\django_gs\src>pip install django-visits Collecting django-visits Using cached django-visits-0.1.6.tar.gz (7.3 kB) Collecting distribute Using cached distribute-0.7.3.zip (145 kB) ERROR: Command errored out with exit status 1: command: 'C:\gsData\Workspace\venv\django_gs\Scripts\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\pc\\AppData\\Local\\Temp\\pip-install-wjigmtsi\\distribute_5b4d0ce4a799441984df2e08779f375e\\setup.py'"'"'; __file__='"'"'C:\\Users\\pc\\AppData\\Local\\Temp\\pip-install-wjigmtsi\\distribute_5b4d0ce4a799441984df2e08779f375e\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\pc\AppData\Local\Temp\pip-pip-egg-info-vg0ihtkz' cwd: C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\ Complete output (20 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "C:\gsData\Workspace\venv\django_gs\lib\site-packages\_virtualenv.py", line 89, in exec_module old(module) File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\dist.py", line 7, in <module> from setuptools.command.install import install File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\command\__init__.py", line 8, in <module> from setuptools.command import install_scripts File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\command\install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\pkg_resources.py", line 1518, in <module> register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ---------------------------------------- WARNING: Discarding … -
Django ValueError (The view views.save_flow_data didn't return an HttpResponse object. It returned None instead.)
When I try to submit my form I get this message: The view views.save_flow_data didn't return an HttpResponse object. It returned None instead. I have to say I'm really starting to regret using Django for this project. I've slimmed down everything so it's easier for you to read. Views.py def save_flow_data(request): if request.method == 'POST': if request.POST.get('upload_flow') \ and request.POST.get('water_flow_rate')\ and request.POST.get('water_flow_rate_unit')\ data=CalcData() data.water_flow_rate = request.POST.get('water_flow_rate') data.water_flow_rate_unit = request.POST.get('water_flow_rate_unit') data.save() return render(request, 'io/flow.html') else: return render(request,'io/flow.html') models.py class CalcData(models.Model): upload_flow = models.BooleanField(default=False) water_flow_rate = models.DecimalField(max_digits=100, decimal_places=5) water_flow_rate_unit = models.TextChoices('wfr_unit', 'm3/day m3/month') datetime = models.DateTimeField(default=timezone.now) submit button in form <div> <button action="{% url 'MyProject:save_flow_data' %}" type="submit" class="btn btn-light" style="width: 517.5px;" >Calculate</button> </div> urls.py urlpatterns = [ path('', views.home, name='MyProject-home'), path('io/flow/', views.io_flow, name='MyProject-io-flow'), path('io/flow/save_flow_data', views.save_flow_data, name='save_flow_data') ] I'm really not sure where to go from here. I had a perfectly working form but as soon as I scaled it up it flopped. -
Getting User Model from Django rest framework Token Authentication token endpoint URL
I want to get all User Model object of user from Token. Token should be on URL which shows all user details like username, first_name, last_name, email. -
How to keep Django CKeditor format on Ionic template
I would like to keep the format set on Django CKeditor plugin. On Django works well because in database i can see the content for this attribute: database column: <p style="text-align:right">Esta es un descripci&oacute;n lo suficientemente larga para poder ver la alineaci&oacute;n del texto en el plugin de ckeditor.</p> And after API request keeps works well: ionic ts file: console.log(this.place.information); <p style="text-align:right">Esta es un descripci&oacute;n lo suficientemente larga para poder ver la alineaci&oacute;n del texto en el plugin de ckeditor.</p> But in the Ionic template not keeps the alignment <div [innerHTML]="place.information"></div> Anybody could help me please ? Thanks in advance -
Sequence of arguments in django signals
Below is the receiver function that I wrote. @receiver(post_save,sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Is there a specific sequence for the arguments in this function? Can I change the positioning of these arguments? Eg - def create_profile(sender, created, instance, **kwargs) -
Django - How do I save a file from a server locally, and use it on frontend (In production)
I'm building functionality in Django that requires that I download file-data (bytes of png, pdf etc.) from the web. From here I need to save it into a folder, and use it in the frontend by linking to it, like I would with a png-logo from the static folder. This needs to be done while the project in running in production, so a user can click on a button, which then runs a views function that downloads the file into the right folder, and returns a template containing the file (So for example returning : <img src='the downloaded file'>) I've gotten this to work running the code locally by writing a file into my projects static folder, however this doesn't work in production because, to my understanding, a django project in production doesn't use each projects static files. Instead it runs the collectstatic command which collects all static files into one folder. I've therefore written the following code which should save my downloaded files into this static folder: #From function download_file(request) in views.py #file_name, downloaded_bytes are both defined previously. #Define path for saving files into path = f'{settings.BASE_DIR}/static/files/folder1/folder2/' + file_name #Make folders for saving files into try: os.mkdir(f'{settings.BASE_DIR}/static/files/folder1') except OSError …