Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert Django bytes data to mp3 files
I have send audid/webm bytes from react to django. And the transfered data enter image description here the code in view.py is like this def get_audio(request): audio = BytesIO(request.body) print(audio.read()) print(type(audio.read())) # os.makedirs('./data/audio.wav', exist_ok=True) # with open('./data/audio.wav', mode='bx') as f: # f.write(audio.read()) return HttpResponse("audio delievered") the request in react is like this setTimeout(() => { setRec("Stopped") const tracks = stream.getTracks(); tracks[0].stop(); mediaRecorder.stop() // console.log(chunks[0]) blobAudio = chunks[0] }, 5000); const audioUpload = () => { const fd = new FormData(); fd.append("audio_5sec", blobAudio); try{ axios.post("/uploading_audio", fd, { headers:{ 'Content-Type' : 'multipart/form-data', }, }) .then((response) => { console.log(response); }) }catch(error){ console.log(error); } } now i want to convert audio.read() bytes to mp3 in django directory and write it. How can i do this? The above comment parts doesn't work -
Django rest_framework put method doesn't obtain HTTP_AUTHORIZATION
I'm having problems with Django Rest Framework. When I'm trying to send my JWT token from React with Axios, it sent nothing... The code works for POST and GET but in PUT ... -_- The settings : CORS_ALLOW_METHODS = ( "DELETE", "GET", "POST", "PUT", ) Axios call (The token is good, so i don't sending undefined, tested): try { console.log("Ejecutando caso Exitoso"); const response = await axios.put("http://localhost:8000/empresas/empresa-persona/" + param[1], { headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, 'Content-Type': 'application/json', }, }); console.log(response); } catch (error) { console.log(error); } Django function (the same function works in GET and POST , but in PUT, HTTP_AUTHORIZATION doesn't exist): def user_call_validation(request, perm): # Control de Acceso print(request.META) user = validate_user_token(token=request.META["HTTP_AUTHORIZATION"]) # print(User.objects.get(id=user["id"]).get_all_permissions()) if User.objects.get(id=user["id"]).has_perm(perm) != True: raise Exception("Acceso denegado!") -
Overriding DRF settings for tests
I'm using Python 3.9, Django 3.2, DRF 3.12.4. I'm adding JWT authentication method using simple JWT. To test my auth method, I need to set "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), I would like to avoid editing my settings file and keep all changes in my test file. That's because I have separate local and production settings, and local settings are using fake auth backend. All tests are passing when I set the above auth class in my local settings. I tried to use @override_settings: @override_settings( REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), } ) It seems to work fine - when I print the settings in my test: from django.conf import settings from rest_framework.settings import api_settings ... def setUp(self): print(settings.REST_FRAMEWORK) print(api_settings.DEFAULT_AUTHENTICATION_CLASSES) I get {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',)} [<class 'rest_framework_simplejwt.authentication.JWTAuthentication'>] However, tests aren't passing - I'm getting error from my fake auth backend, as if the settings aren't getting overriden after all. I also tried editing django.conf settings directly - which is something I would rather not do, but it didn't solve my problem as well. Am I doing something wrong? Maybe my solution/tests have some logical mistakes and I'm doing something I shouldn't do? Thank you in advance for all the help. -
How to apply the sklearn OneHotEncoder to a subset of rows in a Pandas Dataframe?
I have a pandas dataframe with numerical as well as categorical columns. For any input row (to keep things simple we take any row from the orginal dataframe), I want to find the N most similar rows to it. However, instead of comparing the input row against the entire dataset I want to use a subset of the dataframe. def find_similar_rows(dataset, query_df, input_row, top_n=10): # Identify common columns common_columns = list(set(dataset.columns) & set(input_row.index)) numeric_cols = dataset.select_dtypes(include=['int64', 'float64']).columns categorical_cols = dataset.select_dtypes(include=['object', 'category']).columns _, num_imputer, cat_imputer, scaler, encoder = preprocess(dataset.copy(), numeric_cols, categorical_cols) processed_query_df, _, _, _, _ = preprocess(query_df, numeric_cols, categorical_cols, num_imputer, cat_imputer, scaler, encoder) processed_input_row, _, _, _, _ = preprocess(pd.DataFrame([input_row[common_columns]]), numeric_cols, categorical_cols, num_imputer, cat_imputer, scaler, encoder) # Calculate cosine similarities cosine_similarities = cosine_similarity(processed_input_row, processed_query_df)[0] # Combine cosine similarity with DOMAIN_WEIGHTED_SUM and normalized RECHNUNGS_MENGE combined_scores = cosine_similarities + processed_query_df['DOMAIN_WEIGHTED_SUM'].values / 100 + processed_query_df['RECHNUNGS_MENGE'].values / RECHNUNGS_MENGE_NORMALIZATION_FACTOR # Get indices of top similar rows based on combined_scores top_indices = np.argsort(combined_scores)[::-1][:top_n] # Return both indices and scores return top_indices, combined_scores[top_indices] def preprocess(df, numeric_cols, categorical_cols, num_imputer=None, cat_imputer=None, scaler=None, encoder=None): # Check if the imputers and scaler are provided, if not, create new ones if num_imputer is None: num_imputer = SimpleImputer(strategy='mean') df[numeric_cols] = num_imputer.fit_transform(df[numeric_cols]) else: df[numeric_cols] … -
I encountered this error "UNIQUE constraint failed: accounts_user.username" while trying to register a user in my django project
I tried registering a user for the first time in Django but it was giving me this error IntegrityError at /register/ UNIQUE constraint failed: accounts_user.username Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 4.2.6 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: accounts_user.username Exception Location: C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: accounts.views.register Python Executable: C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\python.exe Python Version: 3.12.0 Python Path: ['C:\Users\Joseynice\Desktop\task_file', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\python312.zip', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\DLLs', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\Lib', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\Lib\site-packages'] Server time: Tue, 09 Jan 2024 14:21:19 +0000 I tried registering a user in Django see the error below` File "C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\Lib\site- packages\django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username [09/Jan/2024 15:25:43] "POST /register/ HTTP/1.1" 500 159087 #accounts.model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password1=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password1) user.save(using=self._db) return user def create_superuser(self, email, password1=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password1, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="email", max_length=60, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) username = models.CharField(max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
Cannot insert into a generataed always identity column in Django ModelForm
I have a table 'Orders' in Oracle database which have a column 'order_id' as primary key and is set to auto generate Ids. Then I have remaining columns like order_date, received_from ,quantity,delivery_date etc..Now I am using a ModelForm 'OrderForm' for adding new orders and updating if order accordingly. Now the problem is I am able to update the order table using orderform for a particular order using order_id, but when I try to add a new order, then it throw error saying cannot insert in to a generated always identity column. I understand that here that django is trying to insert a null value into auto generated column order_id. I actually want to just ignore 'order_id' field and insert other details to the table. I am new to django. Please help. Thanks. -
Custom form in the Django Admin: how to make it look the same as the Django's Admin forms?
I have Django application which handles license codes, so there's a model and a modeladmin, and that all works. But I want to add a custom page to the admin interface to generate a whole bunch of license codes and while everything is working, it looks really bad. So first of all to get a new button in the top right, I have a custom change_list.html template for this specific model: {% extends "admin/change_list.html" %} {% block object-tools-items %} {{ block.super }} <li><a href="generate/" class="addlink">Generate Codes</a></li> {% endblock %} This makes the extra button show up: Clicking on that button opens a new page, which I created with this code: @admin.register(RedeemCode) class RedeemCodeAdmin(admin.ModelAdmin): # [...the usual admin config...] def get_urls(self): return [ path("generate/", self.admin_site.admin_view(self.generate_codes), name="generate-codes"), ] + super().get_urls() def generate_codes(self, request): class GenerateCodeForm(forms.Form): product = forms.ModelChoiceField(queryset=ProductVariant.objects.all()) partner = forms.ModelChoiceField(queryset=Partner.objects.all()) comment = forms.CharField() count = forms.IntegerField(min_value=1, initial=1) for_email = forms.CharField() export_csv = forms.BooleanField(required=False, label="Export generated codes to CSV") if request.method == "POST": form = GenerateCodeForm(request.POST) if form.is_valid(): print(form.cleaned_data) return HttpResponseRedirect("/admin/shop/redeemcode/") context = dict( # Include common variables for rendering the admin template. self.admin_site.each_context(request), opts=RedeemCode._meta, title="Generate Codes", form=GenerateCodeForm(), ) return TemplateResponse(request, "admin/shop/redeemcode/generate_codes.html", context) And my generate_codes.html template: {% extends "admin/base_site.html" %} {% … -
how to create django rest asynchronous APIView
I have an ecommerce website developed using django rest framework version 3.14. In some days of month, we have a huge traffic of users trying to order. As the number of requests in some specific times are so big, a few of them will fail. I think one solution is to use asynchronous APIs in backend. The views in django back are class based APIView. And I can not figure out how should I change the simple APIViews to Async views. I also don't need to change all views, but 2 views that are handling purchase process. In these 2 views, I have post and get methods, and some other methods that handle ORM calls (filter, get, all, etc.) Any solution? -
Skipping of tests in pytest using the command line
I've tried to skip tests in pytest according to this: https://docs.pytest.org/en/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option When I try to run the tests using only the command pytest, the marked tests are skipped as intended. But when I run the tests with pytest --runslow I get the following error: ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --runslow inifile: /app/pyproject.toml rootdir: /app My tests are in project/myapp/tests/tests.py and the conftest file in project/conftest.py. How can I make pytest recognized my command line argument? -
I am trying to import views.py to urls.py using from . import views but I keep getting an import erroe
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path("", views.home), path("predict/", views.predict), path("predict/result", views.result) I expected to run urls.py successfully -
I want 1st field to be not equal to 2nd field (both fields are foreign key to same model)
I am trying to raise validation error when my 'reference' field is same as 'contact', but def clean won't work. Here is my code: class FacultyRegistration(models.Model): role = models.ForeignKey(Roles, on_delete=models.CASCADE, null=True, verbose_name="Faculty Role") contact = models.OneToOneField('Contacts.Contact', related_name='faculty_Contact', unique=True, on_delete=models.CASCADE) reference = models.ForeignKey('Contacts.Contact', on_delete=models.CASCADE, related_name='faculty_reference',) # I tried def clean but it wont work def clean(self): if self.contact == self.reference: raise ValidationError('Primary and secondary inclinations should be different.') def __str__(self): return f"{self.contact} ({self.role})" class Meta: verbose_name = "Faculty Management" verbose_name_plural = "Faculty Managements" -
CSS styling not applying to Dockerized Django project
I created a django project, life was good. However when I dockerized it everything else works fine apart from the css styling. Below is my dockerfile, let me know any other information I can provide FROM python:3.8 WORKDIR /app COPY . /app RUN pip install -r requirements.txt EXPOSE 8000 ENV NAME World RUN python manage.py collectstatic --noinput CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I feel like ive tried everything but nothing will make these pesky css files appear in my image -
No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context
I have an appengine app that works with python2.7 and I want to migrate to python3.9. I started by making call to google ndb cloud inside my appengine app. I am using python3.9 and django as a web framwork. This is my code: from django.shortcuts import render,redirect from google.cloud import ndb class Book(ndb.Model): title = ndb.StringProperty() client = ndb.Client() def get_books(): with client.context(): books = Book.query() return books def main(request): return HttpResponse(get_books()) And this is the traceback File "/Users/hizan/Desktop/venvdjango/lib/python3.9/site-packages/google/cloud/ndb/query.py" in wrapper 1213. context = context_module.get_context() File "/Users/hizan/Desktop/venvdjango/lib/python3.9/site-packages/google/cloud/ndb/context.py" in get_context 118. raise exceptions.ContextError() Exception Type: ContextError at / Exception Value: No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context. -
Django : How to fill Charfield with the button value
I'm building a simple python webapp that stacks 2 tables. First the columns of both tables are listed as buttons on top of the page (lets call it column buttons). Next we have input field row (with 2 inputs), Input 1 --> The columns to be stacked, separated by commas. Input 2 --> The column name of the Output table. i.e each row represents a column-combination. I'm good until here. Challenge: I want to auto-fill Input 1 (with the column names) while I click the respective column buttons. Instead of typing it manually I'm unable to find the options in Django to achieve this yet. Many thanks in advance -
401 Unauthorized when authenticating with token in Django
I'm working on a Django project where users are required to verify their phone number on their first login. Once their phone number is verified, a token is assigned to them. However, when I try to authenticate with the token in my tests, I get a 401 unauthorized error. Does anyone know where the problem might be? r = client.patch("/user/", data= dict(pk=1), format='json', headers= dict(Authorization=f"Token {user.auth_token.key}")) assert r.status_code == 200 -
Why is my hx-trigger not triggered using from: <css selector>?
I have a button that I want to send two requests to the server when clicking. The setup is like this: <button id="add-item" hx-get="some-url" hx-trigger="click" hx-target="#item-form" hx-swap="beforeend" type="button">Add item</button> <br> <div hx-get="some-other-url" hx-trigger="from: #add-item" hx-swap="beforeend"> </div> I have tried using hx-trigger="click from: #add-item but that does not work either. The first request sent by add-item is fetched from the server correctly, but the second one from the div is never sent at all. When changing the trigger for the div to something like hx-trigger="click", it works (also needing some content inside it to click). Is there soemthing wrong with the syntax or why would this not work? I have imported HTMX like so: <script src="https://unpkg.com/htmx.org@1.9.10" integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC" crossorigin="anonymous"></script> Any help would be appreciated. -
Django verification email
I have a Django app deployed on Pythonanywhere. Everything works as expected except for the verification emails.When a new user registers, he should receive a verification email, but Django doesn't send it until the admin panel is reloaded. All other emails(welcome emails, contact form emails) are sent without issue. When I test locally on my laptop verification emails are sent instantly. I am using django-email-verification and emails are sent through gmail. views.py class RegisterView(CreateView): form_class = RegisterForm template_name = 'common/register.html' success_url = reverse_lazy('login') def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') return super().dispatch(request, *args, **kwargs) def form_valid(self, form): form.save(commit=False) user_email = form.cleaned_data['email'] user_username = form.cleaned_data['username'] user_password = form.cleaned_data['password1'] user = UserModel.objects.create_user(username=user_username, email=user_email, password=user_password) user.is_active = False send_email(user) return HttpResponseRedirect(reverse('email sent')) def form_invalid(self, form): return super().form_invalid(form) -
Django admin: group two fields in a section without having to specify every other field as well?
I have a Django model with a whole bunch of fields. In the Admin UI I want to group two of these fields in their own little section, but as far as I know that means I now have to specify every single model field in the fieldsets config: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): fieldsets = ( ( None, { "fields": ("field_1", "field_2", "field_3") # etc etc } ), ( "My special section", { "fields": ("field_11", "field_12") } ) ) It's annoying to copy and paste so many field names, but worse: if I add a new field to the model I have to remember to add it to the fieldsets config as well. So my question is: is there no way to have some kind of "the rest of the fields go here" section? Or another way to only change the section of a subset of fields while leaving the rest alone? -
i am trying to run manage.py runserver on pycharm and an attribute error is returned
File "C:\Users\user\PycharmProjects\Diabetes Prediction\Diabetes_prediction\Diabetes_Prediction\urls.py", line 23, in path("", views.home), ^^^^^^^^^^ AttributeError: module 'Diabetes_Prediction.views' has no attribute 'home' I expected the project to run -
How to get Page no of pdf and assign to a table in ReportLab, Python
I'm working on a PDF generation script using ReportLab in Python. The script generates a PDF with a client table and some additional information. I have implemented a custom PageNumCanvas class to handle page numbering.(PageNumCanvas is from https://www.blog.pythonlibrary.org/2013/08/12/reportlab-how-to-add-page-numbers/) this is the PageNumCanvas. I override(in save method) the first page to add the page no on a fixed location. But i need to load the page_count dynamically, in the client table. class PageNumCanvas(canvas.Canvas): """ http://code.activestate.com/recipes/546511-page-x-of-y-with-reportlab/ http://code.activestate.com/recipes/576832/ This below code is taken from the https://www.blog.pythonlibrary.org/2013/08/12/reportlab-how-to-add-page-numbers/ """ #---------------------------------------------------------------------- def __init__(self, *args, **kwargs): """Constructor""" canvas.Canvas.__init__(self, *args, **kwargs) self.pages = [] #---------------------------------------------------------------------- def showPage(self): """ On a page break, add information to the list """ self.pages.append(dict(self.__dict__)) self._startPage() #---------------------------------------------------------------------- def save(self): """ Add the page number to each page (page x of y) """ page_count = len(self.pages) self.__dict__.update(self.pages[0]) self.setFont("Helvetica", 9) self.drawRightString(270, 679, str(page_count)) for page in self.pages: self.__dict__.update(page) self.draw_page_number(page_count) canvas.Canvas.showPage(self) canvas.Canvas.save(self) #---------------------------------------------------------------------- def draw_page_number(self, page_count): """ Add the page number """ page = "Page %s of %s" % (self._pageNumber, page_count) self.setFont("Helvetica", 9) self.drawRightString(200*mm, 20*mm, page) class YourPdfClass: def __init__(self): pass def header(self, canvas, doc): pass def write_pdf_lines(self, columns_fields, file_path): pdf_filename = file_path pdf_document = SimpleDocTemplate(pdf_filename, pagesize=letter ) # Calculate the available width within the margins available_width … -
How to add value into a form before saving in Django
I want the user to fill some form, then add the user's id and user's branch(from another table, by releation) to add to the form data before saving it. the form has other fields like {type, serialno, model, date}, after it is submitted i want to add userid and branchid to that form value and submit it to database This is my view.py enter image description here I tried to overide the form data as you can see in the picture. But, it keeps showing me an error message of "TypeError" -
Incorporating Slack-bolt django example in my app
I have incorporated slack-bolt Django example in my Django project. I can successfully install the app using /slack/install. However, I have challenges with customisation. My app is initialised as in the django example app = App( signing_secret=signing_secret, oauth_settings=OAuthSettings( client_id=client_id, client_secret=client_secret, scopes=scopes, user_scopes=user_scopes, # If you want to test token rotation, enabling the following line will make it easy # token_rotation_expiration_minutes=1000000, installation_store=DjangoInstallationStore( client_id=client_id, logger=logger, ), state_store=DjangoOAuthStateStore( expiration_seconds=120, logger=logger, ), ), ) Challenge 1: I would like the installation flow to be triggered from the /profile page of my app. I generated the Slack install button and placed it inside of my app /profile page. Please note that the profile page is available to the user after authentication to the django project. When the user gets redirected, the Slack page shows up, user clicks Allow and is redirected back to the /slack/oauth_redirect The error shows up with information that Slack installation was triggered from a different URL than /slack/install. I tried to set the installation_url in my app as follows app.oauth_flow.install_path = '/profile' app.oauth_flow.settings.install_path = '/profile' but it didn't work The only way I could make it work was to disable the state validation app.oauth_flow.settings.state_validation_enabled = False Question 1: How do I … -
Issues while using related names
This is the Course and LearnerCourse model: class Course(BaseModel, Timestamps, SoftDelete): name = models.TextField(_("Course Name"), max_length=100, blank=True, null=True, unique=False) description = models.TextField( _("Course Description"), blank=True, null=True) course_number = models.CharField( max_length=15, null=True, blank=True, unique=True).... class LearnerCourse(BaseModel, Timestamps, SoftDelete): course = models.ForeignKey(Course, verbose_name=_("Course"), on_delete=models.CASCADE, db_index=True, related_name='course_learner_courses') learner = models.ForeignKey(Learner, verbose_name=_("Learner Course"), on_delete=models.CASCADE, db_index=True) course_subscription = models.ForeignKey(CourseSubscription, null=True, on_delete=models.CASCADE, db_index=True) enroll_date = models.DateTimeField(verbose_name=_("Course Enroll Date")) is_favourite = models.BooleanField(default=False) in LearnerCourse used the related name for the course field, after that When used like this details = LearnerCourse.objects.filter(learner=learner_id).all().order_by('-datetime_created') print("details", details) courses = details.course_learner_courses.all() print("courses", courses) which causes an error 'SafeDeleteQueryset' object has no attribute 'course_learner_courses' Please give me some suggestions to fix this problem. -
Tried to live the server using ngrok but ending up getting error
i have created a django crud application website and i want to live it using ngrok server once i tried to login using the link the ngrok given im getting this error [09/Jan/2024 13:21:36] "GET /static/img/login.png HTTP/1.1" 200 1543188 Forbidden (Origin checking failed - https://4407-2001-d08-2901-3214-a5a4-7e36-5645-47c1.ngrok-free.app does not match any trusted origins.): /login/ , i have put the link on allowed host and CORS_ALLOWED_ORIGINS as well. -
TypeError: RocCurveDisplay.__init__() takes 1 positional argument but 4 were given [closed]
from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report, roc_curve, RocCurveDisplay print('----- confusion matrix ------') print(confusion_matrix(y_test, y_pred_nb)) print('----- classification report -----') print(classification_report(y_test, y_pred_nb)) RocCurveDisplay(nb, X_test, y_test) TypeError: RocCurveDisplay.__init__() takes 1 positional argument but 4 were given how to fix this error? i use sklearn 1.2