Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Returning full exception trace to front-end on a 400
So just for closed beta and internal testing purposes I'm trying to return the exception with the 400 error in my Django server. Here is an example below of how I am doing this in Django code. I have a partner working on the front-end and they said they can't get the error out of the 400 response. I assumed it'd be in like response.body['error']. How can I send back a 400 with the full error trace in a way that can be pulled out by the front-end? except Exception as e: return Response(dict(error=str(e), user_message=error_message_generic), status=status.HTTP_400_BAD_REQUEST) -
error occured while reploying django app on heroku
2021-12-19T13:18:18.028596+00:00 app[web.1]: File "", line 953, in _find_and_load_unlocked 2021-12-19T13:18:18.028635+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed 2021-12-19T13:18:18.028675+00:00 app[web.1]: File "", line 1006, in _gcd_import 2021-12-19T13:18:18.028714+00:00 app[web.1]: File "", line 983, in _find_and_load 2021-12-19T13:18:18.028764+00:00 app[web.1]: File "", line 965, in _find_and_load_unlocked 2021-12-19T13:18:18.028834+00:00 app[web.1]: ModuleNotFoundError: No module named 'home' 2021-12-19T13:18:18.292460+00:00 heroku[web.1]: Process exited with status 1 2021-12-19T13:18:18.370187+00:00 heroku[web.1]: State changed from starting to crashed 2021-12-19T13:21:06.146372+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=aai-mes.herokuapp.com request_id=2b6669e7-58ca-4754-a66e-ccd32ef5e49b fwd="152.57.134.21" dyno= connect= service= status=503 bytes= protocol=https 2021-12-19T13:21:06.532523+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=aai-mes.herokuapp.com request_id=d2c98d53-350b-4f79-84db-93cf40fb1104 fwd="152.57.134.21" dyno= connect= service= status=503 bytes= protocol=https -
Django downloading a file
i have a db i made it with Django, and with the models.CharField I created the path how the users going to upload a file in their post. in MEDIA_URL = "/media/" but i tried to let the user download the content (the file) throw a link or just a click. how can i do that! i have a multiple files name in my models.py like this: files_Tensile = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") files_Charpy = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") files_Modulus = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") Diagramm_Hohen_Temp = models.ImageField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") files_Metallo = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") Gefüge = models.ImageField(blank=True, null=True, upload_to="chapters/%Y/%m/%D") Diagramm_Wärmebehandlung=models.ImageField(blank=True,null=True,upload_to="chapters/%Y/%m/%D") files_Density = models.FileField(blank=True, null=True, upload_to="chapters/%Y/%m/%D" the views.py: def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 in the html: <td><a href="media/files_Density/download"> Download Files</a></td> I get the error, Page not found (404). can anyone please explain how to fix this? -
I want to write an a-cinch export report using python- django
I have an heavy data which I want to export, I have problem that because it's heavy it is timeout and fail. Do you know I can I write an a-cinch report using django? -
How to connect two applications and hit the API of the first application1 from application2
How can I connect two applications with the scenario below? Application1: Our infrastructure was created on AWS with python-django and react, its a private VPC that i can only access via SSH to the EC2 bastion instance (as far as to be able to write codes into)and the way the backend was deployed to create the backend URL api.mywebsite.com (which has multiple endpoints) was through cloudfront and Route53. (www.mywebsite.com was built via s3 and can talk to the backend api.mywebsite.com). Application2: (This is a client infrastructure) At this time i haven't met the client to know what their system is made of but regardless i need to find a way write some codes on this system when a specific event is triggered to send data to an API endpoint of Application1. What would be the best way to implement such an API to connect Application1 and Application2? This is pretty much the same way that someone would use an API like STRIPE...I guess, but i am not sure how to achieve such result... thank you in advance -
Iterating over queryset of dictionary
I have a queryset dict which I want to access in template, I have following queryset: <QuerySet [{'membership__name': 'm1', 'membership_count': 2}, {'membership__name': 'm2', 'membership_count': 1}]> I have tried some options but can't seem to get what I want. {% for key, value in reports_data %} {{key}} : {{value}} {% endfor %} Can anyone please help me how can I do it. -
Increment value in while-loop based on rank
I am currently working on a Django application where a user can track played golf rounds and compare them to friends. Some background on this: Every player has a handicap which gives them a number of extra strokes on each course they are playing. These extra strokes are distributed over all holes depending on the difficulty of the hole (called HCPI, the number of the hole is not equal to its HCPI). E.g. you are playing an 18 hole course. If you get 18 extra strokes, they are equally added to the par of every hole. If you get 20 extra strokes, you get one stroke added to the par of hole 1-18 and one stroke added to the hole ranked 1 and 2. And so on. I am currently stuck in adding the extra strokes on the current par. The problem itself seems to need a while-loop and some javascript. But I wonder if my whole set-up is wrong? As I want to add the whole table to a database later on, it might be a better solution to add the extra strokes there. Any input is appreciated as I would like to have a solution where the user … -
Using aggregation on subquery in Django ORM
I have a table like this Category Subcategory Sub_subcategory Cat_1 Subcat_1 Sub_subcat_1 Cat_1 Subcat_1 Sub_subcat_2 Cat_1 Subcat_2 Sub_subcat_3 Cat_2 Subcat_2 Sub_subcat_4 Cat_3 Subcat_3 Sub_subcat_5 And I need to find in how many categories each subcategory appears. So my expected output based on above table would be: Subcategory Total Subcat_2 2 Subcat_1 1 Subcat_3 1 So I can get that by running following SQL query: SELECT subcategory, count(*) total FROM ( SELECT DISTINCT subcategory, category FROM table_1 ) as temp_table GROUP BY subcategory ORDER BY total DESC I spent a lot of time trying to get the same result with Django ORM but wasn't able to get it done. I expected this code to work: subquery = Table1.objects.values('subcategory', 'category').distinct() results = subquery.annotate(total=Count('*')).values('subcategory', 'total').order_by('-total') But it works exactly the same as without 'distinct()' in subquery, so it counts all categories for every subcategory. I also tried to find similar case in other questions, but those with subqueries usually relate to JOINing tables and using OuterRef, here it is more like getting results based on temporary table that is created by subquery. Does anyone know how can I achieve that (or if it's even possible)? -
retrieve data from views to html in template in django
from django.shortcuts import render from django.http import HttpResponse mList=[ { 'id':1,'title':'ECOMMERCE WEBSITE','description':"ECOMMERCE IS GOOD" },{ 'id':2,'title':'Graphic WEBSITE','description':"graphic IS GOOD" },{ 'id':3,'title':'PORTFOLIO WEBSITE','description':"portfolio IS GOOD" }, ] def single(request,pk): projectObj = None for i in mList: if i['id'] == pk: projectObj = i return render(request,'appone/single-project.html', {'pobj': projectObj }) and in html in template folder I use: <h1> {{pobj.title}}--{{pobj.description}}</h1> but nothing appears there:( whats the problem ? It should work fine -
Django admin chained select using django-select2
I have a standard model City with a Foreign Key to Country. In my django admin, I want to implement the so-called chained select, i.e. first we pick the country and then based on that we pick the city. It would be perfect if I could also pick the city first and then get the country on the spot. Also, what makes this case more complicated is that we pick cities and countries in an inline. How do I do this? -
Django - Ensure ordering of response data is newer first
So I have some code below that returns posts that are newer than a post with post_uuid given. This is ensured because I force an ordered uuid scheme where each Post is given a uuid in order of creation. I want to enforce that that the returned serializer.data is ordered by Post creation data, with the newest best first or index=0 and oldest being last. How do I ensure this? view.py def query_to_full_post_data_serializer(request, post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar') ) return FullPostDataSerializer(query_set_annotated, many=True) @api_view(['GET']) def get_newer_posts(request, post_uuid, count): query = generate_followee_or_join_goal_follow_query(request) query = query & Q(uuid__gt=post_uuid) serializer = query_to_full_post_data_serializer(request=request, post_query_set=Post.objects.filter(query).order_by('uuid')[:count]) return Response(serializer.data, status=status.HTTP_200_OK) serializer.py class FullPostDataSerializer(serializers.ModelSerializer): creator_username = serializers.SlugField() creator_avatar_url = serializers.SlugField() class Meta: model = Post fields = ( 'body', 'created', 'creator_username', 'uuid', 'creator', 'creator_avatar_url') Tried Solutions serializer.data.reverse() doesn't reverse the list for some reason. -
View not returning ID
I have a view that requires two args to be provided. Project_id and Questionnaire_ID There is a Project and Questionnaire model. class Questionnaire(models.Model): title = models.CharField(max_length=50, blank=False, unique=True) class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) I have a project details page, which is basically just a project landing page and from there I have a link to the questionnaire. the link is formed via a For loop {% for item in questionnaire %} <a class="dropdown-item" href="{% url 'questions' project.id questionnaire.id %}?next={{ request.path|urlencode }}">Questionnaire</a> {% endfor %} and my url conf is path('questions/<int:project_id>/<int:questionnaire_id>', view=add_fundamental_answers_view, name="questions"), but when i load the project_details page i get an error Reverse for 'questions' with arguments '(1, '')' not found. 1 pattern(s) tried: ['questions/(?P<project_id>[0-9]+)/(?P<questionnaire_id>[0-9]+)$'] So it looks like the questionnaire_id is not being past in, but i'm not sure why? def add_fundamental_answers_view(request, project_id, questionnaire_id): project = get_object_or_404(Project, pk=project_id) questionnaire = Question.objects.filter(questionnaire_id=questionnaire_id) next = request.POST.get('next', '/') if request.method =='POST': formset = AnswersForm()(request.POST) if formset.is_valid(): answer = formset.save(commit=False) answer.project_name = project answer.save() return HttpResponseRedirect(next) else: form = AnswersForm() return render(request, 'pages/formset.html', {'project': project, "form": form,'questionnaire':questionnaire}) Any ideas where I'm going wrong? Thanks -
I am getting TemplateDoesNotExist error in Django version 4.0
urls file from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('hello/', views.say_hello), path('name/', views.name), path('tp/', views.tp) ] #views file def tp(request): return render(request, 'TP.html') -
What to use: Provide canvas frontend using backend api
I am thinking about a web page providing some 2d-like animations based on backend data. The animations/action change frequently based on the backend data. . Currently I am thinking about using React and combine with canvas So my thinking was to provide the data via some end point as json and using react to build the frontend.But using canvas in react found me only a few links. [1]: https://thibaut.io/react-canvas-components The most similar question I found on stack was this [2]: Mixing HTML5 Canvas and Python. But the answers are almost a decade old. Can someone provide me some basic approach / links so I am not starting totally off? Thank you in advance! cheers! hobo -
Django form error: django.db.utils.IntegrityError: UNIQUE constraint failed: legal_useragreedtolegal.user_id
Whenever, I call form.save() I get "django.db.utils.IntegrityError: UNIQUE constraint failed: legal_useragreedtolegal.user_id" I think this might be because I have a oneToOneField and Django is trying to save to UserAgreedToLegal and User Model but the User model already has that ID, so the unique constraint fails, but not sure. I am wondering how I can fix this issue. I listed my model, form, and view code below models.py import uuid from django.contrib.auth.models import User from django.db import models from django.utils import timezone as django_timezone class UserAgreedToLegal(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) agreed_first_terms_of_service = models.BooleanField(default=False, blank=False, null=False) date_agreed = models.DateField(null=True, default=django_timezone.now) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) def __str__(self): return self.user.username forms.py from django import forms from legal.models import UserAgreedToLegal class TermsOfServiceAgreementForm(forms.ModelForm): class Meta: model = UserAgreedToLegal fields = [ 'agreed_first_terms_of_service' ] views.py if request.method == 'POST': form = TermsOfServiceAgreementForm(request.POST) if form.is_valid(): form.clean() terms_of_service_agreement = form.save(commit=False) terms_of_service_agreement.user = request.user terms_of_service_agreement.save()``` -
http://localhost:8000/token/ 400 (Bad Request)
in django, i have the jwt module for drf (it is called simple-jwt), and i have set up the urls as instructed in the docs, how do i fix the error, in backend side, the whole login process is supposed to be POST request: urls.py urlpatterns = [ path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), now for react part (frontend): function Login(){ let [login,setLogin] = useState({ email: '', password:'' }); let cookie = Cookies.get('csrftoken'); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ const token = localStorage.getItem('token'); e.preventDefault(); axios.post('http://localhost:8000/token/',login,{withCredentials:true},{headers: {'Content-Type': 'application/json', 'X-CSRFToken': cookie,'Access-Control-Allow-Origin':'*','Authorization': `Bearer ${token}`}}) .then(res => { console.log(res.data); } ) .catch(err => console.log(err)) } return ( <div className="container"> <form method='post' onSubmit={handleSubmit}> <h1>Login</h1> <label> Email: <input type='text' name = 'email' value={email} onChange={e=>handleChange(e)} required/> </label> <label> Password: <input type='password' name = 'password' value={password} onChange={e=>handleChange(e)} required/> </label> {isLoggedin = true} <button type='submit'>Login</button> </form> <p className='mt-3'> Don't have an Account? <Link to='/signup'>Sign Up</Link> </p> </div> ); }; export default Login; ``` this is login component, I am getting bad request (400) error, but I cant find out why, and how to fix it? if there is anything else (more code, or more information) to add, … -
How do I override Django's default form error templates - at the project level?
I know this topic has been asked a few times before on StackOverflow, and the docs seem pretty clear about how to do it, but it's not working for me and I'm stumped. Overriding at the project level makes the most sense to me so I created a templates directory outside my app directories - at the same level as manage.py - and I added that directory path to my TEMPLATES['DIRS'] setting TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [BASE_DIR / 'templates'], # Allow overriding of other apps templates 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I checked where the form is getting its error template by printing the path in the View print(form.errors.template_name) The print statement printed django/forms/errors/dict/default.html so I put a new custom default.html file inside mydjangoproject/templates/django/forms/errors/dict/. This doesn't work however. My new default.html template file isn't being used. Any ideas for what I'm doing wrong? -
Data validation on api endpoints ? What approach do you guys take?
To provide context to my question, consider this example. We have three tables (these are fictitious) animal -> [id, name] animal_breed -> [id, name, animal, userId] animal_registration_table -> [id, userId, breedId] Now i have seen two kinds of devs, One who does not validate if the breedId being inserted actually belongs to the user. They just enter the data to db directly assuming that the app or frontend will send them valid data. One who first checks if the breedId belongs to userId by checking from the animal_breed table Now i am more of the 2 guy. But i want to know what approach is good, approach 2 requires an additional query or check, or is there a better way to do this by having constraint in db and if so can you help me on directing me to what sort of constraints should i have or any other better alternative, as i don't feel point 1 is a good way to go. (p.s not that highly skilled with db so require direction and help) -
Envoy proxy: 503 Service Unavailable
Client(Nuxt) is up on http://localhost:3000 and the client sends requests to http://0.0.0.0:8080/. Server(Django) is up on 0.0.0.0:50051. I configured the envoy.yaml file as follows: static_resources: listeners: - name: listener_0 address: socket_address: { address: 0.0.0.0, port_value: 8080 } filter_chains: - filters: - name: envoy.filters.network.http_connection_manager typed_config: "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager codec_type: auto stat_prefix: ingress_http route_config: name: local_route virtual_hosts: - name: local_service domains: ["*"] routes: - match: { prefix: "/" } route: cluster: greeter_service max_stream_duration: grpc_timeout_header_max: 0s cors: allow_origin_string_match: - prefix: "*" allow_methods: GET, PUT, DELETE, POST, OPTIONS allow_headers: keep-alive,user-agent,cache-control,content-type,content-transfer-encoding,custom-header-1,x-accept-content-transfer-encoding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout max_age: "1728000" expose_headers: custom-header-1,grpc-status,grpc-message http_filters: - name: envoy.filters.http.grpc_web - name: envoy.filters.http.cors - name: envoy.filters.http.router clusters: - name: greeter_service connect_timeout: 0.25s type: logical_dns http2_protocol_options: {} lb_policy: round_robin load_assignment: cluster_name: cluster_0 endpoints: - lb_endpoints: - endpoint: address: socket_address: address: 0.0.0.0 port_value: 50051 But the following error occurs and, as it seems, the requests do not reach the Django 0.0.0.0:50051 server. 503 Service Unavailable grpc-message: upstream connect error or disconnect/reset before headers. reset reason: connection failure, transport failure reason: delayed connect error: 111 -
Django, I'm not able to pass a variable from Views to html template
Good day, I'm new to Django and following CS50Web. I've been having a headache for a couple of days trying to understand why this is not working. Basically we have a Flights model and a Passengers model with a many-to-many relationship. here is the views.py code: def flight(request, flight_id): flight = Flight.objects.get(pk=flight_id) passengers = flight.passengers.all() print(passengers) return render(request, "flights/flight.html", { "flight": flight, "passengers:": passengers }) and here is the html: <h2> Passengers </h2> <ul> {% for passenger in passengers %} <li>{{ passenger }}</li> {% empty %} <li>No passengers.</li> {% endfor %} </ul> I know the passengers variable is not empty, the print statement returns: "<QuerySet [<Passenger: Fidel Castro>, <Passenger: James Bond>, <Passenger: Larry Bird>]>" Still, the rendered Html page always shows no passengers! Could a good soul help me understand what I'm I doing wrong? Because I'm out of ideas at this point. Thank you in advance -
Django Upload File to S3
How do I link my form to upload in AWS S3 and display the avatar? (Using views.py) I just need to use my current bucket which works for static files for media after making the media file private and only for authenticated users to use. models.py from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): """ bio = models.TextField(max_length=500, blank=True) phone_number = models.CharField(max_length=12, blank=True) birth_date = models.DateField(null=True, blank=True) """ avatar = models.ImageField(default='default.png', upload_to='users/', null=True, blank=True) pages/forms.py from django import forms from django.core.files.images import get_image_dimensions from pages.models import Profile class UserProfileForm(forms.ModelForm): class Meta: model = Profile def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 100 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 20k.') except AttributeError: """ Handles case when we are updating the user profile and do … -
django video file not playing
I am trying to build a video streaming app with django. class Video(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) thumbnail = models.ImageField(upload_to='thumbnail', blank=True, null=True) file = models.FileField(upload_to='video', validators=[FileExtensionValidator(allowed_extensions=['mov', 'MOV','avi','mp4', 'MP4','webm','mkv'])]) list view {% for video in page_obj.object_list %} <video width="400" height="350" controls {% if video.thumbnail %} poster="{{ video.thumbnail.url }}" {% endif %} > <source src= "{{ video.file.url }}" type="video/mov"> </video> {% endfor %} The result is that when I click on play, it stuck at thumbnail and no data displayed on timeline, which video is not loaded. When I goes to the url of the video, there is an error in console Failed to load resource: Plug-in handled load I wonder why this happens, will be grateful for your help. in addition, in html, type attribute of source tag, is there a way I can get meta type definition from FileField? for example, if it is mp4 I want to get video/mp4 in string. >>> from video.models import Video >>> vs = Video.objects.all() >>> v = vs[0] >>> v.video Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Video' object has no attribute 'video' >>> v.file <FieldFile: video/roc_i9zy5He.mov> >>> v.file.url '/media/video/roc_i9zy5He.mov' >>> v.file.type Traceback (most recent call last): File … -
This page isn’t working , redirected you too many times. django
When I run python manage.py runserver the server runs fine. But the web page show the redirection. I have attached the image link below. how can I resolve the issue? redirected you too many times -
Select a valid choice. 1 is not one of the available choices. django error
I am creating an app that needs value from views.py for filtering data in choice field. So I passes the data from views to init using kwargs. I wrote a query and added that in choice field in init. The data is displaying correctly but when I post the form It throwing the above error. "Select a valid choice. 1 is not one of the available choices." class General(ModelForm): def __init__(self, *args, **kwargs): self.n_data1 = kwargs.pop('data1') super(GeneralPostingForm, self).__init__(*args, **kwargs) CHOICES = Glheads.objects.filter(data=self.n_data1, status=1, acmast=1) new_choices = [ (p.head, f'{p.head}-{p.detail}') for p in CHOICES ] self.fields['head'].choices = new_choices head = forms.ChoiceField(widget=forms.Select(), label='HEAD') -
Request permission not appearing in fcm for django
I am using gitpod to test the push notifications that I have setup in DJnago using firebase. Everything went well but in the end the request permission dialog box didn't appear. I am not sure what is the cause. The link that I followed is this one: https://blog.hipolabs.com/testing-push-notifications-locally-with-firebase-ef052531af03 It was supposed to come like this: But in mine it appears like this: The request permission button is missing on mine. I have done several attempts but the same result. The index.html file looks like this: function requestPermission() { console.log('Requesting permission...'); Notification.requestPermission().then((permission) => { if (permission === 'granted') { console.log('Notification permission granted.'); // TODO(developer): Retrieve a registration token for use with FCM. // In many cases once an app has been granted notification permission, // it should update its UI reflecting this. resetUI(); } else { console.log('Unable to get permission to notify.'); } }); }