Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I share the embedded video link that I got from the Vimeo site on my Heroku app, it gives an error
When I add the embedded video link, I am facing this error. I in the video I shared on Vimeo, I chose the option "Let only the allowed sites be able to embed". Then I added my own heroku site here. For ex: my-site.herokuapp.com herokuapp.com heroku.com Normally the video should start playing on my site. But it didn't work. Can you help? How can I solve it? Privacy : Hide from Vimeo Embed : Specific domains -
cannot link postgresdb with django because of UTC
When i try to connect postgresql, python terminal returns "database connection isn't set to UTC". How can i solve it? Former answers on this site does not work. -
Saving image captured from webcam
I'm building a Django project in which I need to take a picture from webcam, and then store it in my database and as a file. I'm saving the source in the database, but I'm having some trouble saving it as a file. Here is my code: html: <form method="POST" action="{% url 'takePhoto' %}" enctype="multipart/form-data"> {% csrf_token %} <video id="video" autoplay ></video> <canvas id="canvas"></canvas> <input type="hidden" name="photo" id="photo" value=""/> <button id="startbutton1" class="btn btn-outline-secondary btn-sm">Take Photo</button> <button id="submit" type="submit">submit</button> <script src="{% static 'scripts/script.js' %}"></script> javascript: (function() { var width = 320; var height = 0; var streaming = false; var video = null; var canvas = null; var photo = null; var startbutton1 = null; function startup() { video = document.getElementById('video'); canvas = document.getElementById('canvas'); photo = document.getElementById('photo'); startbutton1 = document.getElementById('startbutton1'); navigator.mediaDevices.getUserMedia({video: true, audio: false}) .then(function(stream) { video.srcObject = stream; video.play(); }) .catch(function(err) { console.log("An error occurred: " + err); }); video.addEventListener('canplay', function(ev){ if (!streaming) { height = video.videoHeight / (video.videoWidth/width); if (isNaN(height)) { height = width / (4/3); } video.setAttribute('width', width); video.setAttribute('height', height); canvas.setAttribute('width', width); canvas.setAttribute('height', height); streaming = true; } }, false); startbutton1.addEventListener('click', function(ev){ takepicture(); ev.preventDefault(); }, false); clearphoto(); } function clearphoto() { var context = canvas.getContext('2d'); context.fillStyle = "#AAA"; … -
Django Join two models
I'm beginner to Django. I want to ask how can I get the addresses of all the Dials that are in DataUpload table from BO table. It doesn't return any data in Customer_Address column in HTML. class DataUpload(models.Model): Dial = models.IntegerField() Customer_Address = models.ForeignKey(BO, on_delete=models.CASCADE, null=True,blank=True, related_name='address') National_ID = models.IntegerField() Customer_ID = models.IntegerField() Status = models.CharField(max_length=100) Registration_Date = models.DateTimeField(max_length=100) Is_Documented = models.CharField(max_length=100, null=True) BO Model: class BO(models.Model): id = models.AutoField(primary_key=True) Dial = models.IntegerField() Customer_Address = models.CharField(max_length=100, null=True, blank=True) Wallet_Limit_profile = models.CharField(max_length=100, null=True, blank=True) View: def listing(request): data = DataUpload.objects.all() paginator = Paginator(data, 10) # Show 25 contacts per page. page_number = request.GET.get('page') paged_listing = paginator.get_page(page_number) # print(data) return render(request, 'pages/listing.html', {'paged_listing': paged_listing, 'range': range}) When I call item.Customer_Address it does return any data and no errors are appearing, also I tried item.Customer_Address_id.Customer_Address same thing. HTML: {% for item in paged_listing %} <tr> <td class="text-center align-middle">{{ item.Dial }}</td> <td class="text-center align-middle">{{ item.Customer_Address}}</td> <td class="text-center align-middle">{{ item.National_ID }}</td> <td class="text-center align-middle">{{ item.Status }}</td>--> <!-- <td><a href="{% url 'edit_record' item.Dial %}">Edit</a> </td> --> <td class="text-center align-middle"> <button class="btn btn-primary"><a class="edit-link" href="{% url 'edit_record' item.id %}">Edit</button> </a> </td> </tr> {% endfor %} -
pip install sslcommerz-python raising lots of errors:
I am trying to install sslcommerz-python using pip for my django app in order to create a payment gateway but its showing a lot of errors like × Encountered error while trying to install package.╰─> typed-ast, gcc exit code 1, legacy-install-failure. please how can i solve this problem -
issues with ManyToManyField in django
I have an app with a few simple aspects. You can sign in/sign up as a User, with an Account custom user extension. users/models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(blank=True, null=True) def __str__(self): return self.user Once you're signed in you can create a Group. groups/models.py: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.TextField() topic = models.CharField(max_length=55) joined = models.ManyToManyField(User, related_name='joined_group') def __str__(self): return self.topic Users can join Groups. The issue I'm having is I want to store in the User model (so that Users can see in their account info) the groups they have joined. I'm assuming it's a ManyToManyField because a User should be able to join many Groups and a Group should be able to have many joined Users. I'm just having trouble getting the modeling of it right. Right now I tweaked my CustomeUser model a bit. users/models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(blank=True, null=True) # added line groups_joined = models.ManyToManyField(Group, blank=True) def __str__(self): return self.user I got errors with this so I tried a different approach. users/models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(blank=True, null=True) # added line groups_joined = models.ManyToManyField(Group, blank=True) def __str__(self): return self.user … -
Django ManytoMany prints more than once when if i add more than 2 model
I'm trying to create a e-commerce site for a school project with Django I Created This Product Class for product and variations class Product(models.Model): category = models.ManyToManyField(Category,verbose_name='Kategori') gender = models.ManyToManyField(Gender,verbose_name='Cinsiyet') parent = models.ManyToManyField('self',verbose_name='Ana Varyant',blank=True,null=True,symmetrical=False,related_name='+') name = models.CharField(max_length=200,null=True,verbose_name='Başlık') sub_name = models.CharField(max_length=200,null=True,verbose_name='Alt Başlık') slug = AutoSlugField(populate_from='name') price = models.FloatField(null=True,verbose_name='Fiyat') My Problem is when i use this in my template if product has more than two variants it shows variant more then once. like this : As you can see, there is there is two gray variant in here. so how can i fix this? -
Sending image file via Fetch method
So I'm trying to use MathPix API to get pure Latex from processed image in my Django project. I use few <input type="file"> fields and event listener on each one. After change event the file is validated (if it is a .jpg, .png etc). Next I use URL.createObjectURL() function to create a url for uploaded file without saving it before to db. function checkExtension(event) { var input = event.srcElement; var fileName = input.files[0].name; var extension = fileName.substr(fileName.lastIndexOf(".")); var allowedExtensionsRegx = /(\.jpg|\.jpeg|\.png|\.gif)$/i; var file = document.getElementById(event.target.name) if (allowedExtensionsRegx.test(extension) == true) { file.setAttribute("class", "btn-success p-2 rounded") const image = input.files[0]; const image_url = URL.createObjectURL(image) snip_request(image_url) } else { file.setAttribute("class", "btn-danger p-2 rounded") } } function snip_request(image_url){ if(image_url) { const appId = "XXXXXXXXXXXXXXXXX"; const appKey = "YYYYYYYYYYYYYYYY"; var url = "https://api.mathpix.com/v3/latex"; var _data = { "src": image_url, "formats": "text", "data_options": { "include_asciimath": true, "include_latex": true } } var _header = { "content-type": "application/json", "app_id": appId, "app_key": appKey } const response = fetch(url, { method: "POST", body: JSON.stringify(_data), headers: _header }) .then(response => response.json()) .then(json => console.log(json));; } } Unfortunately at the end of the day I get error message: "error_info": { "id": "image_download_error", "message": "FetchError: request to http://localhost:8000/14340c1a-bb6e-43aa-b82b-80eca8824f71.png failed, reason: connect ECONNREFUSED 127.0.0.1:8000", … -
How to create a splash screen for Django web application?
I've created my first workable Django web application, but am puzzled by the lack of documentation or examples regarding the creation of splash or start-up screens. Am I overthinking this? Is creating a splash screen for my Django web app as simple as creating an initial screen using HTML/CSS/Javascript, or might someone point me in the direction of examples or documentation on how to approach this. Thanks. -
django-jsonforms how to remove the Json: label for the jsonschemaform field?
I'm using django-jsonforms. I'm trying to remove the "Json:" in the picture. b = { "title": "Product", "description": "A product", "type": "object", "properties": { "Products": { "type": "array", "products": { "type": "string" }, "minItems": 0, "maxItems": 5, } } } I already tried the self.fields["form"].label = "myform" and change widget, and put "label", "ui:label" etc. in the schema. I can't find anything in the docs.? -
2D variable name in Django sessions
I am trying to create a 2D variable name in sessions as in the Django docs example at this page: It says: # Gotcha: Session is NOT modified, because this alters # request.session['foo'] instead of request.session. request.session['foo']['bar'] = 'baz' but when i use that code, i get: KeyError: 'foo' if i create 'foo' first with request.session.get('foo', 'baz'), then request.session['foo']['bar'] = 'bam' i still get: KeyError: 'foo' why am i not able to set a 2d variable as in the django doc example? Thank you for any help. -
Django project does not display images in heroku
When I upload the project to heroku, and change DEBUG=True to DEBUG=False, the images stop showing That's my static and media root STATIC_ROOT = Path(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = Path(BASE_DIR, 'media') MEDIA_URL = '/media/' -
How to query trino db from django
How to connect from django to trinodb. what engine should be used? Is it even supported by django? Incase it is not supported, how do I create and maintain the connection object on my own? -
Django link to a specific users profile page
I have a social media website that will allow a user to view another users profile page by clicking their username from one of their posts that appears in the feed section of my page. I have view_profile view created but need to pass in the desired users username into the view, to only show posts, activity, etc... made by that specific user. How do i pass the username into my view? view_profile.html <section id="main_feed_section" class="feed_sections"> {% for post in posts %} <div class="post_main_container"> <section class="post_title"> <h1> <a href="{% url 'view_profile' %}">{{ post.user_id.username }}</a>{{ post.title }}</h1> </section> <section class="post_main_body"> <p>{{ post.caption }}</p> </section> <section class="post_footer"> <p>{{ post.date_posted }}</p> </section> </div> {% endfor %} </section> views.py def view_profile(request): account = "logan9997" #if a post made by logan9997 was clicked posts = [post for post in Posts.objects.all() if post.user_id.username == account] followers = [follower for follower in Relationships.objects.all() if follower.acc_followed_id.username == account] context = { "title":account, "posts":posts, "followers":followers } return render(request, "myApp/view_profile.html", context) -
How to handle object specific permissions in django-river?
I have a use case for django-river where users can approve some objects (database records) in a model but not all of them. I need to check if a user can approve a transition programmatically as a user can approve an object depending on the user and depending on the properties of the object (eg: Managers can approve posts that have the category 'fiction') django-river allows specifying groups and permissions for transitions approval meta. However, this means that if a user has permission or they are part of a group, they can approve all objects. I investigated a possible solution which is adding custom permissions to the model I have in the Meta subclass. Example: class BlogPost(models.Model): title = models.CharField(verbose_name="Title", max_length=255) content = models.TextField(verbose_name="Content") state = StateField() def approve_draft(self, user): self.river.state.approve(as_user=user, next_state=State.objects.get(slug="published")) class Meta: permissions = [ ("approve_draft", "Approve draft"), ] def __str__(self): return self.title Then I added the approve_draft permission to the transition approval meta, and checked if the user has this permission using the has_perm function on the user model. eg: ... ... def has_perm(self, perm: str, obj = None) -> bool: if perm = "app.approve_draft": # I have my logic here to check if the user has … -
Where do I store user personal information
I am creating an application in which a user registers with a username, email, and password. This data is stored in one table. But then the user enters profile information such as photo, bio, activity and such. Do I store this data in the same table as the username, email, and password? Or do I create another table in which I link those in some way? -
Celery instantly kill running task
i want to implement api endpoint for start/stop button with celery (when is running, on backend in while(True) loop do some work) celery version 4.4.6. As broker i use rabbit i stuck with task revoking(i need just instantly kill task) i use this code for that(but it not works) app.control.revoke(started_task.id, terminate=True, signal='SIGKILL') my task looks like that def _grind(): count = 1 while True: count += 1 print(count) # here are many parrallel aihttp requests and database writes... @shared_task(bind=True) def grind(self): asyncio.run(_grind()) and i need is_running state to provide him to my frontend my vain tries... the idea is that when you click on the stop at the task entry, a signal is set to stop and while saving, I cause an exception that interrupts the execution of the task (but the save signal never works) class Task(models.Model): id = models.CharField(max_length=50, primary_key=True) type = models.CharField(max_length=20, choices=TaskType.choices) signal = models.CharField(max_length=20, choices=TaskSignal.choices, null=True, blank=True) user = models.ForeignKey(CustomUser, related_name='tasks', on_delete=CASCADE) @shared_task(bind=True) def grind(self): task_id = self.request.id def cancel_task(instance: Task, **kwargs): print('Never trigger') if instance.id == task_id and instance.signal == TaskSignal.STOP: post_save.disconnect(cancel_task, sender=Task) instance.delete() raise Ignore() post_save.connect(cancel_task, sender=Task) count = 1 while True: count += 1 print(count) # ---- on start-stop click def toggle_grind(user: … -
How to make a constructor through which the user can create a template by adding any field from the model to it, including nested fields?
I have 5 entities that are related to each other. I have successfully described the models and the relationships between them. Everything is good here. But they require a certain constructor from me, which assumes that the administrator can, in user mode (in the admin panel, or on any other page), change the appearance of the check that is printed for the client without changing the source code of the program (i.e. add or remove ticket fields). For example, a user can create 2 receipt templates - "regular" and "reduced". A "regular" check will include the name of the voyage, itinerary, carrier, departure_station and arrival_station, departure_date and arrival_date, place_number, etc., while "abbreviated" will only contain the name of the voyage, departure_date and place_number I will briefly describe the models here: class BusStation(models.Model): name = models.CharField(max_length=64) city = models.CharField(max_length=32) region = models.CharField(max_length=32) class Carrier(models.Model): name = models.CharField(max_length=64) inn_number = models.PositiveBigIntegerField(verbose_name='ИНН', unique=True) class Itinerary(models.Model): name = models.CharField(max_length=64) number = models.CharField(max_length=64) departure_station = models.ForeignKey(BusStation, related_name='departure_busstations', on_delete=models.CASCADE) arrival_station = models.ForeignKey(BusStation, related_name='arrival_bus_stations', on_delete=models.CASCADE) class Voyage(models.Model): departure_date = models.DateTimeField() arrival_date = models.DateTimeField() itinerary = models.ForeignKey(Itinerary, related_name='itineraries', on_delete=models.CASCADE) bus_station_platform = models.PositiveIntegerField() class Ticket(models.Model): TYPE_TICKET = [ ('1', '1'), ('2', '2'), ] passengers_name = models.CharField(max_length=128) voyage = models.ForeignKey(Voyage, … -
having trouble installing django on centos 7
enter image description here been trying to install django on my venv on centos 7. I'm new to using centos and linux in general so i'm having trouble finding out what's causing these errors shown on the screenshot. If it's not clear on the picture I've also pasted it here below. Also, I'm not sure if having two versions of python is maybe causing this. I installed 3.6.8 using the package manager because i did not have an idea that that was the latest version available there so i downloaded 3.10.5 and installed it too. However on the error message that is showing, it seems like 3.6.8 is being mention. I can't understand. Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/pip/_vendor/urllib3/response.py", line 302, in _error_catcher yield File "/usr/lib/python3.6/site-packages/pip/_vendor/urllib3/response.py", line 384, in read data = self._fp.read(amt) File "/usr/lib/python3.6/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 60, in read data = self.__fp.read(amt) File "/usr/lib64/python3.6/http/client.py", line 459, in read n = self.readinto(b) File "/usr/lib64/python3.6/http/client.py", line 503, in readinto n = self.fp.readinto(b) File "/usr/lib64/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) File "/usr/lib64/python3.6/ssl.py", line 971, in recv_into return self.read(nbytes, buffer) File "/usr/lib64/python3.6/ssl.py", line 833, in read return self._sslobj.read(len, buffer) File "/usr/lib64/python3.6/ssl.py", line 590, in read v = self._sslobj.read(len, buffer) socket.timeout: The read … -
How can I pass HTML data from Python to an already created HTML page for display?
I am working on a Django project and would like to take markdown texts, convert them to HTML, and then display them on the browser. I did some research and tried different ways, but none worked as I wanted. This is my code: Python: class HTMLFilter(HTMLParser): text = "" def handle_data(self, data): self.text += data def display_entry(request, entry): if util.get_entry(entry.capitalize()) != None: markdowner = Markdown() data = markdowner.convert(util.get_entry(entry.capitalize())) html = HTMLFilter() html.feed(data) body = html.text return render(request, "encyclopedia/display.html", { "title": entry, "body": body }) else: return render(request, "encyclopedia/error.html", { "entry": entry.capitalize() }) This is how the function (get_entry()) from the util module looks like: def get_entry(title): try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None I use the python-markdown2 package to convert markdown language to HTML and it works perfectly. Below is an example of the text that was converted into HTML. <h1>Django</h1> <p>Django is a web framework written using <a href="/wiki/Python">Python</a> that allows for the design of web applications that generate <a href="/wiki/HTML">HTML</a> dynamically.</p> My biggest challenge is displaying this text as normal HTML to the browser. This is what my HTML file looks like: {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock … -
Django Admin One-To-Many-To-One (Site->Product->Price) Relationship
I'm developing a web app for fun and the goal is to use Django Admin and only Django Admin, without any custom templates (yet). I'm unable to figure out how I should structure my models.py and admin.py files, where what I'm trying to do is: There are many items and many departments: Each item can only belong to one department and each department can have several items. This currently works. Now, what I can't seem to figure out is: There are many sites. Each site can have many items, but the PRICE of each item at each site can be different. For example: Site #123 can have a can of coke for $1.00 Site #124 can also have a can of coke, but at a price of $0.95 Site #123 can have a bag of chips for $1.50 Site #124 can also have a bag of chips, but at a price of $1.95 etc... How do I establish this relationship in Django models.py/admin.py? Also, how could I edit the price using the inline (screenshot below)? In other words, how could the price be shown to the right of the description? Thanks in advance Current Code: admin.py: from django.contrib import admin … -
Django Project Multitenancy Structure
I would like to develop a saas structure made on django. I have the virtual env installed, also the project created. I would need to find a video or help of some how on knowing how to set up the structure for a SAAS CRM System. Basically the structure would be: SUPERADMIN ROLE WITH PERMISSIONS Superadmin (ME) Superadmin Team ( MY TEAM) ADMIN (CLIENT) TEAM MEMBER ( CLIENT TEAM) Also since there are many permissions to define it would be perfect if superadmin can manage the users, roles, profiles and create new ones and delete them. Superadmin would be able to check boxes and uncheck boxes that allow users permissions. Hope someone can help! Thank you -
How can i get actual path of the docx file uploaded to the database using django models?
I am developing a simple web application using django that can take three .docx files containing tables and merge those tables in a single file and return that file to user in downloadable form. I used python-docx library for docx file processing. All three files are uploaded successfully without having any issue but the problem arises when i try to open those document files using doc.Document(file path) constructor of docx library. But the problem is that doc.Document() can't open the word file and it shows error like docx.opc.exceptions.PackageNotFoundError: Package not found at '/media/documents/word/SS_SMS39_CE3_InQfp7c.docx' while it clearly shows the path and while checking on the /media/documents... i can clearly locate that file. I tried a lot on searching about this issue went through docx documentation and even django's fileStorage documentations. But i cannot solve this problem. If you could help me figure out this issue, i will be grateful. I have provided all the models.py, views.py, urls.py, and my templates models.py from django.db import models class Mydocument(models.Model): file1 = models.FileField(upload_to='documents/word/') file2 = models.FileField(upload_to='documents/word/') file3 = models.FileField(upload_to='documents/word/') file_processed = models.FileField(upload_to='documents/word/',null=True,default='documents/word/ssm.docx') views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import DocumentForm from .models import Mydocument import docx as dc def … -
django-jsonforms how to limit how many fields can add from object properties collapsable?
Is there a way so set a range or limit on how many fields a person can add from the object properties collapsable? or any docs on how to configure it? I looked at the docs I could find, but. options = {'additionalProperties': True } form = JSONSchemaForm(schema=jsonschema, options=options, ajax=False) -
request.Meta.get is not working in django appdeployed on heroku
I want to limitize user accessing the endpoints, I have used request.Meta for that, IT is workig properly on local but when I deployed it on heroku, its not working. PLease let me know where I am wrong class ResetPasswordPhoneView(View): def get(self, request, *args, **kwargs): if request.META.get('HTTP_REFERER') != 'http://127.0.0.1:8000/login/' or request.META.get('HTTP_REFERER') != 'https://auth.herokuapp.com/login/': return redirect('login') reset_form = Reset_Password_phones_Form() return render(request, 'phone.html', {'reset_form': reset_form})