Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultipleObjectsReturned - get() returned more than one User -- it returned 2
views.py def message(request): username = request.GET.get('username') user = User.objects.get() return render(request,'member/message.html',{ 'username':username, 'user' : user }) if User.objects.filter(name=user).exists(): return redirect('/'+user+'/?username='+username) else: new_user = User.objects.create(name=user) new_user.save() return redirect('/'+user+'/?username='+username) def send(request): message = request.POST['message'] username = request.POST['username'] new_message = Message.objects.create(value=message,user=username) new_message.save() return HttpResponse('Message sent successfully') def getMessages(request,user): user = User.objects.get() messages = Message.objects.filter() return JsonResponse({"messages":list(messages.values())}) models.py class Message(models.Model): value = models.CharField(max_length=10000000) date = models.DateTimeField(default=datetime.now, blank=True) user = models.CharField(max_length=1000000) -
How to write character field in foreign key
I am creating a model with the name of area_model and in there I am taking foreign key of another model How to write field name as character field Class area_model(models,Model) Area_Name=model.ForeginKey(Group_Model,on_delete=models.CASCADE) How to write Area_Name in charfield -
sh: 1: Syntax error: Unterminated quoted string\n
I am making an online judge in django frame work I am trying to run a c++ program inside a docker container through subprocess. This is the line where I am getting error x=subprocess.run('docker exec oj-cpp sh -c \'echo "{}" | ./a.out \''.format(problem_testcase.input),capture_output=True,shell=True) here oj-cpp is my docker container name and problem_testcase.input is input for the c++ file C++ code: #include <bits/stdc++.h> using namespace std; int main() { int t; while (t--) { int a, b; cin >> a >> b; cout << a + b << endl; } return 0; } problem_testcase.input: 2 4 5 3 5 error: CompletedProcess(args='docker exec oj-cpp sh -c \'echo "2\n4\n5\n3\n5" | ./output\'', returncode=2, stdout=b'', stderr=b'2: 1: Syntax error: Unterminated quoted string\n') I am not getting what's wrong is in my code -
[Python/Django]How to know source of logs in console
I am currently working on configuring logging in Django and Python. In my django settings.py I configured LOGGING like below. # settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'verbose': { '()': 'django.utils.log.ServerFormatter', 'format': '[{name}][{levelname}][{server_time}] {message}', 'style': '{', }, 'test': { 'format': '[{name}][{server_time}] {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.StreamHandler', }, 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, }, } If I send a request for test, I got this logs. Bad Request: /visit/timetable/ [WARNING][11/Jul/2022 14:18:49] "POST /visit/timetable/ HTTP/1.1" 400 41 What I want is remove this log Bad Request: /visit/timetable/ To remove unwanted logs, I need to know a source of logs. How can I make all logs to display "the source"? -
Django template: How to use variables in an {% if x == y %} statement?
In a Djgano template I want to include a {% if x == y %} statement where both x and y are variables as follows: <title>Category: {{category_id}}</title> <select name="category_id"> {% for category in categories %} <option value="{{category.id}}" {% if category.id is category_id %} selected {% endif %}>{{category.id}} : {{category.name}}</option> {% endfor %} The {{category_id}} variable is set and in the context. It displays correctly if places outside of the {% if %}, but inside the {% if %} bracket does not work. {% if category.id == category_id %} does not work. I assume that in this case category_id is simply read as a non-variable. {% if category.id is {{category_id}} %} {% if category.id == {{category_id}} %} Gives an error: "Could not parse the remainder: '{{category_id}}' from '{{category_id}}'" {% if category.id is category.id %} Works, of course, but of course that means that everything in the loop will become "selected". -
How to make CSS file from Vue work in Django?
I ran npm run build and then python manage.py collectstatic, but when I opened the Django server, the CSS got lost. One thing I noticed was that after build the css file wasn't stored as bundle.css in dist, rather, enter image description here So, I am confused how t specify this in vue.config.js file Here it is... enter image description here -
Cross domain cookie (sessionid, csrf token) with React after deployed Django backend server to AWS EC2
I have Django&React project. Problem is that as Login Authentication use session cookie, but browser is not set sessionid and csrf token in cookie. //React const API = "https://{my-aws-ec2-PublicIP}:8000/api/v1"; //Django //AWS_EC2_DEV_HOST is the variable set my aws ec2 public ip SESSION_COOKIE_AGE = 1209600 # Default: 1209600 (2 weeks, in seconds) SESSION_COOKIE_DOMAIN = AWS_EC2_DEV_HOST //SESSION_COOKIE_DOMAIN = 'https://127.0.0.1' SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None CSRF_COOKIE_DOMAIN = AWS_EC2_DEV_HOST //CSRF_COOKIE_DOMAIN = 'https://127.0.0.1' CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = None Any problems? or Do i must have domain? Everything is fine in localhost. -
Error when create django application on pycharm
Few days ago I installed pycharm, then I create Django project and got error at step general...: Error creating Django application... I use: - python 3.8 - pycharm 2022.1.3 (pro version) - archlinux (kernel 5.15.53-1-lts) - i3 version 4.20 - xorg-server version 21.1.3 Any idea to fix this error? Thanks. -
JSON file of Accesss_token save in my db?
at firts i use java script, python, django and Maria DB. I want to save the information logged in with sns in the DB. enter image description here this is Kakao talk's login code. enter image description here I want to save the underlined information in my DB. enter image description here Code indicating the message window of the second photo. I want to know how to extract and save the JSON file of Accesss_token and save in my db -
How do make some computation on my POST request data in Django?
I am trying to send a POST request to my Django backend ie djangorestframework, rest api, and I am trying to get the data from this request and make some computation and send it back to the client. I get this error: File "/Users/lambdainsphere/seminar/backend/seminar/api/evaluator.py", line 12, in evaluate operand, op, operand2 = exp ValueError: too many values to unpack (expected 3) Here's my view: @api_view(['POST']) def compute_linear_algebra_expression(request): """ Given a Linear Algebra expression this view evaluates it. @param request: Http POST request @return: linear algbera expression """ serializer = LinearAlgebraSerializer(data=request.data) if serializer.is_valid(): serializer.save() data = serializer.data algebra_expr = data['expression'] #algebra_expr = tuple(algebra_expr) print(algebra_expr) algebra_expr = evaluate(algebra_expr) return Response({"expression":algebra_expr}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) here is my evaluator: it consumes a python3 tuple: def evaluate(exp): """ Evaluate a Linea Algebra expression. """ operand, op, operand2 = exp if isinstance(operand, Vec) and op == '+' and isinstance(operand2, Vec): return operand + operand2 elif isinstance(operand, Vec) and op == '-' and isinstance(operand2, Vec): return operand - operand2 elif isinstance(operand, Vec) and op == '*' and isinstance(operand2, Vec): return operand * operand2 elif isinstance(operand, Vec) and op == '*' and isinstance(operand2, int): return operand * operand2 elif isinstance(operand, Matrix) and op == '+' and isinstance(operand2, … -
django-import-export exclude cannot work with a `fields.Field(ForeignKeyWidget(...`
I want name field be a description in export file, don't import it if it exists. But it always find instances with name and got a return more than 2 error. class Employee(models.Model): name = models.CharField(max_length=180, null=True, blank=True) id_number = models.CharField(max_length=180, null=True, blank=True, unique=True) class EmployeeFootprint(models.Model): rcsp = models.CharField(max_length=180, null=True, blank=True) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True) class EmployeeFootprintResource(resources.ModelResource): employee = fields.Field(column_name='id_number', attribute='employee', widget=ForeignKeyWidget(models.Employee, 'id_number')) name = fields.Field(column_name='name', attribute='employee', widget=ForeignKeyWidget(models.Employee, 'name')) class Meta: model = models.EmployeeFootprint exclude = ['id', 'name'] import_id_fields = ['employee', 'rcsp'] -
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)