Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to I play an .wav file in an <audio> field by setting the source to my Audio field Model(DataBase)?
I haven't been able to find anything online that can help me with this yet. I am trying to play some .wav audio files that I have stored in my Django Model. I am having trouble finding a way to create an instance/query to my database and then being able to use that in my HTML page where my audio field is. Here is what I have so far... HTML <audio controls id="listen "> <source class="form-control" src="{{ }}" type="audio/wav"> </audio> Model.py class Media(models.Model): title = models.CharField(max_length=100) key = models.IntegerField() audioFile = models.FileField() duration = models.FloatField() isPlaying = False view.py def audioPlayer(request): return render(request, "Website/myWebSite.html" I am just trying to figure out a way I can set the source on the tag to pull from the Media Model. Any suggestions? -
How to access a parent model from one of my fk fields?
I'am trying to access a parent instance from its child. I have the following models class ModelA(models.Model): user_name = models.Charfield() points = models.Charfield() class ModelB(models.Model): user = models.ForeignKey(ModelA) points = models.Charfield() class ModelC(models.Model): model_b = models.OneToOne(ModelB) info = models.TextField() And I'am doing a query like this: ModelB.objects.filter({somefilters}).values('user__user_name') But I want to check if there is a reference to B in C, and if there is get the info. I can't start from ModelC as: ModelC.objects.filter({somefilers}).values('model_b__user__user_name') Because there maybe or not a record relating both models. Is possible to get starting from ModelB to get info from its parent ModelC? -
Aggregation in Django
Model: class A(models.Model): nr = models.IntegerField() class B(models.Model): points = models.IntegerField() class C(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) So for every A there are many entries in C, and for every B there are also many entries in C. But every entry in C there is exactly one entry in A and one in B. I would like to sum up the B.points for a given A. How can I do that in Django? I would know how to do that in SQL if that helps? -
passing headers to Django channels using Javascript Websockets to authenticate user using Token
i have no idea how to connect and authenticate django channels using token authentication because javascript websockets doesnt support passing headers to the server class TokenAuthMiddleware: """ Token authorization middleware for Django Channels 2 """ def __init__(self, inner): self.inner = inner def __call__(self, scope): headers = dict(scope['headers']) if b'authorization' in headers: try: token_name, token_key = headers[b'authorization'].decode().split() if token_name == 'Token': token = Token.objects.get(key=token_key) scope['user'] = token.user except Token.DoesNotExist: scope['user'] = AnonymousUser() return self.inner(scope) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) I have found this answer regarding authentication using token but the thing is I don't understand how to pass headers to the server token = Token.objects.get(key='175f76fd9b63a9477bf5f9a6f2e9a7f12ac62d65') if token.user: scope['user'] = token.user else: scope['user'] = AnonymousUser() return self.inner(scope) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) when ever i manually authenticate users the channels can recognize user and authenticate him i have tried def get(request): for user in User.objects.all(): token=Token.objects.get_or_create(user=request.user) if token.user: print("ok") else: print("not okay") print(token) adding this function in the same class TokenAuthMiddleware i thought this would work but it's not working so that i can use the token generated to authenticate users I just want to know is there any way where i can authenticate users using token -
Creating a comment-system in Django 2
I've tried creating a comment-system in Django 2 I have tried assigning the comment to a post ID. I still cant seem to figure it out. My models.py: class post_id(models.Model): user_post_id = models.IntegerField(null=True) class Comments(models.Model): post = models.ForeignKey(post_id, on_delete=models.CASCADE, null=True) post_comment = models.TextField(null=True) comment_id = models.CharField(max_length=255, null=True) class posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_text = models.TextField() post_likes = models.IntegerField(null=True) post_id = models.ForeignKey(post_id, on_delete=models.CASCADE, null=True) post_category = models.ForeignKey(Category, on_delete=models.CASCADE) post_likes = models.IntegerField(default=0, null=True) post_comments = models.ForeignKey(Comments, on_delete=models.CASCADE, null=True) datetime = models.DateTimeField(auto_now_add=True) user_ip = models.CharField(max_length=100) user_agent = models.CharField(max_length=255) -
Django TypeError at /url/ get() missing 1 required positional argument
I'm having trouble with this because in my localhost the url can receive 2 optional arguments, the url can receive just one but not both. testing the route locally works, but not when in production, i get this error: TypeError at /url/ get() missing 1 required positional argument: 'pk' in the urls.py file: urlpatterns = [ path('url/<int:pk>', Class.as_view()), path('url/', Class.as_view()), path('url/<int:option>',Class.as_view()), #etc... more routes below in my Class.py file: class Class(APIView): def get(self, request, pk = None, option = None): # more code below... Note: i change the name of the class & routes for job reasons... Not sure why works locally but not in server production, any ideas? what i'm missing? -
Django default session
I want to give user some default session when joining website, without pressing anything.One way is to include request.session['lang']='en' at the home page class but what if first time joining user tries to access another class. -
Why isn't Django detecting the data I'm sending in a javascript fetch POST request?
I'm POSTing data using the fetch api. In the body I send the employee_id, yet I'm getting a MulitDictKey error from Django saying it (and the other data, for that matter) wasn't received. Why isn't it sending? Is there something I'm missing? In my html file (in the script tag): const graduateEmployee = row => { const token = row.querySelector('INPUT').value fetch('/questions/ajax/update_employee', { method: 'POST', headers: { "X-CSRFToken": token, "Accept": "application/json", 'Content-Type': 'application/json' }, body:JSON.stringify({ employee_id: row.id, column: 'mentor_status', new_value: false }) }).then((res) => res.json()) .then((response) => console.log('Success:', JSON.stringify(response))) .catch((err)=>console.log('Error:', err)) } In my views.py: def update_employee(request): employee_id= int(request.POST["employee_id"]) column = request.POST["column"] new_value = request.POST["new_value"] employee = Employee.objects.get(employee_id = employee_id) employee[column] = new_value employee.save() return HttpResponse(f'{column} column for employee with id{employee_id} set to {new_value}') Error Page: MultiValueDictKeyError at /questions/ajax/update_employee 'employee_id' Request Method: GET Request URL: http://127.0.0.1:8001/questions/ajax/update_employee Django Version: 2.2.2 Exception Type: MultiValueDictKeyError Exception Value: 'employee_id' Exception Location: C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in getitem, line 80 Python Executable: C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.1 Python Path: ['C:\Users\dklaver\mentor-program\mentor', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32', 'C:\Users\dklaver\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages', 'C:\Users\dklaver\mentor-program\mentor\helpers', 'C:\Users\dklaver\mentor-program\mentor\cron'] Server time: Fri, 5 Jul 2019 17:42:18 +0000 Traceback Switch to copy-and-paste view C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in getitem list_ = super().getitem(key) … ▶ Local vars During handling of the above exception ('employee_id'), another exception … -
Django: how to mock a class inside the API view
Title might be a little confusing. Say I have an APIView with a post method. Inside the post method, I introduced a class that has its own method. In this case, it's a class that deals with uploading to S3, which is something I want to skip when running unittest. class SomeView(APIView): def post(self): # do something here input1 = some_process(payload_arg1) input2 = some_other_process(payload_arg2) uploader = S3Uploader() s3_response = uploader.upload_with_aux_fxn(input1, input2) if s3_response['status_code'] == 200: # do something else return Response('Good job I did it!', status_code=200) else: return Response('noooo you're horrible!', status_code=400) Real code has different function calls and responses, obviously. Now I need to mock that uploader and uploader.upload_with_aux_fxn so I don't actually call S3. How do I mock it? I tried in my test script class SomeViewTestCase(TestCase): def setUp(self): self.client = APIClient() uploader_mock = S3Uploader() uploader_mock.upload_support_doc = MagicMock(return_value={'status_code': 200, 'message': 'asdasdad'} response = self.client.post(url, payload, format='multipart') But I still triggered S3 upload (as file shows up in S3). How do I correctly mock this? -
Django create related objects in save() not saving to DB
I have a mode Profile that has a related object set of ProfileSiteFields (ProfileSiteFields has a FK to Profile). I want to create ProfileSiteFields on creation of a new Profile based on some business logic. For some reason, the related objects are created fine, but not saving to the DB. def save(self, *args, **kwargs): is_new_object = self._state.adding super(Profile, self).save(*args, **kwargs) if is_new_object: self._create_profile_site_fields_objects() def _create_profile_site_fields_objects(self): site_ids_to_create = SiteWhiteLabeling.objects.filter( copy_profile_id_to_site_fields=True ).values_list('site', flat=True) for site_id in site_ids_to_create: site_field_obj = ProfileSiteFields.objects.create( profile=self, site_id=site_id, external_id=self.unique_id ) When I log out site_field_obj in the for loop, everything is as expected - something like this: { '_profile_cache': Profile : TEST NEW PROFILE 6 - Unknown, '_state': <django.db.models.base.ModelState object at 0x7f21644dd2d0>, 'site_id': 7, 'external_id': u'P3DAB584', 'id': 23498, 'profile_id': 28611 } ... it just doesn't save to the DB. I also tried this syntax site_field_obj = ProfileSiteFields(...) site_field_obj.save() and calling .save() from the debugger, but when I query for the object in ProfileSiteFields, it's not there. Any suggestions on what is missing? -
How to have a field represent the count of related objects
I have a couple of Django models, Channel and Recording. Channels have a one-to-many relationship with recordings, such that a channel may have many recordings. Within the Channel model, I currently have 2 fields, num_recordings, and storage_size, which are right now created as Integers, but which I want to have dynamically generated as the result of a DB query. E.g. num_recordings should be the current count of recordings on a given channel, and storage_size should be the sum of a field "size" for each of the recordings on a given channel. I'm using Django rest framework to give a JSON representation of the models, and want it so that when I query the Channel, I see these two fields as Integers, but don't want to have to calculate these separately, e.g. it would be ideal if when you query the Channel endpoint, it would perform a count on the recording relationship, and return that as "num_recordings" and a sum on the recording.size field for all recordings in the relationship and report that on the storage_size field. How can I do this? -
My domain name keep switching from example.com to mydomainname.com
After struggling to finish the project, I built a sitemap. After pushing it digital ocean, I and signing up to Google search console it gave out an error (from Google console) invalid domain name. When I looked at the generated file from mydomainname.com/sitemap.xml I saw that example.com is appended to sitemap instead of my domain name. I removed example.com from Sites. But it's showing same thing. I found an article on stackoverflow and realised that I should've changed the name from instead of deleting it. I went on my server and turned the id of mydomainname.com to 1 from the database, now mydomainname.com and example.com is swapping ..? How can I fix this? -
I created a user model myself, but I get an error in 'ChoiceField'. | PYTHON - DJANGO
When I try to register a user, I get the error "('favorite_music' is an invalid keyword argument for this function)". Request Method: POST Request URL: http://localhost:8000/user/register/ Exception Type: TypeError Exception Value: 'favorite_music' is an invalid keyword argument for this function Traceback says, C:\Users\adilc\Desktop\DjangoMusic\Music\user\views.py in register registeredUser = User(username = username, email = email,favorite_music = favorite_music) forms.py class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = MyUser fields = ('full_name','username','email') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = MyUser fields = ('full_name','email', 'password', 'active', 'admin') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather … -
How to redirect a page using Session ID
I am displaying qr code on a page and save the session id regarding qr code to authenticate the user.Once the user scan the qr code, the scanner app send response by using callback URI. I have received the response for specific user now how I can redirect the user using Session ID. Thanks -
How to fix a false permanent redirect [on hold]
I have used the following code in my project/urls.py but I don't want the change after restarting my project or computer. How can I fix it? I learned it would be difficult. Please explain for a beginner. from django.views.generic import RedirectView urlpatterns += [ path('', RedirectView.as_view(url='/app1/', permanent=True)), ] -
Cannot return null for non-nullable fiel error with graphene form mutations
I'm trying an example of graphene-django with forms. But I get next error: `graphql.error.base.GraphQLError: Cannot return null for non-nullable field [MyMutationPayload.name]. I'd tried set values in return expression inside perform_mutate function. It does not work if request does not perform all variations. class MyForm(forms.Form): name = forms.CharField(min_length=10) age = forms.IntegerField(min_value=0) birth_date = forms.DateField() class MyMutation(DjangoFormMutation): class Meta: form_class = MyForm @classmethod def perform_mutate(cls, form, info): print('ok') return cls(errors=[], name=form.cleaned_data.get('name'), age=form.cleaned_data.get('age'), birth_date=form.cleaned_data.get('birth_date')) class Mutations(): my_mutation = MyMutation.Field() class Mutation(Mutations, ObjectType): pass ROOT_SCHEMA = Schema(mutation=Mutation) Query mutation customMutation($data: MyMutationInput!){ myMutation(input: $data){ name age birthDate errors{ field messages } clientMutationId } } Variables { "data": { "name": "Cristhiam", "age": "-29", "birthDate": "1990-04-06" } } Response { "errors": [ { "message": "Cannot return null for non-nullable field MyMutationPayload.name.", "locations": [ { "line": 3, "column": 5 } ], "path": [ "myMutation", "name" ] } ], "data": { "myMutation": null } } Mutation result should show all errors or all form values. -
How to save queryset in models from template data by logged in user?
In models: class Match(models.Model): user = models.ManyToManyField(User, blank=True) match_name = models.CharField(max_length=20, help_text='Enter the name of 2 team using vs (eg. ban vs ind)') first_team = models.ForeignKey('FirstTeam', on_delete=models.SET_NULL, null=True) second_team = models.ForeignKey('SecondTeam', on_delete=models.SET_NULL, null=True) tournament_name = models.ForeignKey('TournamentName', on_delete=models.SET_NULL, null=True) match_created = models.DateTimeField(auto_now_add=True) match_stated = models.DateTimeField(default=timezone.now()) In views: def league(request, pk): match = Match.objects.all() context = { 'match': match, } return render(request, 'main/league.html', context=context) In templates: {% for match in match %} <div class="row text-center py-2"> <div class="col-3"> <img src="{{ match.first_team.flag.url }}" alt="image" class="team-image"> <h6>{{ match.first_team.name }}</h6> </div> <div class="col-6" style="font-size: 14px;"> <p>{{ match.tournament_name }}</p> <div>Starts On: <div style="color: red;">{{ match.match_stated|date:"d F, Y. h:i A" }}</div></div> </div> <div class="col-3"> <img src="{{ match.second_team.flag.url }}" alt="image" class="team-image"> <h6>{{ match.second_team.name }}</h6> </div> </div> {% endfor %} In my admin site, I add many data for my models without user fields and i show that queryset in my templates. This is working properly. Now, i need to save queryset for logged-in user from the templates. In template when users select my build in queryset then the queryset will save in the models with the user who select it. Every user can select the different different data from templates and the data will store in a new … -
Django projects directory permission error on Azure
I am trying to host a Django web project on Azure. I am able to publish it and create a resource for it to read from in the deployment center through a git repository, and it syncs successfully. However when I try to access the actual page I get: "You do not have permission to view this directory or page". I checked the detailed diagnostics and it comes up as 403 and 404 errors I tried uploading a default Django web project and that didn't work either. Tried higher pricing tier (non-free) also didn't work, making project on git public also failed. Below is the detailed diagnostics message from Azure. HTTP 4XX requests detected 404 Directory listing denied. The Web server is configured to not list the contents of this directory. This error typically comes if you do not have the default document configured and the request has come to the root of the site. The default document is the web page that is displayed at the root URL for a website. The first matching file in the list is used. Web apps might use modules that route based on URL, rather than serving static content, in which case there … -
Django/Django REST Framework - Internal API displaying results fetched from external API with filtering
So hey guys currently I'm trying to create an API endpoint that calls an external API via url with some filtering by comma separated strings. I'm used to creating internal APIs with models and views that call from it's own local sqlite database. But I'm less familiar with this. For instance I'm trying to have it so when I open my django devserver for this endpoint say called 'api/data/' it gets the JSON response from say 'www.example.com/api/data?tags=beef,chicken' and displays it. I was thinking about something like the code but wasn't sure how to apply filtering to it without accessing the queryset. import requests from rest_framework import status from rest_framework.response import Response def external_api_view(request): if request.method == "GET": r = requests.get("https://example.com/api/data/") -
Django wsgi server bjoern multithreaded
i would like to use bjoern wsgi server, currently this is working fine but i want to get it multithreaded so that i can access my application localy on multiple ports not only on port 8080 but also und 8081, 8082 etc... currently i do the following at my run.py file which starts the django app: import bjoern from app.wsgi import application bjoern.run(application, 'localhost', 8080, reuse_port=True) how can i spawn multiple processes of run.py on diffrent ports? Or in general how can i use multithreading at this point? The documentation seems quite complicated to me or at least i dont know where to start, https://docs.python.org/3/library/threading.html. Thanks in advance -
How I can store hashed access tokens in the database?
I use django-oauth-toolkit in my application. I noticed that the tokens are stored in the database in raw(unhashed) form. I think it is not secure. I was looking in the documentation and did not find a way to store hashes instead of tokens in db. Did I miss something, or does it really work like that? How can I fix this for my application? -
App works with ModelChoiceField but does not work with ModelMultipleChoiceField
I am trying to retrieve user input data in a django page. But I am unable to choose to multichoice field. I have tried multiple alternatives to no relief. self.fields['site'].queryset=forms.ModelMultipleChoiceField(queryset=sites.objects.all()) self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id)) self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)]) forms.py class SearchForm(forms.Form): class Meta: model= images fields=['site'] def __init__(self,*args,**kwargs): project_id = kwargs.pop("project_id") # client is the parameter passed from views.py super(SearchForm, self).__init__(*args,**kwargs) self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id)) views.py def site_list(request, project_id): form = SearchForm(project_id=project_id) site_list = sites.objects.filter(project__pk=project_id).annotate(num_images=Count('images')) template = loader.get_template('uvdata/sites.html') if request.method == "POST": image_list=[] form=SearchForm(request.POST,project_id=project_id) #form=SearchForm(request.POST) #site_name=request.POST.get('site') if form.is_valid(): site_name=form.cleaned_data.get('site') print(site_name) I expect to get a multiselect field but I end up getting this error: Exception Value: 'site' Exception Location: /home/clyde/Downloads/new/automatic_annotator_tool/django_app/search/forms.py in init, line 18 (line 18:self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)])) -
Being a superuser of my Django project, How can l see inventory of other user?
In the Django project, users have their inventory and see only their own inventory when logged in, which is displayed on page via views. If I want to create a dashboard where I can choose any users and see their inventory on a page. I should not need to log in with the user's credentials to see their inventory. -
Can't create user with custom user model and hash password DJANGO
I created a custom user model for my users in django and I'm using django rest framework and Jwt along with angular as my frontend. It was working fine while I was using superuser to login, but now that I've created new users I can't login with them, only with superuser. The main problema that I noticed is that the password wasn't being hashed, so the question is, How can I hash the password when I create an user posting the User from Angular?? is it right the way I'm doing it? Cause I see plenty diferente ways to do it, I'm kind of lost to be honest. Thank you models.py class User(AbstractUser): email = models.EmailField(unique=True) username = models.CharField(blank=True,null=True,max_length=30) is_candidate = models.BooleanField(default=False) is_employer = models.BooleanField(default=False) skype_id = models.CharField(max_length=50, blank=True) last_modified = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) created = models.DateTimeField(auto_now_add=True, auto_now=False, null=True) email_confirmed = models.BooleanField(default=False) user_cpf = models.CharField(max_length=14, blank=True,verbose_name='cpf') company_name = models.CharField(max_length=50, blank=True) user_data_waiver = models.BooleanField(default=True) user_receive_emails = models.BooleanField(default=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' views.py class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() core/urls.py router.register('user', UserViewSet, base_name='user') qualify/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('select2/', … -
Download Button Redirecting to Wrong Page
In my Django project, a user submits an Elasticsearch query into a form and it returns a downloadable report generated from that query. We've made some changes, and now I'm trying to get the portion that returns the report working again. However, I'm running into an issue with my url pattern that should call on the view function to download the report. I have a Download Report button that appears once the report is done being generated (checked by an Ajax request). The idea is that a user will click the button, and the report will appear in their downloads folder. But, when I click the button it sends me to /report/return_doc/ instead of /return_doc/. The logic of sending the user to /return_doc/ is that it's associated with the return_doc function in my views, but can I trigger this function and download the report to the user without refreshing the page/sending them to a new url? Or do I need to do something entirely different to make this button functional? error message Page not found (404) Request Method: GET Request URL: http://0.0.0.0:0001/report/return_doc/ Using the URLconf defined in icm_audit_tool_app.urls, Django tried these URL patterns, in this order: admin/ accounts/ form/ report/ …