Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unable to modify a row in SQL Server with multiple primary keys
I am using Django 3.0, DjangoRestFramework 3.12 and django-mssql-backend 2.8.1 to build a webapp version of a current desktop app that stores everything in a legacy MS SQL Server database. Due to this I am limited to database modifications that don't alter the table structure already in place. I built my Django models using the built-in legacy database model-generator and then made final modifications on my own. I've been following tutorials to build an API to handle data and everyone seems to recommend using DRF. All of my views use ListAPIView, RetrieveAPIView, and RetrieveUpdateAPIView. Now, when I try to build part of the API to allow me to alter settings in one of the tables, I'm running into an error about inserting a duplicate key value. Database Table: dbo.systemDateTimeSettings - LocationID (PK, FK, int, not null) - Setting (PK, nvarchar(50), not null) - Value (datetime, null) Model: class SystemDatetimeSettings(models.Model): location_id = models.OneToOneField(Locations, models.DO_NOTHING, db_column='LocationID', primary_key=True) setting = models.CharField(db_column='Setting', max_length=50) value = models.DateTimeField(db_column='Value', blank=True, null=True) def get_api_url(self, request=None): return reverse("api:datetime-settings-update", kwargs={ 'location_id': int(self.location_id.location_id), 'setting': self.setting }, request=request) class Meta: managed = False db_table = 'SystemDateTimeSettings' unique_together = (('location_id', 'setting'),) Serializer: class SystemDatetimeSettingsSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField(read_only=True) class Meta: model = SystemDatetimeSettings fields … -
JavaScript automatically sorts dict? [duplicate]
So, the problem is that when ajax script receives dictionary from server it gains different order: Server sent this: {753: 'Wraith', 752: 'Phantom Extended', 751: 'Phantom', 750: 'Ghost Extended', 749: 'Ghost', 748: 'Dawn', 747: 'Cullinan', 746: 'Black Badge'} But client gets this: {746: "Black Badge", 747: "Cullinan", 748: "Dawn", 749: "Ghost", 750: "Ghost Extended", 751: "Phantom", 752: "Phantom Extended", 753: "Wraith"} Js: $.ajax({ method: 'GET', url: request_url, success: function(data){ console.log(data.response_models); ... Also, the server is running on Django Please help! I really appreciate it -
How to pass queryset from one view to another in Django
I have searched for this but none of the solutions seem to work especially sessions. I have a queryset and i have appended it to a list of tuples such that it looks like this: [(a,b,c),(d,e,f), ...] I want to pass that to another view. How do I achieve this? Here is a code snippet: views.py def view1(request): job_details.append((job, recruiter, salary)) def view2(request): #I want to access the queryset(job_details) here -
How to send selected dropdown value from Django template to a Python file?
I'm trying to have the user select a value from a dropdown menu and then send that to another file to process it. I got the dropdown from bulma, and I'm having issues understanding how to send data from a template to another file in my Django project. This is what the dropdown looks like in my Django template: {% block drop-down-button %} <div class="dropdown is-active" style="margin-bottom:10px"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>AWS Accounts</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> 558232680640 </a> <a class="dropdown-item"> 903500686888 </a> <a href="#" class="dropdown-item"> 183070076065 </a> <a href="#" class="dropdown-item"> 885703380506 </a> <hr class="dropdown-divider"> <a href="#" class="dropdown-item"> All Accounts </a> </div> </div> </div> {% endblock %} Thank you all! -
cannot import name 'execute_from_command_line' from 'django.core'. Is it deprecated?
I can no longer run my Django website locally because Django seems to be missing: (tod_env) C:\Users\antoi\Documents\Programming\Projects\todowoo\webapp>python manage.py runserver Traceback (most recent call last): File "C:\Users\antoi\Documents\Programming\Projects\todowoo\webapp\manage.py", line 11, in main from django.core import execute_from_command_line ImportError: cannot import name 'execute_from_command_line' from 'django.core' (C:\Users\antoi\Documents\Programming\Projects\todowoo\tod_env\lib\site-packages\django\core\__init__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\antoi\Documents\Programming\Projects\todowoo\webapp\manage.py", line 22, in <module> main() File "C:\Users\antoi\Documents\Programming\Projects\todowoo\webapp\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? While Django is in the environment: (tod_env) C:\Users\antoi\Documents\Programming\Projects\todowoo\webapp>pip3 list Package Version --------------- ------- asgiref 3.3.4 Django 3.2 I guess its a version problem? -
Suggestions for an implementation in Django
I have a blog created on django and I need to configure the access using iptables. I do not have any idea how to do it, anybody can indicate some material? I was thinking about creating a function where it is possible to pass a range of ip numbers that are allowed to access, but I don't exactly where to do that in django. -
Cors in Django and ReactJs
I have some trouble with CORS when using Django(3.2) for BE and ReactJs for FE: Here my config, I using django-cors-headers lib for this config. At my setting file: INSTALLED_APPS = [ 'webapi.apps.WebapiConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders'] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] CORS_ORIGIN_ALLOW_ALL = True About my request in React, I use Fetch(): var headers = { "Content-Type": "application/json", "Token": "...", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "*", } fetch('http://127.0.0.1:8000/api/posts', { method: 'POST', headers: headers, body: JSON.stringify(data), }).then(s =>{ if (s.status === 200) { console.log("Success"); } else { console.log("Error"); } }) and error message I got is: "Access to fetch at 'http://127.0.0.1:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response." Thanks for helping me. -
How to convert blob data sent from javascript to Django server for Speech Recognition module
I want to record some audio on the client side using Javascript and send it to my Django Server Here is my js code for recording and sending the data to the server. function start_recording(){ navigator.mediaDevices.getUserMedia({ audio: true }) .then(stream => { const mediaRecorder = new MediaRecorder(stream); console.log(mediaRecorder) mediaRecorder.start(); const audioChunks = []; mediaRecorder.addEventListener("dataavailable", event => { audioChunks.push(event.data); }); mediaRecorder.addEventListener("stop", () => { console.log("stop is called") const audioBlob = new Blob(audioChunks); }); // var stop_button =document.getElementById('stop_button'); stop_button.addEventListener('click',function(){ console.log(mediaRecorder,'stopped') mediaRecorder.stop() }) }); } function GetAudio(audioBlob){ console.log('>>>>>>>>get audioblob',audioBlob) const audioUrl = URL.createObjectURL(audioBlob); var form = new FormData(); form.append('audio', audioBlob); //console.log(wavfromblob) let csrftoken = getCookie('csrftoken'); // var audio_base64; $.ajax({ url:"/get_sound/", headers: {'X-CSRFToken':csrftoken}, type:'POST', processData:false, contentType:false, //contentType:'application/json; charset=UTF-8', data:form, //data:JSON.stringify({'hello':'hi','audio_base_64':audio_base64}), error: function (request, status, error) { alert(error); } }).done(function(response){ if(response=="true"){ console.log("true"); alert("data sent") }else{ console.log("false"); alert("data was not recieved") } here is my function code from views.py def get_sound(request): print("get sound was called") if request.method == 'POST': print(request.FILES) audio_blob= request.FILES['audio'] file_obj=io.BytesIO() file_obj.write(audio_blob.read()) file_obj.seek(0) print(file_obj) recognizer = sr.Recognizer() with sr.AudioFile(file_obj) as source: print("loading") recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) #print("Recording for 4 seconds") #recorded_audio = recognizer.listen(source, timeout=4) print("Done recording") # ''' Recorgnizing the Audio ''' try: print("Recognizing the text") text = recognizer.recognize_google( audio, language="en-US" ) print("Decoded Text … -
How to register a ContentType object Model in Django admin and access Models (view and edit) through it?
I have a Content type model named SeoList which is generically related to Question Model in a different app. i have already connected the models and whenever a question is created a new object of SeoList is created (used signals), Problem: I want to view and have edit access to the Question model through SeoList admin this is the view of SeoList model admin I need to know ,if i click on one of these object can it be redirected to the corresponding Quesion. Is there any magical way to acheive this ? Also, is there a way to display the value insted of the object queryset inthe SeoList model admin. Thanks in advance -
How to implement a graphene-django pagination feature for previous and next?
Currently we implemented our pagination, similar to https://www.howtographql.com/graphql-python/8-pagination/: # Use them to slice the Django queryset def resolve_links(self, info, search=None, first=None, skip=None, **kwargs): qs = Link.objects.all() if search: filter = ( Q(url__icontains=search) | Q(description__icontains=search) ) qs = qs.filter(filter) if skip: qs = qs[skip:] if first: qs = qs[:first] return qs I wonder if I can still extend this to add a feature like prev/next? Or the only way is to use Relay? -
Best cache solution for django e-commerce website?
I develop a django application for our company. it's an e-commerce website. What is best cache solution for this project? Redis? Memcached? Nginx Cache? Django Cache? Gunicoin cache? Thanks! -
How to show django messages based on queryset filter?
I want to show message based on my filter. CHOICES = ( ('0', 'published',), ('1', 'pending',), ('2', 'rejected',), ) Here I tried this code for showing message based on filter but it’s only showing the published message. def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) published = BlogComment.objects.filter(is_published="0") pending = BlogComment.objects.filter(is_published="1") if published: messages.add_message(self.request, messages.INFO, 'Comment status published Sucessfully') elif pending: messages.add_message(self.request, messages.INFO, 'Comment status pending Sucessfully') return data why I am only getting the published message? -
Is it possible to allow all custom permissions to superuser?
Here my_custom_user inside test_func is the user that will required permission for the View but I want to give superusers all the custom permissions I have by default like the django model permissions does. Is it possible instead of checking superuser inside all the test_func(I have many permission)? class MyCustomPermission(UserPassesTestMixin): def test_func(self): my_custom = # here I have some logic to filter my custom_user return self.request.user.is_superuser or my_custom_user class MyView(MyCustomPermission, CreateView): pass -
How to customize flatpages to use with django-oscar get_model
Unfortunately, after countless attempts, I haven't found any promising way to solution. I'm searching for the least intrusive way to customize the flatpages used by django-oscar's 'dashboard.pages' app. It would be ok to break the migration history of the django app and manage them manually. Is it possible to solve it using the get_model loader from oscar and how? (I don't need a full solution and am thankful for every hint) Additional information: My intention is to create a FlatPageCategory model from oscar.core.utils import slugify class FlatPageCategory(models.Model): name = models.CharField(max_length=255, db_index=True) url = models.SlugField() and add a few fields to FlatPage model from django.contrib.flatpages.models import FlatPage class FlatPage(FlatPage): display_order = models.SmallIntegerField( default=0, ) category = models.ForeignKey( 'FlatPageCategory', on_delete=models.SET_NULL, blank=True, null=True, ) attachments = models.ManyToManyField( File, ) def get_absolute_url(self): """ Prepend category url if category exists. """ url = super().get_absolute_url() if self.category: return f'{self.category.url}/{url}' return url -
Python: Validate Regex, find a match inside string
We have an invoice numbering rule, which we would like to modify a bit. Inside user settings, there's a setting that sets the user invoice numbering format, we can let the user to change there anything he wants, but we have an invoice creation page, inside the page what we only want to allow is to let the user to change the number to a bit higher. For example: Inside settings the rule is set to CN-002/2021. Inside the invoice creation page the user tries to change the rule to CN-001/2021, in this case we will throw an error because we won't like to allow this. If the user tries to change the rule to CN-003/2021, we allow it. NOTE: The user can't change anything else, for example, CZ-003/2021 or CN-001/2022. Check if the number has changed: if old_invoice_no != new_invoice_no Find which number has changed, for example, the old number was CN-001/2021 and the new number is CN-002/2021. For this case, we will pass, because we only allow the number to be HIGHER and never LOWER. If the new number is CN-000/2021 we will throw an error, because the number is lower. How can I check if the number … -
error while registering a .txt file on admin in django
I am trying to register a log file(.txt) file but getting an error. the model is below- class LogRegister(models.Model): class Meta: managed = False and code for registering on admin is- from logs.models import LogRegister @admin.register(LogRegister) class JsonDataAdmin(admin.ModelAdmin): def logs_view(self, request, extra_context=None): text = BASE_DIR + 'logs/logs.txt' html = "<br>".join(text.split('\n')) context = dict( self.admin_site.each_context(request), html=html, ) return TemplateResponse(request, "logs.html", context) error is- Exception Type: TemplateDoesNotExist Exception Value: logs.html -
time registration in timegrid together with forms and formsset
In my team we are struggling with a project-time-registration inside Django We want to register time per day per project represented in a week on screen We want to create a grid with projects and monday until sunday as inputfields for the project Like this: For the registration ot the hours in the days of the week, we want to make use of a modelform and modelformset Our models look like this: from django.db import models class Project(models.Model): titel = models.Charfield(max_length=128) class = RegistratedTime(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) date = models.DateField() hours = models.DecimalField(max_digits=4, decimal_places=2) from django import forms class timeRegistrationUnit(forms.From): project = forms.IntegerField() date = forms.DateField() hours = form.DecimalField(decimal_places=2, max_digits=4, max_value=24) We tried many solutions, but none of these are working with a form and formset (we think). How to deal with the days without registration-records, how to make a connection between Project, RegistratedTime and the 7 days in the week and how to save the entered hours? But maybe we did not look good enough or we missing out something(?) Does anybody have an idea how to solve this problem, or have a better way to solve this puzzle? Thanks in advance -
How to use token on the Flutter?
I want my mobile application to have access to create a photo but when I send a request from a mobile application I get an error Unauthorized: /account/api/NFT/. I can register via the mobile application and logged after authorization goes to the photo download tab after filling out forms and sending a mistake. I checked through postman and everything worked well I think this due to the fact that my mobile application does not use the resulting token I have a backend on Django that uses simple JWT models.py class NFT(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False, verbose_name=('Unique ID')) title = models.CharField(max_length=100) image = models.ImageField(null=True, blank=True) price = models.DecimalField(default=1, max_digits=5, decimal_places=2) tags = models.CharField(null=True, max_length=100) owner = models.ForeignKey('auth.User', related_name='NFT', on_delete=models.CASCADE, default=None) api.py class RegisterApi(generics.GenericAPIView): permission_classes = [AllowAny] serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "message": "User Created Successfully. Now perform Login to get your token", }) authSerializer.py class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username','password', 'email', ) extra_kwargs = {'password':{'write_only': True},} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], password = validated_data['password'], email = validated_data['email'], # first_name = validated_data['first_name'], # last_name = validated_data['last_name'], ) return user settings.py REST_FRAMEWORK … -
How can I write a Python program where a bunch of students will be assigned thesis themes using the FIFO method?
each of the students will enter a site and they will classify their choices and the first one who chooses that subject will get it depending on who has enterd the site first and choose the subject -
Rsyslog dropping large messages
I am using rsyslog to forward logs from a docker container to splunk. The docker container runs django which is configured to write all of our application logs to syslog. After a couple of weirdities involving timestamps, everything works great ... except that large messages (approx 2K or above) are dropped (not even truncated). I tried to set the $MaxMessageSize to 64k in rsyslog.conf but it had no effect. If django could be configured to write logs to a TCP socket, or the $MaxMessageSize actually worked, I would be good to go. Any help is appreciated. rsyslogd 8.2001.0 Python 3.8.5 Django 3.1.2 Ubuntu 20.04.2 LTS -
Is there an approved method to completely remove an app?
I have an app which was misconceived, and I would now like to delete it completely. I cannot find anything in the Django documentation about the right "blessed" way to do this. I tried commenting out its models and running makemigrations but this threw errors because its views.py could not import them. If I removed its views from urls.py and tried, then makemigrations did not recognise that anything had changed. Is it as simple as removing it from installed_apps in settings.py, removing its code, and manually deleting its one small model table from the DB? Or will the fact that it had an admin.py mean that there are dangling references left somewhere? I'm using Django 2.2 if it makes any differerence -
What Auth system should we use for our Django project?
We are building a web and mobile app and we want to use a common Rest API to use for both reactjs and react-native, what authentication system should we use since we will need multi-device login/logout functionality and it has to be secure at the same time, please suggest. -
How do you perform get_or_create on DRF ModelViewSet when over riding create()?
I have a ModelViewSet with create() method overwritten as I may be creating more than one instance at a time. I was wondering if it is possible to perform a get_or_create instead of .perform_create() as seen below? Essentially if I make the same call twice I would only like the first call to create the instance/s. class CreateTokenView(viewsets.ModelViewSet): queryset = BayAccessToken.objects.all() serializer_class = accessTokenSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) -
Filefield in django Model, hide the link to file and clear box in template
I have a model Test with a filefield: class Test(models.Model): file = models.FileField(upload_to='file', blank=True, null=True) In the template i render it via the form: class TestForm(forms.ModelForm): class Meta: model = Test fields = '__All__' In the template i do: <td class="tg-0lax">{{ test.file }}</td> In the template its working fine, i gat the file upload possibility But this also shows the clickable link to the file in the template. I dont want that. So i want to render it buy without the link to the file (only the upload possibility) Is this possible -
Django Serializer How to loop over dictionary value and return in serializer
I have following dictionary inside list self.passengers = [{'first_name':'Harry','last_name':'kane'},{'first_name':'cristiano','last_name':'aviero'} I Have set my serializer as following class PassengerSerializer(serializers.Serializer): first_name = serializers.CharField() last_name = serializers.CharField() class TicketDetailSerializer(serializers.Serializer): passenger = PassengerDetailSerializer(many=True) I have set my code as following to extract passenger data 'passenger': [{ 'lastname': [passenger['lastname'] for passenger in self.passengers], 'firstname': [passenger['firstname'] for passenger in self.passengers] }], But I am only getting firstname ->'harry' and lastname-> kane what shall I do next to get all dictionary of first name and last name is self.passengers?