Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google Cloud storage upload method is returning signed URL. Django python
This is my upload image method from storages.backends.gcloud import GoogleCloudStorage storage = GoogleCloudStorage() def upload_image(file, dir_name, filename): try: target_path = '/static/images/' + dir_name + '/' + filename path = storage.save(target_path, file) return storage.url(path) except Exception as e: print(e) This is my settings in the django settings.py DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'bucket name' GS_PROJECT_ID = "project id" GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR,'google_cloud_credientials.json') ) I have used this tutorial for reference https://medium.com/@mohammedabuiriban/how-to-use-google-cloud-storage-with-django-application-ff698f5a740f This is returning me the signed URL for the file which I am using which is expiring after some time, but I want to have a public URL that will be available for any time. -
unoconv conversion from docx to pdf not working asynchronously
Goal I want to make a solution which can convert multiple docx files (submitted via separate parallel requests) to pdf. What I have tried and its behaviour After struggling with libreoffice --headless I came across unoconv which creates a listener for libreoffice in order to process multiple requests. Although, unlike libreoffice --headless, it does not fail to convert the docx files submitted via parallel requests, it seems that internally they are still processed sequentially. For example: If files A.docx & B.docx takes around 20 & 1.1 seconds respectively to get converted into .pdf individually, then, if both are submitted via 2 dedicated parallel requests and the conversion for both start at 00:00:00, the conversion process for both the files end at around 00:00:20. The behaviour I want However, the behaviour I want is to return the pdf for files as soon as they are converted eg: Just return the pdf for B.docx after 1.1 seconds, keep on converting A.docx and return that as well after 20 secs. Here's the minimal Django View for what I'm trying to do: def convert(request): docx_file = request.FILES['docx_file'] file = open(docx_file.name, "w+") file.write(docx_file.read()) cmd = "unoconv -f pdf %s" % file.name subprocess.Popen(cmd.split()).communicate(timeout=30) pdf_file_name = "%s.pdf" … -
How to Bulk Insert 5.5M records in mongodb through django model with in small time?
It took me around 6.5 to 7 hours in inserting bulk records from pandas dataframe of 5.5M records to my mongodb database through django model with 12-GB RAM. Below is the code for raised query. I want to make it faster to around 30 mins to 1 hour time, Is it possible ? # Split DF listDf = [] listDf = split_dataframe(completeDF02) ## This completeDF02 is the full dataframe having 5.5M records, So I split it with having 0.1M record in one batch in listDf list for item in listDf: df_records = item.to_dict('records') model_instances = [MyModel( Field1=record['Field1'], Field2=record['Field2'], Field3=record['Field3'], Field4=record['Field4'], Field5=record['Field5'], Field6=record['Field6'], Field7=record['Field7'], Field8=record['Field8'], Field9=record['Field9'], Field10=record['Field10'], Field11=record['Field11'], Field12=record['Field12'], Field13=record['Field13'], Field14=record['Field14'], Field15=record['Field15'], Field16=record['Field16'], Field17=record['Field17'], Field18=record['Field18'], Field19=record['Field19'], Field20=record['Field20'], Field21=record['Field21'], Field22=record['Field22'], Field23=record['Field23'], Field24=record['Field24'], Field25=record['Field25'] ) for record in df_records] MyModel.objects.bulk_create(model_instances) Is there an alternate way of doing bulk inserts to get more efficiency with speed ? If yes, then please let me know. -
How can I guard routes in Angular?
Currently, after logging in I'm able to get the JWT to the frontend. My app currently has a logging page as the landing page and as soon as the user logins the route checks for authentication to redirect to the guarded home path. My first intuition was to send a boolean from the backend (Django) and use that to create a guard. But I keep seeing that seems to be better practice to handle this in the front end. What I did was create an auth.service.ts and an auth.guard.ts. In the service, I try to retrieve the token from the browser and then verify that it hasn't expired. Then I call that method on the guard and return a boolean. Problem is that every time I look for the token in the local storage, I get back null. Is there any better way to get achieve this? auth.guard.ts import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree, } from '@angular/router'; import { Observable, of } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root', }) export class AuthGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) … -
New to Coding help in solving the issues im facing in django project
I am trying to create an event from Date A to Date B, i want to display that event in all following dates from date a to date b without me creating same event again and again. I am working on djnago -
MySQL Error 1146 and 1050 - Table does not exists and Table already exists
I've been migrating my database from the default Django sqlite3 to MySql but while running this command - py manage.py migrate --run-syncdb I get the following error django.db.utils.ProgrammingError: (1146, "Table 'blogue_test.blogueapp_category' doesn't exist") This is how I create the SQL Table manually CREATE TABLE blogueapp_category( -> id int NOT NULL AUTO_INCREMENT, -> name varchar(45) NOT NULL, -> PRIMARY KEY (id) -> ); Then re-run the same migrate command and it shows me the table already exists? MySQLdb._exceptions.OperationalError: (1050, "Table 'blogueapp_category' already exists") This is my Django models.py class Category(models.Model): name = models.CharField(max_length=255, db_index=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('category-list', kwargs={'cats': self.name}) I am merely a beginner in this and have been stuck with this same error for the past 2 days, even tried doing it in PostgreSQL but resulted in the same. Any help would be appreciated. -
how to get all data of price, qty from html in js and multiple it accordingly and add it into html in Django. anyone help me
I have attached the HTML on Photo Question - how to get all data of price, qty from HTML in js and multiple it accordingly and add it into HTML in Django. anyone help me. const x = document.getElementById("qty").innerHTML; const y = document.getElementById("price").innerHTML; const z = document.getElementById("total"); function calculator(qty, price) { let lowercase = price.toLowerCase(); const remove_price_string = lowercase.replace("only", ""); console.log(remove_price_string); let total = remove_price_string * qty; console.log(total); } calculator(x, y); -
Django image uploading error, "This field is required', "no files chosen"
I was working on a django project. I made a userprofiles app to manage(create, update) user's profile in my website, but it is not working properly. I am getting 'This field is required' & 'no file chosen' while making profile as a user and if I do blank=True in models profile_picture user pictures are not saving in the media url. I have tried so many tips from stackoverflow but they are not working. here is my code: # settings.py MEDIA_URL = '/media/' MEDIA_ROOT = str(BASE_DIR.joinpath('media')) # models.py from django.db import models from django.contrib.auth import get_user_model import uuid class UserProfile(models.Model): author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='media/images/') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.TextField(blank=True) occupation = models.CharField(max_length=100) hobbies = models.TextField(blank=True) date_of_birth = models.TimeField() def __str__(self): return self.author.username + ("'s profile") # views.py from django.views.generic import CreateView from .forms import CustomUserCreationForm from django.urls import reverse_lazy class SignUpView(CreateView): form_class = CustomUserCreationForm template_name = "registration/signup.html" success_url = reverse_lazy("profile_create") # project-level urls.py from django.contrib import admin from django.conf import settings from django.urls import path, include from django.conf.urls.static import static from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path("accounts/", include("accounts.urls")), path("accounts/", include("django.contrib.auth.urls")), path("profile/", include("userprofiles.urls")), path("", TemplateView.as_view(template_name="home.html"), name="home"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # app-level urls.py … -
Need to get the value of Employee_name from User model to Employee model
# model 1 class User(models.Model): JOINING_ROLES_CHOICES= ( ('sde-intern','SDE Intern'), ('sde-trainee','SDE Trainee'), ('sde_1','SDE I'), ('ui/ux','UI/UX Designer'), ('quality-engineer-trainee','Quality Engineer Trainee'), ('quality-engineer','Quality Engineer'), ('product-manager','Product Manager'), ('technical-manager','Technical Manager'), ('technical-architect','Technical Architect'), ('technical-lead','Technical Lead') ) BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) employee_name = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=100,default=None) aadhar=models.CharField(max_length=100,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) joining_role=models.CharField(max_length=250,choices=JOINING_ROLES_CHOICES,null=True) relieving_role=models.CharField(max_length=250,null=True) joining_Date=models.DateTimeField(max_length=8,null=True) relieving_Date=models.DateTimeField(max_length=20,null=True) def __str__(self): return self.firstname #model 2 class Employeename(models.Model): employee = models.ForeignKey(User, related_name='employee', on_delete=models.CASCADE) employee = models.ManyToManyField(User) def __str__(self): return self.employee I need to get the employee_name value from the User model to the Employeename model. Is there any ways to get only employee_name to the employee. while i tried the above code it it throwing an error as mentioned below: TypeError at /admin/App/employee/3/change/ str returned non-string (type ManyRelatedManager) -
How else can i write this django custom validation othere than try and except
how else can i frame this django custom validation function to validate US phone number other than try and except block def validate(value): if re.match(r"[+]?[1\s-]*[\(-]?[0-9]{3}[-\)]?[\s-]?[0-9]{3}[\s-]?[0-9]{4}",value): return True else: return False -
I am not able to send mail in django
THIS IS MY SETTINGS.PY FILE EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL= 'myyandexmail.com' EMAIL_HOST = 'smtp.yandex.com' EMAIL_HOST_USER = 'myyandexmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False This is my views.py file def contact(request): if request.method == "POST": name = request.POST['name'] email =request.POST['email'] message =request.POST['message'] data = { 'name': name, 'email': email, 'message': message } done_message = 'Your message has been sent. We will respond to you soon' try: #send_mail(data['name'],data['message']+ '\n' ' from ' + data['email'],'info@kahwart.com',['info@kahwart.com'],fail_silently=False) msg=EmailMessage(data['name'],data['message']+ '\n' ' from ' + data['email'],'myyandexmail.com',['myyandexmail.com']) msg.send() return render(request,'artgallery/contact.html',{'message':done_message}) except BadHeaderError: return render(request,'artgallery/contact.html',{'message':done_message}) This is working file on lcoal host but doesnot work on digital ocean.First it was showing errors then i made changes to the code ..But it is not showing any errors now ..But it is not sending mails either...when i click the submit message button it only gets refreshed..What should i do.. -
Django Object level permissions
I have to create groups in django for example, lets say A, B, C. I have a model X and each group has access to a set of instances (Objects) of X. I also have to create user, who belongs to one or more of these groups. Now based on the groups access to model X objects, i have to restrict view access to the user. Is there any solution in django that provides this kind of solution of out the box? Or do i have to create separate tables and control the permissions. -
Deployment to Heroku for Django with channels Failed
I'm trying to deploy to Heroku for Django, but it doesn't work and some logs appreared. I'm at a loss because I don't know the cause. I was wondering if someone could tell me what should do or some tips... heroku logs (web) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. heroku logs (worker) unicodeerror: label empty or too long backend(project name)/asgi.py import os import api.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django.setup() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import OriginValidator from django.core.asgi import get_asgi_application application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': OriginValidator( AuthMiddlewareStack( URLRouter( api.routing.websocket_urlpatterns, ) ), [ 'http://localhost:3000', 'http://127.0.0.1:3000' ] ) backend(project name)/wsgi.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django.setup() from dj_static import Cling from django.core.wsgi import get_wsgi_application application = Cling(get_wsgi_application()) backend(project name)/setting.py(excerpt) . . . WSGI_APPLICATION = 'backend.wsgi.application' ASGI_APPLICATION = 'backend.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(env('REDIS_URL'), env('REDIS_PORT'))], }, }, } . . . Procfile release: python manage.py migrate web: daphne backend.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=backend.settings -v2 manage.py import os import sys import django def main(): """Run administrative … -
how to integrate a vue js project within a django project?
I have an existing vue js project and for backend I want to use django, what came to my mind was to use rest api to communicate with the backend without any integration. is that what everyone is doing or my approach is old school and I have to put the vue project in django directory and go through the whole collectstatic thing? sorry if my question is too basic. -
Django heroku deployment No web process error
Please help me to fix this error. I already have Procfile but I still get same error[enter image description here][1] -
Call a stored-procedure mysql in django
I am using a procedure I have written in MySQL that I want to call in Django but I am just receiving an error : " AttributeError: 'Cursor' object has no attribute 'stored_results' " I can't find why is cursor has no attribute, all the info I get about calling a procedure with python goes with the code 'cursor.stored_results()'. Do you have an idea ? My procedure is : CREATE DEFINER=`root`@`localhost` PROCEDURE `ProcTime`(IN in_date int, OUT somme int) READS SQL DATA BEGIN SELECT SUM(tot) INTO somme FROM( SELECT Habitat, COUNT(DISTINCT(Transect)) AS tot FROM MyTable WHERE Year = @in_date GROUP BY Habitat ) AS t ; END And I am calling it in my views : cursor = connection.cursor() args = ['2004', 0] cursor.callproc('ProcTime', args) for result in cursor.stored_results(): print(result.fetchall()) Thanks !! -
Django search with AND operator many to many relationship
This is my model class MenuItem(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) menu_category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) def __str__(self): return f'{self.name}' class Venue(models.Model): name = models.CharField(max_length=500, null=False) def __str__(self): return f'{self.name}' class VenueMenu(models.Model): venue = models.ForeignKey(Venue, null=False, on_delete=models.CASCADE) menu_item = models.ManyToManyField(MenuItem, null=False) This is my view @api_view(['GET']) def search_menu_item(request): if request.GET.get('venue') and request.GET.get('search_name'): menu_item_filter = Q(menu_item__name__icontains=request.GET.get('search_name')) venue_filter = Q(venue__name=request.GET.get('venue').title()) menu_item_search = VenueMenu.objects.filter(venue_filter & menu_item_filter) serializer = VenueMenuSerializer(menu_item_search, many=True) return Response(serializer.data) This is my serializer class MenuItemSerializer(serializers.ModelSerializer): menu_category = MenuCategorySerializer(many=True) class Meta: model = MenuItem fields = '__all__' class VenueSerializer(serializers.ModelSerializer): class Meta: model = Venue fields = '__all__' class VenueMenuSerializer(serializers.ModelSerializer): menu_item = MenuItemSerializer(many=True) venue = VenueSerializer(many=False) I want to search a single menu item information in a specific venue, as you can see in my query am querying the object but this query is returning me all the menu items associated with that venue including the one which I have searched but I want to have a single menu item which I am searching associated to that venue. -
django-allauth or django in general render template on user status
My menu in the html looks like this: <ul id="nav-mobile" class="right"> {% user_display user %} <li><a href="/accounts/login">Login</a></li> <li><a href="/accounts/logout">Logout</a></li> <li><a href="/accounts/signup">Signup</a></li> </ul> Obivous this doesn't make much sense, cause if a user is not logged in it should be possible to logout and vice versa. Are there any template-tags in django or django-allauth, which I can write in the template like. PseudoCode <if user login> <a> logout </a> <end if> -
How can I give a value to a Django environment variable from within the application itself?
I developed an application with its respective access login, when the user tries to log in, he must select a value that will be used throughout the execution of the application until the user closes the session. I have my project configured with environment variables, I use the django-environ 0.8.1 library to configure these variables so that my application can access them in the .env file. How can I manage the login variable with these environment variables? import environ # environ init env = environ.Env() environ.Env.read_env() # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env.str('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool('DEBUG', default = False) # This is the variable that I need to change according to the option # that the user chooses when logging in DATABASE_SAP_CHOSEN = 'SBOJOZF' -
Django admin login not working for superuser
I'm a newcomer to Django, so sorry if this question is bad. I have looked on the internet but have not been able to find a solution. I am trying to login to a superuser account I created with manage.py. I have not modified any file in my Django project, and am using Django 3.2.5. Every time I try to log in on the admin page it gives me this error Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive (in the web browser of course). I know I am using the username and password that I used when creating the superuser account. I have created two super users the second to while trying to figure out what is going on with this error. I am using the default sqlite3 db. I am also using a anaconda virtual environment. I have also made sure to run migrations. -
Use viewset as action in DRF
i am learning Django and DRF, i have a problem. I need to register an url like this collaborators/<str:cc>/sympathizers but the default drf router is overriding the route with the primary key, like collaborators/<str:pk>/ i can do it with viewsets actions but i am going to implement some hard logic and i want my code to be order. router = SimpleRouter() router.register('candidates', CandidateViewSet) router.register('collaborators', CollaboratorViewSet) // the following route is overrided router.register('collaborators/<str:cc>/sympathizers', SympathizerViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(router.urls)) ] -
no such column: student_student.course_id
I am creating a simple system using Django Sqlite but I am facing this error whenever i try to open the table as an admin in the django/admin by clicking Studends table. The error is the following: OperationalError at /admin/student/student/ no such column: student_student.course_id I searched allot but could not find any exact solution to my problem. The following is my code. views.py from django.shortcuts import render from .models import Student # Create your views here. def index(request): return render(request, "student/index.html",{ "student": Student.objects.all() }) index.html {% extends "student/layou.html" %} {% block body %} <h2>Student information</h2> <ul> {% for student in Student %} <li> {{ student.id }} Student Full Name: {{ student.f_name }}{{ student.l_name }} in {{ student.grade }} with {{ student.gpa }} in {{ student.course_id }}</li> {% empty %} No information entered {% endfor %} </ul> {% endblock %} models.py from django.db import models # Create your models here. class Course(models.Model): code = models.CharField(max_length=10) course_name = models.CharField(max_length=64) def __str__(self): return f"Course name: {self.course_name} with course code ({self.code})" class Student(models.Model): f_name = models.CharField(max_length=64) l_name = models.CharField(max_length=64) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name= "Classes" ) grade = models.CharField(max_length=10) gpa = models.DecimalField(max_digits=4.0, max_length=4, decimal_places=2) def __str__(self): return f"{self.id} Full Name: {self.f_name} {self.l_name} in {self.grade} … -
Why can't Django find secrets.json file?
So I have my Django project, and am trying to deploy it via heroku server. I realized that I need to created secrets.json file (in the same directory as manage.py), and then add it to .gitignore, for sake of security. But after deploying the project, I got an error saying it couldn't find secrets.json file. Below is my code. settings.py secret_file = os.path.join(BASE_DIR, 'secrets.json') with open(secret_file) as f: secrets = json.loads(f.read()) def get_secret(setting, secrets=secrets): try: return secrets[setting] except KeyError: error_msg = "Set the {} environment variable".format(setting) raise ImproperlyConfigured(error_msg) SECRET_KEY = get_secret("SECRET_KEY") secrets.json { "SECRET_KEY" : xxx, "EMAIL_HOST_USER" : xxx, "EMAIL_HOST_PASSWORD" : xxx } After saving these, I added secrets.json to .gitignore. But an error occurs at line 2 (with open(secret_file) as f:), saying it can't find secrets.json file. What do you think is the problem? *FYI, The BASE_DIR doesn't seem to be the problem, since it works fine else where. Such as STATICFILES_DIRS. -
Django Rest Framework and Djongo: serializer create method returns an object with incorrect _id
I have following Djongo model: from djongo import models class Feedback(models.Model): _id = models.ObjectIdField() title = models.CharField(blank=False, max_length=100) text = models.TextField(blank=False) datetimestmp = models.DateTimeField(auto_now_add=True) I have following serializer for the model above: from rest_framework import serializers from .models import Feedback class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = Feedback fields = "__all__" read_only_fields = ["datetimestmp", "_id"] def create(self, validated_data): obj = super().create(validated_data) print(obj._id) return obj When I'm sending POST request to create a Feedback entry inside DB wrong id gets printed to the console: curl -X POST -H "Conte-Type: application/json" -d '{"title": "Example Title", "text": "Example Text"}' http://127.0.0.1:8000/api/feedbacks results in 24 being printed to the server console instead of real ObjectId from MongoDB: ObjectId("61f85ecbb0804f215c127c30"). Is there a way to resolve this issue? Thank you -
So I accidently added a META class and am trying to get rid of it, but the csrf.py file doesn't remove the Meta tag
This is the error I get when trying to go past the login page I have set up. module 'urllib.response' has no attribute 'META' What do I need to delete from the csrf.py file to fix this?