Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
id null on django API with mongo and djongo
I need help. My API get me "id": null instead of the uuid given in mongoDB. Here's the results : Result in RestER Result in NoSqlManager And Here's my code : serializers.py from testapp.models import Test class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields=fields='__all__' models.py class Test(models.Model): testChar = models.CharField(max_length=255) testTwo = models.CharField(max_length=255) views.py from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse # Create your views here. from testapp.models import Test from testapp.serializers import TestSerializer @csrf_exempt def testApi(request,id=0): if request.method == 'GET': test = Test.objects.all() test_serializer = TestSerializer(test,many=True) return JsonResponse(test_serializer.data,safe=False) elif request.method == 'POST': test_data = JSONParser().parse(request) test_serializer = TestSerializer(data=test_data) if test_serializer.is_valid(): test_serializer.save() return JsonResponse("Added successfully", safe=False) return JsonResponse("Failed to Add",safe=False) elif request.method == 'PUT': test_data=JSONParser().parse(request) test=Test.objects.get(TestId=test_data['TestId']) test_serializer = TestSerializer(test,data=test_data) if test_serializer.is_valid(): test_serializer.save() return JsonResponse("Update successfully", safe=False) return JsonResponse("Failed to Update") elif request.method == 'DELETE': test=Test.objects.get(TestId=id) test.delete() return JsonResponse("Deleted successfully", safe=False) -
Django: how to solve several Foreign key relationship problem?
I'm currently learning Django and making electronic grade book. I am completely stuck after trying everything, but still cannot solve the problem. I will explain in detail and post all the relevant code below. I need to have two url pages "class_students" and "teacher_current". The first page is for the teacher to see the list of students of a certain class. The table on this page has "action" column. In every cell of this column there is View button, so that the teacher could be redirected to "teacher_current" page and see the list of current tasks, given to a certain student. On this page there is a "Mark" column, its cells may contain EITHER mark given to this student with link to another page to update or delete this mark OR "Add mark" link to add mark on another page. Here comes the problem: everything works correctly, except the thing that each mark is related to a Task class via Foreign key and NOT to a Student class. So every student of the same class has the same marks for the same tasks. But it certainly won't do. Here is all my relevant code: 1) views.py models.py urls.py: https://www.codepile.net/pile/qkLKxx6g 2) … -
Page not found (404) No post found matching the query
I am working with Django and I am just a beginner. I am following this tutorial to create a contact form. But I have this error when I want to go to this URL: http://127.0.0.1:8000/contact/. I have 3 apps in my project(Posts, Users and Contact): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Posts', 'Users', 'crispy_forms', 'Contact', And here is the urls.py in my project : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('' , include('Posts.urls')), path('',include('Contact.urls')), ] And it is urls.py in my Contact app: from django.urls import path from Contact import views app_name = "Contact" urlpatterns = [ path('contact/', views.context, name="contact"), ] And this is views.py in my Contact app: from django.shortcuts import render, redirect from .forms import ContactForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse def context(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Website Inquiry" body = { 'first_name' : form.cleaned_data['first_name'], 'last_name' : form.cleaned_data['last_name'], 'email' : form.cleaned_data['email_address'], 'message' : form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message,'admin@example.com', ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect("Posts:home") form = ContactForm() return render(request, "Posts/templates/contact/contact.html", {'form':form}) I have a templates folder in Posts app and … -
Django: CSRF cookie sometime missing while submitting form
After submit the form, I got csrf forbidden error. So, If I clear browser cookie, the problem is resolved. Suggest me what should I do? -
Heroku Django crashed: at=error code=H10 desc=“App crashed” method=GET path=“/”
I am trying to deploy my Django project on Heroku.But everytime, I have got same error. Heroku restart doesnot work for me. I cleared buildpack and added python buildpack. This has not work for me. I also tried different host like ALLOWED_HOSTS = ['*', '127.0.0.1', 'dailynotes.herokuapp.com']. In Procfile I tried different way like web: gunicorn ToDoApps.wsgi: --log-file - and web: gunicorn ToDoApps.wsgi:application --log-file - --log-level debug python manage.py collectstatic --noinput manage.py migrate This does not work for me. crashed file 2021-08-18T09:37:39.832259+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dailynotes.herokuapp.com request_id=81cc172e-247e-4aa9-8b39-fb9440cd67d2 fwd="103.14.72.227" dyno= connect= service= status=503 bytes= protocol=https 2021-08-18T09:37:40.734680+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=dailynotes.herokuapp.com request_id=8d2598b4-0521-4519-892a-467d2a2642ca fwd="103.14.72.227" dyno= connect= service= status=503 bytes= protocol=https logs --tail 2021-08-18T09:21:46.641887+00:00 app[web.1]: preload_app: False 2021-08-18T09:21:46.641888+00:00 app[web.1]: sendfile: None 2021-08-18T09:21:46.641888+00:00 app[web.1]: reuse_port: False 2021-08-18T09:21:46.641888+00:00 app[web.1]: chdir: /app 2021-08-18T09:21:46.641889+00:00 app[web.1]: daemon: False 2021-08-18T09:21:46.641889+00:00 app[web.1]: raw_env: [] 2021-08-18T09:21:46.641889+00:00 app[web.1]: pidfile: None 2021-08-18T09:21:46.641889+00:00 app[web.1]: worker_tmp_dir: None 2021-08-18T09:21:46.641890+00:00 app[web.1]: user: 9071 2021-08-18T09:21:46.641890+00:00 app[web.1]: group: 9071 2021-08-18T09:21:46.641890+00:00 app[web.1]: umask: 0 2021-08-18T09:21:46.641891+00:00 app[web.1]: initgroups: False 2021-08-18T09:21:46.641891+00:00 app[web.1]: tmp_upload_dir: None 2021-08-18T09:21:46.641909+00:00 app[web.1]: secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} 2021-08-18T09:21:46.641909+00:00 app[web.1]: forwarded_allow_ips: ['*'] 2021-08-18T09:21:46.641909+00:00 app[web.1]: accesslog: - 2021-08-18T09:21:46.641910+00:00 app[web.1]: disable_redirect_access_to_syslog: False 2021-08-18T09:21:46.641916+00:00 app[web.1]: access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" … -
Django S3 : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I'm trying to use s3 to fetch images on my website. I'm trying to use get_object() to access to the image object. The part of the object that I want to return is the Body, which type is StreamingBody. I want to convert the StreamingBody into string to return it. Here is my code : def get_image_link(image): """Get image link""" key = "media/" + str(image) s3 = boto3.client('s3', config=Config(signature_version='s3v4', region_name=settings.AWS_S3_REGION_NAME)) obj = s3.get_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=key) return obj['Body'].read().decode('utf-8') obj['Body'].read() return bytes that I'm tring to decode in utf-8. When I run obj['Body'].read().decode('utf-8'), I get this error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Thank you by advance for your help -
Is there a way of having variable methods/functions in django?
I would like to be able to create functions to use them as "rules" or conditions. let's say i have a bunch of employees, but to calculate commissions to each one i would like to call a function that calculates the output. there are cases where i would reuse the function between employees but cases too where i would only have a function for a single employee. said function can change in time and must apply for all employees with that function. Example: if employee have more than 3 sales, give him/her 15% of beneficts from all sales: i would create a function like this: output = 0 orders = Order.objects.filter(employee = kwargs.get('employee_id')) if len(orders) < 3: return output for order in orders: output += (order.benefits * 0.15) return output Notes: Should be able to receive parameter in KWARGS as variables and others -
importing module into django/python and calling a function which also imports another module, Error
I have django application that i am trying to import a whole module into, i want to import this module which also calls other module but i get this error when i call a function that belongs to the imported module ModuleNotFoundError: No module named 'models' on the first line of the function is from models.regressor import SingleInputRegressor but if include the module or file name as from module_name.models.regressor import SingleInputRegressor the error goes away but there is such lines in the module that i cant do them manually its a machine learning module that am trying to import the whole module into django and just call a function from the model module that begging's the whole process. -
React seems to be requiring that Django Model field associated with the variable in React be declared to POST
I'm fairly new to programming so I am most likely missing something fairly basic but, I have lost a couple day on this issue and can't seem to find a solution. I am following a tutorial from the Great Adib (Source Code: https://github.com/GaziAdib/django_react_fullstack) and I am trying to hook up my React form with my Django backend. I am using axios to handle the API communication and have tested my API using Postman and the Django API UI and it seems to be working just fine, I can even GET data from my Django backend without issues but when I try to POST the data from my form I am running into issues, I keep getting RefrenceErrors on my Django fields that are associated with the according variables in my React code, that it is not defined, here is how I have my code set-up and the error that I am getting: import React, { useState } from 'react'; import { useHistory } from 'react-router'; import axios from 'axios'; [enter image description here][1]const Form = () => { let history = useHistory(); const [firstName, setFirstName] = useState("") const [lastInitial, setLastInitial] = useState("") const [dateVisited, setDateVisited] = useState("") const [foodRating, setFoodRating] … -
React Axios unable to POST to Django Rest Framework
I am trying to post data from react js to django rest api, but getting Method Not Allowed (POST) Settings.py CSRF_COOKIE_NAME = "XCSRF-TOKEN" CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = list(default_headers) + [ 'XCSRF-TOKEN', ] CSRF_TRUSTED_ORIGINS = [ "localhost:3000", "127.0.0.1:3000", ] Request with axios let token = localStorage.getItem("token"); let csrfCookie = Cookies.get('XCSRF-TOKEN'); let res = await axios.post(url + "/add/card/", /* url is working with postman and django */ data, /* data is a JavaScript Object */ { withCredentials: true, headers: { 'X-CSRFTOKEN': csrfCookie, 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Token ' + token } } ); So, I am sending this request headers Accept: application/json, text/plain Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Authorization: Token <token> Connection: keep-alive Content-Length: 186 Content-Type: application/x-www-form-urlencoded Cookie: XCSRF-TOKEN=<token>; sessionid=<token> Host: 127.0.0.1:8000 Origin: http://127.0.0.1:3000 Referer: http://127.0.0.1:3000/ sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="92", "Opera GX";v="78" sec-ch-ua-mobile: ?0 Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 OPR/78.0.4093.153 X-CSRFTOKEN: <token> But getting this response headeres Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://127.0.0.1:3000 Allow: GET, HEAD, OPTIONS Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Wed, 18 Aug 2021 16:42:26 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.8.3 Vary: Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY This unabled post only happens … -
Delete post in django
I know similar kind of question is asked before, but I was not able to get it. This is my first project as a Django beginner. In my Django blog app, I made a delete button but it is not working and I am finding for answers, trying different methods on the web but it did not help. I am trying to do is when admin open the post, then on clicking the delete button, it take the post-id and delete that post and redirect to home page, but it is not working as expected. So, lastly I came here. Any help will be appreciated. Thanks! This is my urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('post/<int:pk>', views.post, name='post'), path('about', views.about, name='about'), path('contact_us', views.contact_us, name='contact_us'), path('register', views.register, name='register'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('create_post', views.create_post, name='create_post'), path('delete_post', views.delete_post, name='delete_post') ] This is my views.py file: def delete_post(request, *args, **kwargs): pk = kwargs.get('pk') post = get_object_or_404(Post, pk=pk) if request.method == 'POST': post.delete() return redirect('/') return render(request, 'delete-post.html') This is delete post html form: <form action="{% url 'delete_post' post.id %}" method="post"> {% csrf_token %} <input type="submit" value="Delete post"> </form> Delete button: <a … -
/bin/sh: 1: apk: not found, while build image docker
I'm trying to create and run a djanog image with the docker to deploy it along with kubernetes, but when I run the image build command, it gives the error "/bin/sh: 1: apk: not found " Dockerfile: FROM python:3.8-slim LABEL maintainer="r.ofc@hotmail.com" ENV PROJECT_ROOT /app WORKDIR $PROJECT_ROOT RUN apk update \ && apk add mariadb-dev \ gcc\ python3-dev \ pango-dev \ cairo-dev \ libtool \ linux-headers \ musl-dev \ libffi-dev \ openssl-dev \ jpeg-dev \ zlib-dev RUN pip install --upgrade pip COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . CMD python manage.py runserver 0.0.0.0:8000 can someone help me? -
Deleting GeoServer layer with Django
I am trying to delete from the GeoServer using Django with request.delete, however, I get the 401 error. GEOSERVER_URL = f"http://admin:geoserver@GEOSERVER:8080/geoserver/rest/workspaces" def delete_geotiff_from_geoserver_task(owner_id, project_id, imageURL): layer_name = f'{owner_id}-{project_id}' workspace_name = 'geotiffs' geoserver_headers = {'Content-type': 'image/tiff'} url = f"{GEOSERVER_URL}/{workspace_name}/coveragestores/{layer_name}" response = requests.delete(url, data=open( f"{imageURL}", 'rb'), headers=geoserver_headers) return {"response code": response.status_code, "url": str(url), "project_id": project_id, "image data": str(imageURL)} I should have the necessary authorizations, and my code for adding a GeoTIFF, which is fairly similar, worked, so I am not sure why this would not work I have included the logs in my Geoserver below 2021-08-16 18:22:00,941 ERROR [org.geoserver.rest] - coveragestore not empty org.geoserver.rest.RestException 401 UNAUTHORIZED: coveragestore not empty at org.geoserver.rest.catalog.CoverageStoreController.coverageStoreDelete(CoverageStoreController.java:178) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:798) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:931) at javax.servlet.http.HttpServlet.service(HttpServlet.java:666) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:352) at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:171) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.geoserver.filters.ThreadLocalsCleanupFilter.doFilter(ThreadLocalsCleanupFilter.java:26) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:69) at org.geoserver.flow.controller.IpBlacklistFilter.doFilter(IpBlacklistFilter.java:89) at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:66) at org.geoserver.wms.animate.AnimatorFilter.doFilter(AnimatorFilter.java:70) at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:66) at org.geoserver.monitor.MonitorFilter.doFilter(MonitorFilter.java:142) at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:66) at org.geoserver.filters.SpringDelegatingFilter.doFilter(SpringDelegatingFilter.java:41) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.geoserver.platform.AdvancedDispatchFilter.doFilter(AdvancedDispatchFilter.java:37) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:70) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) … -
How to fix an error which occurs when I am trying to delete an object related to another objects in Django app as an admin?
I have a class named Customer: class Customer(models.Model): # One to one relationship: customer is a user user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) # Returns the string representation of an object def __str__(self): return self.name ... And a class named Order (customer can have many orders). class Order(models.Model): objects = None # many to one relationship: customer can have many orders customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_order = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) # You can access the parent class from inside a method of a child class by using super() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.id = None def __str__(self): return str(self.id) When I am trying to remove the object of class Customer I have created, named Kasia (which is probably superuser as well) I cannot do it. I have previously deleted this customer's orders and now they are set to Null value. There is a type error and a message: 'Model instances without primary key values are unhashable'. The exception location is as follows: C:\Users\kasia\AppData\Roaming\Python\Python37\site-packages\django\db\models\base.py, line 536, in hash When I want to delete user, the same thing happens. What is happening here? -
Extended user registration (to Profileuser) before login, is it possible?
So am trying to solve this: Registration -> Registration Profile -> Login (In admin Registration = User and RegisterPage = Profileuser app) Got registration working connected to login, but would like the user to add info to the Profileuser app BEFORE login. Am trying to use signals to. Getting error: NoReverseMatch at /profileusers/register/ Reverse for 'RegisterPage' not found. 'RegisterPage' is not a valid view function or pattern name. Really appreciate any help on how to go about it! (And, yes, am new at this, still learning.) url.py from django.urls import path from . import views urlpatterns = [ path('', views.all_profiles, name='profiles'), path('profile_details/', views.profile_details, name='profile_details'), path('profile_edit/', views.profile_edit, name='profile_edit'), path('register/', views.Register, name='register'), path('register_profile/', views.RegisterPage, name='register_profile'), # <int:pk>/ path('login/', views.loginPage, name='login'), ] views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.db.models.functions import Lower from django.http import JsonResponse from django.core import serializers from django.views.generic import TemplateView, View from .models import Profileuser from .forms import ProfileuserForm, EditForm, RegisterUserForm def Register(request): # pylint: disable=maybe-no-member form = RegisterUserForm() if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' … -
Change href to django iterated object with Javascript
I have a template with a formset: <form method='post' id="data_form"> {% csrf_token %} {{ my_formset.management_form }} <table> ... <tbody> {% for form in my_formset %} <tr> {% for field in form %} {% if 'inventory_number' in field.auto_id %} <td> <a href="{% url 'invent:update_item' pk %}" class="update-link"> {{ field.value }} </a> </td> {% else %} <td>{{ field }}</td> {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table> </form> Since the field "inventory_number" is supposed to be immutable anyway, I want it to link to the UpdateView of this item. I can get pk for this item with JS: var links = document.getElementsByClassName('update-link') for (let i = 0; i < links.length; i++){ let link_row = links[i].parentNode.parentNode let item_id = link_row.lastElementChild.childNodes[1].attributes.value.value }; Now how do I pass this item_id form the script to django {% url 'invent:update_item' pk %}? Or maybe there's a better way to do it all together. -
Django duplicate primary keys
I have a form that creates an object with the same previous id after submission. How do I change the uuid to be random each time? class TbTerminalPermission(models.Model): id = models.CharField( primary_key=True, default=str(uuid.uuid4()).replace('-', ''), max_length=60) terminal = models.ForeignKey( 'app.TbTerminal', on_delete=models.CASCADE, db_column='ter_id') user = models.ForeignKey( TbUser, on_delete=models.CASCADE, db_column='user_id') class Meta: managed = False db_table = 'tb_terminal_permission' unique_together = ('id', 'terminal', 'user') class TbTerminalPermissionForm(forms.ModelForm): class Meta: model = TbTerminalPermission fields = ['user', 'terminal'] def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user if self.user: self.fields['user'].queryset = TbUser.objects.filter( id=self.user.id) self.fields['terminal'].queryset = TbTerminal.objects.exclude( tbterminalpermission__user=self.user).filter(customer=self.user.customer) the error Exception Value: (1062, "Duplicate entry 'ea870f29ec124e39aa5251b0862635f3' for key 'PRIMARY'") -
Django not saving form
Im abit lost, in relation to referencing other models in forms. I created the following form which references auditsModel as the model: class auditForm(ModelForm): class Meta: model = auditsModel fields = '__all__' Everything works fine and i am able to delete, add and save data in the form, but then i wanted to create drop down windows with options, and these options(Data validation) were stored in another model called dv_model. So i created the following field using ModelChoiceField which takes as a query the dv_model. Defect_Area_Associate = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Defect_Area_dv',flat=True).distinct(),widget=forms.Select) Everything works but when i click save, and refresh the page, it goes back to how it was. Something else that i noticed is that the other fields that would usually save, if i tried to change them, id get the following error: IntegrityError at /A3QGSDAKRQXG6H/ NOT NULL constraint failed: main_auditsmodel.Defect_Area_Associate So for some reason it doesnt save the form when referencing another model? This is my forms.py: class auditForm(ModelForm): class Meta: model = auditsModel fields = '__all__' #RADIO BUTTONS CHOICES = [('Defect', 'yes'), ('No Defect', 'no')] CHOICES_Action_correctly_captured = [('yes', 'yes'), ('no', 'no')] Audit_outcome = forms.ChoiceField(choices=CHOICES, widget=RadioSelect()) Action_correctly_captured = forms.ChoiceField(choices=CHOICES_Action_correctly_captured, widget=RadioSelect()) Defect_Area_Associate = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Defect_Area_dv',flat=True).distinct(),widget=forms.Select) def __init__(self, *args, **kwargs): super(auditForm, self).__init__(*args, **kwargs) # … -
What should one use for push notification from server side?
Most of the modern framework provide some means to leverage web sockets out of box for example django has django channel, rails has action cable. So in the scenario where you need to build a push notification services for your web application/mobile app what should one use websockets provided by the framework or some external services provided by different cloud providers like amazon sns. Can someone share pros and cons of both? -
Is there a JavaScript library I could use to create a musical notation website? [closed]
I'm working on a musical notation website. The site will provide users with the ability to create scoresheets, similar to noteflight. Is there any JavaScript library I could use for this? It would be even better if I could get an open-source project similar to noteflight. -
How can i get a dropdown for a CharField in Wagtail Admin?
In Django Admin, it is possible to add a dropdown selector with all possible enum values like this example: class ThesisStatus(models.TextChoices): OPEN = 'O', _('Offen') TAKEN = 'T', _('Vergeben') WORK_IN_PROGRESS = 'W', _('In Arbeit') COMPLETED = 'C', _('Komplett') ABORTED = 'A', _('Abgebrochen') status = models.CharField( max_length=1, choices=ThesisStatus.choices, default=ThesisStatus.OPEN, ) In wagtail, this does not work: panels = [ FieldPanel('status'), ] if the field is a CharField, but it does work for a TextField. How can I fix or implement this for CharField? -
How to use paginate_orphans in django function based views?
In Class-Based View We Can Use Like This. class PostListView(ListView): model = Post template_name ='blog/index.html' ordering = ['id'] paginate_by = 5 paginate_orphans = 2 But How can I Use this paginate_orphans in function-based views? page = request.GET.get('page', 1) paginator = Paginator(filter_qs, 2) try: filter_qs = paginator.page(page) except PageNotAnInteger: filter_qs = paginator.page(1) except EmptyPage: filter_qs = paginator.page(paginator.num_pages) -
one to many relationship not showing in admin
I was making a post system with two models Post and Image. I want one post to have multiple images Here is my models class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) content = models.CharField(max_length=150, null=False) images = models.ManyToOneRel( field="image", to="Image", field_name="images") class Image(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) image = models.ImageField() post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="images") When I checked it in admin the images field is not shown. I am not entirely sure how to use ManyToOneRel in django. So far what I understood is I need my post saved before i can add an image. Is there any other way I can have multiple images for one post -
how to compare db fetched data with user selected inputs in django
I am currently working on a django project that store images in database along with additional information(Gender & age groups).To begin with when the project starts it will take user an index page(index.html) index page and after clicking take part button user gets to another page(test.html)challenge page where randomly 9 fetched images from db was showed in a grid manner and asked the user to select particular group of images from the shown images, now I have a "TRY ANOTHER" button in case user wants to reload new set of images with different question and I have a button "NO ONE" in case no images from the given group are shown in the grid. In addition to I have another and last button "VERIFY", by clicking which if the users guess is right ( selected images matches the result of the question ) it will redirect to the index page (index.html) or if user guessed input is wrong it will reload the challenge page with another set of images as well as new question. now my question is: how to compare the data fetched alongside with image with question. when the challenge page is loaded it take so much time, … -
FileNotFoundError when file obviously exists
I am trying to run a Django server in a dev environment (on Debian). I don't want to store my Django SECRET_KEY in the settings file itself, so I have it stored in the /home/admin/keys directory (the server is being run from the admin user). In my settings.py, I have added the following: _secret_key_path = '/home/admin/keys/django-secret-key.txt' with open(_secret_key_path, 'r') as f: _secret_key = f.read() SECRET_KEY = _secret_key When I try running the Django interactive shell (python manage.py shell), I get the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/admin/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/admin/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/home/admin/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/admin/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/admin/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/admin/repos/server/app/settings.py", line 37, in <module> with …