Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Returning django form as json response?
Hello I'm new in django. Is there any way to return django form as a json response? I want to use this response in js to paste it to my html template. Any hint? -
404 page not found in django localhost when try to click on image url
I created menu objects from Django default admin panel on which one of the fields is an image. I have successfully uploaded the image as well. But in the response api, if I clicked on image url, it says 404 not found. The api response is like this. Both image_url and image are 404 not found. I added image_url just to see if it works, but it didn't work as well. My model: class Menus(models.Model): category = models.CharField(max_length=50,choices=CATEGORY,default='main courses') food_name = models.CharField(max_length=100,blank=True, null=True) image = models.ImageField(blank=True,null=True) rating = models.FloatField(blank=True, null=True) description = RichTextField(blank=True, null=True) price = models.FloatField(blank=True, null=True) My serializers: class MenusSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField('get_image_url') def get_image_url(self, obj): request = self.context.get('request') image_url = obj.image.url return request.build_absolute_uri(image_url) class Meta: model = Menus fields = ['category','image', 'image_url','food_name', 'description','price','rating'] My settings: # BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') # MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"media") MEDIA_URL = '/media/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) My project urls:py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I tried many things, putting just urlpatterns for media. Also,I commented out the media_root … -
What is the best practice for Dependency Injection in Django/Python?
I work on a Django-based product that works as a middleman/proxy between an enterprise ERP and some mobile clients. So it supposes to have scalability and easy maintenance in long run. One challenge I'm facing right now is the ability to have multiple versions both on API I expose to clients, and also API I consume from the ERP. I have my business logic in a separate module in each app named *_usecase.py, essentially I should implement versioning by having a base UseCase class and override methods for each version and provide the right class instance to view through DI based on request/response header values. So I've reached this package python-inject. It has pretty neat decorators to inject instances based on configuration you have and type annotation for method parameters. something like: # in view.py @inject.autoparams() def send_notification( request, use_case: SendNotificationUseCase, # as many type annotated parameters you required ): pass # in binder.py binder.bind_to_provider( SendNotificationUseCase, self.provide_send_notification_use_case ) def provide_send_notification_use_case(self): # some check and logic to evaluate appropriate version return SendNotificationUseCaseV1() # v1 implementation of usecase So this package does the job eventually, although I had some minor issues with it here and there but, since it doesn't have that … -
How to authenticate User from mysql in django?
I want to implement login app. all the users information are in table named 'admin_users'. I am using mysql server by xampp. when i am authenticating using user = authenticate(username=username,password=password) On printing user I am getting None. I am beginner in django and I could not find out whats wrong. If I am doing AdminUsers.objects.all() I can print all the table information. models.py class AdminUsers(models.Model): username=models.CharField(max_length=50) firstname=models.CharField(max_length=50) department=models.CharField(max_length=50) name=models.CharField(max_length=50) mail=models.CharField(max_length=50) id=models.IntegerField(primary_key=True) password=models.CharField(max_length=200) class Meta: db_table="admin_users" view.py def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username,password=password) print(user) return render(request,'AdminUsers/login.html') my index.html contains simple forms with username and password. settings.py """ Django settings for python_test project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j*uh&s1$j-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # … -
For loops in HTML Tables (for var in var)
I am trying to print some database values onto an HTML page. The html code is run through a for loop that counts the amount of description values. However it prints the entire database for each entry of Debit , Credit and Account Number. I'm pretty sure the problem is inside the for loop structure , please assist. Home.html: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> {% extends "main/base.html"%} {% block content%} <h1> Kyle Database </h1> <h2>Trial Balance</h2> <br> <br> <table> <th>Account</th> <th>Description</th> <th>Debit</th> <th>Credit</th> {% for description in description %} <tr> <td>{{ accountNo }}</td> <td>{{ description }}</td> <td>{{ debit }}</td> <td>{{ credit }}</td> </tr> {% endfor %} </table> {% endblock %} Views.py: def home(request): return render(request , 'main/home.html') def Kyletrb(request): desc = "SELECT Description FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor = cnxn.cursor(); cursor.execute(desc); description = [tup[0] for tup in cursor.fetchall()] accNo = "SELECT Account FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor.execute(accNo); accountNo = [tup[0] for tup in cursor.fetchall()] deb = "SELECT Debit FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor.execute(deb); debit = [tup[0] for tup in cursor.fetchall()] cred = "SELECT Debit FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor.execute(cred); credit = [tup[0] for tup in cursor.fetchall()] return render(request , 'main/Kyletrb.html' , {"description":description … -
Django app while dockerizing gives "Starting development server at http://0.0.0.0:8000/" but doesn't show up on browser
So I am a beginner in docker and Django. What I have here is a django app which I am trying to dockerize and run. My requirements.txt has only django and gunicorn as the packages. I am getting the below in terminal after building and running the docker image: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 26, 2021 - 06:57:22 Django version 3.2.6, using settings 'myproject.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Below is my Dockerfile: FROM python:3.6-slim ENV PYTHONUNBUFFERED=1 RUN mkdir /Django WORKDIR /Django ADD . /Django RUN pip install -r requirements.txt EXPOSE 8000 CMD python manage.py runserver 0.0.0.0:8000 The commands I am using are: docker build . -t myproj docker run -p 8000:8000 myproj I have tried adding allowedhosts = ['127.0.0.1'] in settings.py but still I am getting "The site can't be reached. 127.0.0.1 refused to connect. Not able to see the "Congratulations" screen. Please help me out with this. P.s: I am using windows machine -
Django model object changed after update
I have a simple model as follows: class Invite(models.Model): status = models.CharField() .... .... In my view, I update an Invite entity: invite_obj = Invite.objects.get(pk=id) // currently invite.status = "OLD" print(invite_obj.status) // prints OLD invite_serializer = CustomSerializer(invite_obj) // a custom serializer which updates the instance status from "OLD" to "NEW" if invite_serializer.is_valid(): invite_serializer.save() print("after update", invite_obj.status) // prints NEW variable invite_obj got modified after update. How did the variable storing the original entity is modified? -
How I generate qr code in django rest framework api
i want to make scannable qr code api generate qr code and put text inside qr code response in image formate models.py .... qr_code = models.ImageField(upload_to='qr_codes', blank=True) ... -
DRF FILE UPLOAD IN NESTED SERIALIZER
I have a three models company, company_contact,company_logo where i have to insert a data in three tables at once. i can upload a company and company_contact but not a company logo. DRF is deleting a nested serializer file itself. while i can see a data in request.data but when i put in serializer it automatically remove that field. here is my serializers class CompanySerializer(serializers.ModelSerializer): company_contact = CompanyContactDetailsGet(many=True,required=False) company_logo_details = CompanyLogoGet(many=True,required=False) class Meta: model = company_details fields = ('id','company_name','company_address','company_email','company_contact','company_logo_details') def create(self,validated_data): print("company_data",validated_data) company_contact_no = validated_data.pop('company_contact') print("company_contact",company_contact_no) # company_logo_data = validated_data.pop('company_logo_details') with transaction.atomic(): company = company_details.objects.create(**validated_data) # company_logo.objects.filter(Q(is_deleted_flag='n') | Q(company=company)).update(is_deleted_flag='y') # for data in company_logo_data: # companyLogo = company_logo.objects.create(company=company,**company_logo_data) for contact in company_contact_no: print("contactsss",contact,company) # contact['company'] = company company_contact_details.objects.create(company=company,**contact) return validated_data and here is my views.py @api_view(['POST']) # @parser_classes([MultiPartParser]) def add_company_all(request): serializer = CompanySerializer(data=request.data) if serializer.is_valid(): serializer.save() result = { 'data':serializer.data, 'msg':"Company Details Added Successfully!!" } return Response(result,status=status.HTTP_200_OK) result = { 'data':serializer.errors, 'msg':"invalid data!!" } return Response(result,status=status.HTTP_400_BAD_REQUEST) here is the data that comes in request in views.py <QueryDict: {'company_name': ['new company'], 'company_address': ['new baneshwor'], 'company_email': ['new@gmail.com'], "comapny_contact[0]['company_contact_no']": ['9867543450'], "company_logo_details[0]['company_logo']": [<InMemoryUploadedFile: 2016-08-27-10-59-56-187.jpg (image/jpeg)>]}> here is the data which goes in serializers company_data {'company_name': 'new company', 'company_address': 'new baneshwor', 'company_email': 'new@gmail.com'} -
How to make python django website more effective for adds?
I tried google adds after coding but finding issues with them also. -
Problem in token generation with django rest framework for django-tenants
My django project is working properly with multi tenant architecture. I have implemented rest framework but it is giving me an error for token authentication. I tried multiple ways for generating token (admin panel, signals , custom token class, djoser package) but I get the same error(below). IntegrityError at /api/token/login insert or update on table "authtoken_token" violates foreign key constraint "authtoken_token_user_id_35299eff_fk_accounts_customuser_id" DETAIL: Key (user_id)=(3) is not present in table "accounts_customuser". I think this is because auth token table is created in public schema and users are in seperate schemas. My settings file - SHARED_APPS = [ 'django_tenants', 'accounts.apps.AccountsConfig', 'customer', 'api.apps.ApiConfig', #project containing rest api 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'crispy_forms', 'rest_framework', 'rest_framework.authtoken', 'djoser', ] TENANT_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'accounts.apps.AccountsConfig', ' 'api.apps.ApiConfig', #project containing rest api 'rest_framework', 'rest_framework.authtoken', 'djoser', ] INSTALLED_APPS = list(set(SHARED_APPS + TENANT_APPS)) -
Saving profile instance when login
I am building a BlogApp I implement a feature and I am trying to save profile instance (Boolean) when user login. So I create a custom login page for saving profile instance, BUT User is successfully logging in BUT Profile instance (Boolean) is not updating. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=30,default='') email = models.EmailField(max_length=30,default='') send_notify = models.BooleanField(default=False) users/views.py def login_request(request): if request.user.is_authenticated: request.user.profile.send_notify = False request.user.profile.save() form = AuthenticationForm() return render(request = request, template_name = "registration/login.html", context={"form":form}) I have tried many times BUT is is still not updating, I also tried to change custom login but it is not even showing the login form. Any help would be much Appreciated. Thank You in Advance -
Which Django model should be used for staff members?
For a project (my own pet project) I am doing, I have an app called 'staff'. The ideas is 'staff' will contain list of all staff members in my organization. Now, they have to have an ability to login to the system and check what assets were assigned to them. The question is which built-in model (User, AbstractBaseUser, or AbstractUser) I should use for the 'staff' app? I've started with models.Model, however, I am thinking it might not be correct choice. -
Django ORM SQL Raw Mysql
select CONCAT(first_name,last_name)as broker_name,coupon_name, (select count(user_details.id)from user_details join user on user.id=user_details.user_id and user.role_id=3 where referral_coupon_id=coupons.id) as tenat_referrals, (select count(user_details.id) from user_details join user on user.id=user_details.user_id and user.role_id=2 where referral_coupon_id=coupons.id) as landloard_referrals from user LEFT JOIN coupons on coupons.user_id=user.id where role_id=4 -
I am new to Django and things i didnt understand are these can i get some insights
I have a problem or i am thinks that in which conditions do we write or to define functions like save and also in what condition do we need to write queryset -
Ignore changes to m2m relationship in post_save signal of django
I've got a question regarding django signals. Let's say I have these models: class Parent(models.Model): parent_name = (...) class Children(models.Model): child_name = (...) parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name='children') And let's assume I have this signal connected to the post_save signal of Parent class: def handle(*args, **kwargs): (...) post_save.connect(handle, sender=Parent) Now, If I create a new child: some_parent = Parent.objects.get(...) new_child = Child.objects.create( ..., parent = some_parent ) Even though I'm just creating a new Child, Django will send a post_save signal from some_parent and thus handle will be invoked. Is there a way to ignore this signal? Something similar to this: def handle(*args, **kwargs): if <some_condition>: # check if the signal is sent just because a new child is created # Ignore the signal return # Do everything as usual ... -
how to use code block plugin in ckeditor5 cdn in python django?
it can't work... i cant find solution. please it can't work... i cant find solution. pleaseit can't work... i cant find solution. pleaseit can't work... i cant find solution. pleaseit can't work... i cant find solution. pleaseit can't work... i cant find solution. please <head> <script src="https://cdn.ckeditor.com/ckeditor5/29.1.0/classic/ckeditor.js"></script> </head> <body> strong text<textarea id="editor" name="queseditor"></textarea> <script> ClassicEditor .create( document.querySelector('#editor'), { codeBlock: { languages: [ { language: 'python', label: 'Python' } ] } } ) .catch( error => { console.error( error ); } ); </body> -
Why does this call to the Google Secret Manager API cause my Django application to hang?
In short: I have a Django application being served up by Apache on a Google Compute Engine VM. I want to access a secret from Google Secret Manager in my Python code (when the Django app is initialising). When I do 'python manage.py runserver', the secret is successfully retrieved. However, when I get Apache to run my application, it hangs when it sends a request to the secret manager. Too much detail: I followed the answer to this question GCP VM Instance is not able to access secrets from Secret Manager despite of appropriate Roles. I have created a service account (not the default), and have given it the 'cloud-platform' scope. I also gave it the 'Secret Manager Admin' role in the web console. After initially running into trouble, I downloaded the a json key for the service account from the web console, and set the GOOGLE_APPLICATION_CREDENTIALS env-var to point to it. When I run the django server directly on the VM, everything works fine. When I let Apache run the application, I can see from the logs that the service account credential json is loaded successfully. However, when I make my first API call, via google.cloud.secretmanager.SecretManagerServiceClient.list_secret_versions , the application … -
Django - After removing a table from models.py and migrations I get "relation "<table name> does not exist"
So I realized I could just remove a table and add it as a ManyToMany relation to another model and I removed the creation of the table from the migration files in the folder. But for some reason I'm getting the error below when I call python manage.py migrate django.db.utils.ProgrammingError: relation "<table name>" does not exist How do you properly remove tables and or add attributes to models in models.py without causing errors when you run python manage.py migrate? -
Right Way to inherit django form fields
EnquiryForm is a model form with many fields, I am not able to inherit fields of the Parent form using inheritance. class EnquiryForm(models.ModelForm): ... possession = forms.ChoiceField( required=True, choices=(('', '----Select----'),) + models.Enquiry._meta.get_field('possession').choices, widget=forms.Select(attrs={'class': 'form-control btn btn-primary'}) ) ... # It has several other fields and clean method to manipulate user inputs and form validation class EditForm(EnquiryForm): possession_month = forms.ChoiceField(label='Possession Month', required=True, choices=MONTHS.choices, widget=forms.Select( attrs={'class': 'form-control btn btn-primary', 'required':True}) ) possession_year = forms.ChoiceField(choices=possession_year_choices( datetime.now().year + 10, datetime.now().year), label='Possession Year', required=True, widget=forms.Select( attrs={'class': 'form-control btn btn-primary', 'required':True}) ) class Meta(EnquiryForm.Meta): model = models.Enquiry fields = EnquiryForm.Meta.fields + ('possession_month', 'possession_year', ) Notice here (last line), I am directly accessing EnquiryForm.Meta.fields. but I tried to access it by inheritance super().fields of the Meta class but no luck. Can we inherit fields through Meta inheritance such as super(EnquiryForm.Meta).fields. P.S. - Also I have to drop the field possession from parent Meta.fields in EditForm. -
Keep getting last value in for loop
I'm trying to get all the values in the variable roomnum, but the last value of roomnum keeps showing up. However, when I tried to print roomnum the values show up correctly. I'm not quite sure where the problem lies. roomnum = request.POST.getlist('polygon-names') print(roomnum) for k,v in unique_keys.items(): if category_in_excel == "Material": color_cell_format = workbook.add_format({'font_color': 'black', 'bg_color': v['color']}) color_cell_format.set_align('center') worksheet.write(row + 1, col, k, cell_format) worksheet.write(row + 1, col + 1, v['color'], color_cell_format) worksheet.write(row + 1, col + 2, convert_quantity_from_mm_squared_to(units, v['initialArea'], precision), cell_format) worksheet.write(row + 1, col + 3, units, cell_format) worksheet.write(row + 1, col + 4, ",".join(v['pages']), cell_format) else: for i in roomnum: print(i) worksheet.write(row + 1, col, i, cell_format) worksheet.write(row + 1, col + 1, convert_quantity_from_mm_squared_to(units, v['initialArea'], precision), cell_format) worksheet.write(row + 1, col + 2, units, cell_format) worksheet.write(row + 1, col + 3, ",".join(v['pages']), cell_format) Terminal when I print out the i value in roomnum: Values that I get in excel worksheet: As shown, the value keeps repeating for Polygon 3, when it should be Polygon 1,2,3. Any help would be greatly appreciated thanks! -
Where to learn to crop videos in django
I'm trying to crop video in my Django application, but I literally cannot find any resources or libraries on cropping videos, every time I search something up, image cropping recourses pull up and nothing about cropping videos. I'm using cropper.js to crop my images, but the library only does images and not videos. I want something like in the picture below that works for videos. If anyone could tell me where to start or recourses they recommend that would be much appreciated. -
ValueError at /result X has 118990 features per sample; expecting 103815
I am trying to make a fake news detector using scikit learn and I have deployed it on Django. I have made a front-end for inputting news descriptions from the user and display the result according to the prediction and I have used pickle to save the model. When I give input it shows the above error. Code for removing stop words and train test splitting def word_drop(text): text = text.lower() text = re.sub('\[.*?\]','',text) text = re.sub("\\W"," ",text) text = re.sub('https?://\S+www\.\S+','',text) text = re.sub('<.*?>+','',text) text = re.sub('[%s]' % re.escape(string.punctuation),'',text) text = re.sub('\n','',text) text = re.sub('\w*\d\w*','',text) return text news_total['text'] = news_total['text'].apply(word_drop) X = news_total['text'] # independent variable y = news_total['flag'] # dependent variable X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.1,random_state=0) 'flag' determines whether the news is fake or not and 'text' is the news description in the dataset. Vectorizer and classifier code vectorizer = TfidfVectorizer(stop_words="english",max_df= 0.7 ) X_train_vector = vectorizer.fit_transform(X_train) X_test_vector = vectorizer.transform(X_test) psa_classifier = PassiveAggressiveClassifier(max_iter = 100) psa_classifier.fit(X_train_vector,y_train) y_predict = psa_classifier.predict(X_test_vector) pickle.dump(psa_classifier,open('model_pickle.sav','wb')) Front end part Code of the views.py of the app of the project. Also model_pickle.sav is in the same directory as the app. loaded_model = pickle.load(open("model_pickle.sav", "rb")) news_total = pd.read_csv("final_dataset.csv") X = news_total['text'] # independent variable y = news_total['flag'] … -
Django Upload Images from Forms
I am trying to upload the images from django widget form. The rest of the form is filed correctly but the image field shows errors. Despite using the request.FILES is still getting the error. What could be the problem Here is my views.py file def addProduct(request): form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('modifyAllProduct') context = { 'form': form } return render(request, 'products/Admin/addProduct.html', context) Here is my form.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['image', 'title', 'category', 'price', 'description', 'is_published'] widgets = { 'image': forms.FileInput(attrs={'class': 'form-control'}), 'title': forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'price': forms.TextInput(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'is_published': forms.CheckboxInput(attrs={'class': 'form-control'}), } Here is my model.py class Product(models.Model): image = models.ImageField(null=False, blank=False) title = models.CharField(max_length=2000, null=False, blank=False) category = models.ForeignKey( Category, on_delete=models.CASCADE, default=True, null=False) price = models.DecimalField(max_digits=5, decimal_places=2) description = models.TextField() delivery_time = models.DateTimeField(default=datetime.now, blank=True) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(default=datetime.now, blank=True) digital = models.BooleanField(default=False, null=True, blank=False) -
JQuery UI autocomplete dropdown select change another field value and deselect dropdown clear field value
I am working on Django template. I am try to find solution that, when i select autocomplete dropdown then change value of this input field which (id=id_project_id). and if i deselect or any change on autocomplete input field, clear previous value of (id_project_id) input field and value set as (value = "00"). After lot of search & implementation, I found solution. Thats code work for me. <input type="text" name="package_name" id="id_package_name" placeholder="project...."> <input type="hidden" name="project_id" id="id_project_id" value="00"> Here is my solution script. $("#id_package_name").autocomplete({ source:'{% url 'autocomplete_project_name' %}', autoFocus: true, select: function( event, ui ) { $("#id_job_no").val(ui.item.job_no); // auto fill item code in id_code field $("#id_project_id").val(ui.item.project_id); }, // CHANGE INPUT FIELD change: function(event, ui) { $("#id_project_id").val(ui.item ? ui.item.project_id : "00"); }, minLength: 2, delay:500 }); });