Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No such file or directory when python manage.py runserver
I have function to upload the document in folder, after it i want to execute methods to transform this file. I wrote another functions where i am calling this methods, but after pyrhon manage.py runserver i receive No such file or directory: 'beeline/media/docs/assignment.xlsx' But if i execute python file with methods everyrhing is working fine class UploadView(generic.TemplateView): def get(self, request): form = ExcelForm return render(request, 'index.html', {'form': form}) def injection(self): post_team() post_db_service() post_database() post_db_schema() post_db_table() return "Everything is created" def post(self, request): if request.method == 'POST': form = ExcelForm(request.POST, request.FILES) if form.is_valid(): upload = request.FILES['file'] fss = FileSystemStorage('media/docs') fss.save(upload.name, upload) self.injection() return render(request, 'ty.html') return render(request, 'index.html') -
Django calculated fields on custom queryset
This seems like a basic question but for the life of me I cannot seem to figure this out. I have a Recipe model that uses a custom RecipeQueryset as a manager. Now I've been doing a lot of reading on where to put business logic of the application some people suggest a "services" layer others say to put it in a custom queryset which is what I am trying to accomplish now. None of them really give an example of doing calculations though only CRUD functionality. At the moment I have a property of total_cost defined on the Recipe model but according to a lot of articles/discussions I should be moving this "business logic" to elsewhere to the custom queryset for example? Is there a way to do the calculation in a custom queryset method for a queryset of Recipe objects and calculate that total_cost for each Recipe and return that queryset with the extra total_cost field? How would I then add this so it can be used in my serializer? Model class RecipeQueryset(models.QuerySet): """Custom queryset for Recipe Model""" def all_for_user(self, user): return self.filter(user=user) # this is where I think I should put it? def total_cost(self, recipe): return # … -
While downloading xls file from django download code, file is not opening, It shows corrupted
Here is my code for xls download using python(Django) views.py def downloadfile(request, filename=''): if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" path = open(filepath, encoding='cp437') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response else: return HttpResponseRedirect("adduser", {}) With this code I am able to download file properly, but while opening that file it shows me error. I attach screenshot of error. I have tried this code for solution, if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" return FileResponse(open(filepath, 'rb') , True, filename) else: return HttpResponseRedirect("adduser", {}) This also not works, It shows error 'TypeError at /downloadfile/SampleExcel.xls HTTP status code must be an integer.', and it is not even downloading. Please help me. I am stuck here from last 3 days. Note: I need to download xls file only, as after downloading it I have to perform import functionality with that downloaded xls file. I can not change xls to xlsx. -
Django Form Is None
Im on investigation Django framework and now trying to create custom procedure of resetting password. I use this URL path path('password_reset_confirm/<uidb64>/<token>', PasswordResetConfirmView.as_view( template_name='user_account/reset_password/password_reset_confirm.html', success_url='/account/password_reset_complete/'), name="password_reset_confirm"), In template i use crispy form <form class="login-form p-4 rounded" method="post"> {% csrf_token %} <h1 class="h4 mb-4 font-weight-bold">Change your password</h1> <p>Use the form below to change your password.</p> {{ form|crispy }} <button type="submit" value="Change"> Submit </button> </form> So now this form do not showing in template, and if if type {{ form }} instead of {{ form.as_p }} or crispy form, that showing me None in form place. -
"GET /static/css/stylesheet.css HTTP/1.1" 404 1813
I tried to ling CSS file in Django framework by using " " It shows error but, it is showing error ""GET /static/css/stylesheet.css HTTP/1.1" 404 1813file Oder" -
Can't use context data in the HTML in django
models.py class ChapterQuestions(models.Model): question_id = CharField(primary_key=True, max_length=40) question_order = CharField(max_length=40, blank=True, null=True) question_wording = CharField(max_length=4000, blank=True, null=True) question_type = CharField(max_length=1, blank=True, null=True) sub_question = CharField(max_length=1, blank=True, null=True, default='N') sub_question_trigger = CharField(max_length=1, blank=True, null=True, default='Y') answer_required = CharField(max_length=1, blank=True, null=True, default='Y') parent_question = models.ForeignKey('self', on_delete=models.DO_NOTHING) chapter = models.ForeignKey(ReportChapter, on_delete=models.DO_NOTHING) update_date = models.DateField(blank=True, null=True) update_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, db_column="update_user", blank=True, null=True) class Meta: managed = True db_table = "Chapter_Question" views.py class LfrReportChapterOneView(PermissionRequiredMixin, TemplateView): permission_required = "RockHub_App.is_in_risk_and_ic_team" template_name = "../templates/dashboards/lfr/lfr_report_chapitre1_create.html" def get_context_data(self, *args, **kwargs): context = super(LfrReportChapterOneView, self).get_context_data(*args, **kwargs) data = ChapterQuestions.objects.filter(chapter_id=1).order_by("question_id") context["questions"] = data return context While debugging i can see all the data available in the database but in the HTML file when I write **<h1>{{ questions.question_id }}</h1>** or <div hidden> {% for qst in questions %} {{ qst.question_id }},{{ qst.question_name }} {% endfor %}</div> <div><h1>{{ qst.question_id }}</h1></div> Nothing is shown !! -
daphne service listen failure: Couldn't listen on 0.0.0.0:8001 Address in already in use
as the title indicates I am using django-channels with daphne in the production server but when I show the status of daphne.service it says 8001 is already in use. The interesting thing is that the socket connection is working perfectly with the frontend and easily exchanging messages. here is my configurations # /etc/systemd/system/daphne_seb.service [Unit] Description=daphne daemon After=network.target [Service] User=simple Group=www-data WorkingDirectory=/home/simple/my_proj ExecStart=/home/simple/my_proj/venv/bin/daphne -b 0.0.0.0 -p 8001 project.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target daphne asgi in supervisor # /etc/supervisor/conf.d/daphne_proj.conf [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8001 # Directory where your site's project files are located directory=/home/simple/my_proj # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/home/simple/my_proj/venv/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --endpoint fd:fileno=0 --access-log - --proxy-headers project.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=4 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/home/simple/my_bg/daphne.log redirect_stderr=true finally, my nginx looks like this upstream websocket { server 0.0.0.0:8001; } server { listen 80; server_name MY_SERVER_DOMAIN; location = /favicon.ico { access_log … -
How to call a variable present inside a function into a different function present inside a class in python?
I want to compare the 'limit' variable present inside a function with another integer variable 'amount' present inside a different function inside a class. @login_required def Limit(request): if request.method == "POST": limit = request.POST.get('tlimit') en = UserLimit(limit=limit) en.save() print(limit) return render(request, 'limit.html') class PaymentView(View): def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) form = PaymentForm(self.request.POST) userprofile = UserProfile.objects.get(user=self.request.user) if form.is_valid(): token = form.cleaned_data.get('stripeToken') save = form.cleaned_data.get('save') use_default = form.cleaned_data.get('use_default') if save: if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: customer = stripe.Customer.retrieve( userprofile.stripe_customer_id) customer.sources.create(source=token) else: customer = stripe.Customer.create( email=self.request.user.email, ) customer.sources.create(source=token) userprofile.stripe_customer_id = customer['id'] userprofile.one_click_purchasing = True userprofile.save() amount = int(order.get_total() * 100) if (amount > limit): print("Not allowed") -
how to import excel file in mysql database with check the field validation which have country code or not in django python
how to upload excel file in mysql database before import , check the field validation for contact number which have country code or not in django python. Hi we are trying to import file to add data to database , for simple data it is working. but we want to know before import data we want to check whether contact number data have country code or not so how can we check? Is it possible to check data before import? -
Need to check if a timer is started when reload the page and continue running the timer
I did a timer with Django and Java Script to count how many hours a user is working into the company. My problem is, when i refresh the page the timer is rested. I need to get the timer continue counting up in accordance with the date and time in hours when the page is reload IF the timer is starting. HTML <link rel="stylesheet" href="../static/css/contador.css" /> <script src="../static/js/contador.js"></script> {% block content %} <!-- Main page --> <section class="container chrono"> <!------ Message displaying in a div ------> {% if messages %} {% for message in messages %} <div class="center"> <div class="{{ message.tags }}"> <div> {{ message }} </div> </div> {% endfor %} </div> {% endif %} <div class="row justify-content-center"> <div class="profile-complete-button col-sm-4 center" id="cronometro"> <div id="reloj"> 00:00:00 </div> <form name="cron" action="#"> <input class="btn btn-cron" type="button" value="Iniciar" id="button_1" name="boton1" /> <input class="btn btn-cron" type="button" value="Pausar" id="button_2" name="boton2" /><br/> </form> </div> </div> </section> {% endblock %} JS if($(this).val() === 'Iniciar') { $.ajax({ url: 'view_contador_start', headers: {"X-CSRFToken": getCookie('csrftoken')}, method: 'POST', contentType: 'application/json', data: JSON.stringify({ 'contador_time_start': '00:00:00', 'chrono_date': WithoutTime() }), dataType: "json", cache: false, success: function (response) { console.log(response) } }); ``` Django ``` def view_contador_start(request): """View to display the counter""" print('body', request.body) chrono_data_start = … -
encrypt data in django that need complex search
we have a Django Rest app with PostgreSQL db that in some parts business force us to encrypt data. but what I need is searching and heavy queries on data to be executed, I've used django-pgcrypto-fields but it's not updated until 2021 and have some bugs for production,what can I do?encrypting data directly does't allow me to execute queries for search the data,also I can't find any other library to help me. -
Django "no such table found" error even after makemigrations
I recently add a new table RunningTable in my models file and I do execute both: python manage.py makemigrations and python manage.py migrate. Both commands returned success. And I checked files in APPName/migrations/000x.py and the RunningTable lies really there. But my code runs with this table not found error. I tried check by Django shell with below picture shows. As you can see, I can import it from the correct path. But failed when I call RunningTable.objects.all(). Is there anyone can tell me why this error happens? -
How to set custom text for django on_delete function?
I have a model named 'Clients' and another model named 'Information'. class Information(models.Model): client_name = models.ForeignKey(Clients, on_delete=models.SET(get_deleted_client_intance)) I want to set a custom text when a name is deleted from 'Clients' model. The below function creates a new name 'deleted' as a new entry and is saved in 'Clients' model. I don't want that. I want if I delete a name it says 'deleted' or 'removed' on it's place. def get_deleted_client_intance(): return Clients.objects.get_or_create(name='deleted')[0] How can I do this? -
Use Count with aggregate(Sum) in django ORM, Custom Queryset Fields
i want to use query in which I need No of Invoices and Total Amount of Invoices in a Queryset. Invoice.objects.aggregate(total_amount=Sum('order__order_items__amount')) Invoice.objects.count() how can i handle above queries in a single query. -
Efficient way to re-order objects in Django
I have written a query to re-order objects based on the values I get in the API request. Below is the sample code I have written: @action(detail=False, permission_classes=[], methods=["PUT"]) def reorder_modules(self, request, *args, **kwargs): """ ReOrdering Modules Sample request data { <module_id>: <ordering_number> 12: 2, 13: 1, 14, 3, } """ updatabale_modules = [] for module_id, module_order in request.data.get("modules", {}).items(): _mod = Module.objects.get(id=module_id) _mod.order = module_order updatabale_modules.append(_mod) Module.objects.bulk_update(updatabale_modules, ["order"]) return Response({"detail": "successfully reordered course modules"}, status=HTTP_200_OK) Is there any way to avoid looping and getting each module? If that's possible I should be able to save making a few queries. -
How to annotate foreignkey
class Bookmark(CoreModel): """Bookmark Model Definition""" spot = models.ForeignKey( "spots.Spot", related_name="bookmarks", on_delete=models.CASCADE ) class Spot(models.Model): """Spot Model Definition""" name = models.CharField(max_length=50) coords = models.PointField(srid=4326) this is my model bookmarks = Bookmark.objects.filter(user_id=user_id).annotate( distance=Distance("spot__coords", ref_location) ) for bookmark in bookmarks: print(bookmark.spot.distance) <- error this is my queryset bookmark.distance is working, but i want bookmark.spot.distance "distance" appears in "bookmark". How can I annotate "distance" in "spot"? -
Request response in django
I have question? like if user request to the server then server process and in the processing if server gets another request then what will happen with the response i am talking about django -
While Creating a new user in Django, I'm seeing this error: for model in model_or_iterable: TypeError: 'function' object is not iterable
I am new to Django and currently, I'm building a web application which requires user authentication. I'm trying to make a sign-up page for new users. I tried to register my User model on the admin.py page but now I'm seeing this error. It says I'm having the error at the 8th line of the admin.py file. Here's my admin.py file. from django.contrib import admin from .models import User # Register your models here. class User_display(admin.ModelAdmin): list_display = ("id","username","password") admin.site.register(User,User_display) Right now, I have only the User model. Here's my views.py file. def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] password = request.POST["password"] confirm_password = request.POST["confirm_password"] if(password != confirm_password): return render(request,"precisionmedicine/register.html",{ 'message' : "Sorry! Password didn't matche." }) try: user = User.objects.create_user(username, email, password) user.save() except IntegrityError: return render(request, "network/register.html", { "message": "Username already taken." }) login(request,user) return HttpResponseRedirect(reverse("profile",kwargs={id: request.user.id})) else: return render(request,"precisionmedicine/register.html") def profile(request,id): id = request.user.id return render(request,"precisionmedicine/profile.html",{ 'id' : id }) I don't exactly get this problem. Please let me know if I need to share more parts of my code. I need to solve this immediately. -
filter price range by django-filter
I added a price range filter by Django-filter but seems it doesn't work filters.py from django_filters import FilterSet from .models import Apartment class ApartmentFilter(FilterSet): class Meta: model = Apartment fields = { 'price': ['lt','gt'] } views.py class ApartmentViewSet(viewsets.ModelViewSet): queryset = Apartment.objects.all().order_by('-timestamp') serializer_class = ApartmentSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerApartmentOrReadOnly] filter_backends = [filters.SearchFilter, DjangoFilterBackend, filters.OrderingFilter] filter_class = ApartmentFilter search_fields = ['address'] filterset_fields = ['category', 'district'] ordering_fields = ('price',) -
Django upload and download files in google drive using googledriveapi
I am new to django and trying to create a web app to upload and download files to the google drive using gdriveapi. I have gone through the python quickstart for Google drive and tried the code in manage.py where it is working. How to write the same code to obtain credentials and upload and download in the django app? How to write the view and model in django to obtain credentials and upload files to gdrive? -
Other keys for error messages in Django model
When you want to set error messages in Django model field use: class UserCreationForm(forms.ModelForm): password1 = forms.CharField( label='password', widget=forms.PasswordInput(attrs={'class': 'form-control form-control-lg'}), error_messages={ 'required': ("required"), '?': ("..."), } ) How can we fine other keys like required? -
Download Excel File in Django
we have several complicated, long-running functions that generate data reports. These services started taking longer as we scaled up, and we were getting concerned that our report generation functions might time out, or jam the server for other users. We didn’t see a lot of guides on implementing async downloads on apps that use Django for both the front and the back end, So I'm looking for some guide how can i implement async download properly, for production level. -
Django: How to render a Model from a tempalte to another?
I have an app were I'm trying to make a course with modules in it, and inside the course page I want to link a page with the modules of the course in it but I get "TypeError at /modules modules_page() missing 1 required positional argument: 'id'". Sorry for my bad explaining. I appreciate every answer, thanks in advance! Models.py class Course(models.Model): title = models.CharField(max_length=30) description = models.TextField(null=True, max_length=150) #completion_time = models.CharField(max_length=30) course_image = models.ImageField(blank=True, null=True, upload_to="images/") watching = models.ManyToManyField(User, blank=True, related_name="watchlist") category = models.ForeignKey(Category, on_delete=models.CASCADE ,related_name="listing_category") author = models.ForeignKey(User, on_delete=models.PROTECT, related_name="author") ended = models.BooleanField(default=False) creation_date = models.DateTimeField(default=timezone.now) class Module(models.Model): title = models.CharField(max_length=255, null=True) description = models.TextField(blank=True, max_length=2550, null=True) module_image = models.ImageField(blank=True, null=True, upload_to="images/") creation_date = models.DateTimeField(default=timezone.now) module_author = models.ForeignKey(User, on_delete=models.PROTECT, related_name="module_author") deadlined = models.BooleanField(default=False) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="modules", null=True) Views.py def courses_page(request): courses = Course.objects.all() return render(request, "auctions/index.html", { "courses": courses }) # THIS FUNCTION IS NOT WORKING def modules_page(request, id): if not request.user.is_authenticated: return render(request, "auctions/login.html") course = Course.objects.get(id=id) ended = Course.ended return render(request, "auctions/modules_page.html", { "course": course, "course_ended": "Course has ended.", "commentform": CommentForm() }) Urls.py path("", views.index, name="index"), path("auction/course/<str:id>", views.course, name="course"), path("modules", views.modules_page, name="modules_page"), Template.html: <!-- Modules --> <h3><span class="badge badge-secondary badge-pill mx-1">{{ course.modules.count }}</span><a href="{% … -
request.user returning AnonymousUser in ModelViewSet, but working properly in APIView
I am trying to customize get_queryset() in my DocumentViewSet so the GET method will return all Document objects created by request.user (currently logged in user). However, I am stuck in this error:django.core.exceptions.ValidationError: ['“AnonymousUser” is not a valid UUID.'] I assume this is caused by getting AnonymousUser as my self.request.user. The weird part is that my other APIView that deals with request.user are working flawlessly; The only difference I could find between the two is type of viewset: ModelViewSet vs APIView. Would appreciate any help! document.views class DocumentViewSet(viewsets.ModelViewSet): model = Document serializer_class = DocumentSerializer list_serializer_class = DocumentListSerializer permission_classes = (AllowAny,) # for testing, will change later def get_queryset(self): user = self.request.user return Document.objects.filter(user=user) def perform_create(self, serializer): print(self.request.user) serializer.save(user=self.request.user) document.models class Document(models.Model): id = HashidAutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100, default="Untitled") template = models.CharField(max_length=100, default="") editorState = models.JSONField(default=[]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title user.models class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None first_name = models.CharField(max_length=100, default="unknown") last_name = models.CharField(max_length=100, default="unknown") profile_pic = models.CharField(max_length=200, default="unknown") email = models.EmailField(unique=True, db_index=True) secret_key = models.CharField(max_length=255, default=get_random_secret_key) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] class Meta: swappable = "AUTH_USER_MODEL" users.api & selectors This is the APIView which … -
Cannot assign 3, must be a model instance while bulk create in django rest
I am trying to do a bulk create and update in a view. But however, when I bulk create the following error. ValueError: Cannot assign "3": "LmsGrade.exam" must be a "LmsExamModel" instance. I have done bulk_create several times before but none of the time it ask for a instance instead of id. But I think its because i did in the serializer class and serializer class pre validates everything before performing an operation. MY models: class LmsGrade(TimeStampAbstractModel): exam = models.ForeignKey( "lms_exam.LmsExamModel", on_delete=models.CASCADE, related_name="lms_grades" ) student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name="grades" ) marks_obtained = models.PositiveIntegerField(blank=True) grade_obtained = models.CharField(max_length=2, blank=True) present = models.BooleanField(default=True) My view: def create(self, request, *args, **kwargs): grades = self.request.data grades_to_create = [] grades_to_update = [] grades = [ { "id": LmsGrade.objects.filter( exam_id=grade.get("exam"), student_id=grade.get("student"), ) .first() .id if LmsGrade.objects.filter( exam_id=grade.get("exam"), student_id=grade.get("student"), ).first() is not None else None, **grade, } for grade in grades ] [ grades_to_update.append(grade) if grade["id"] is not None else grades_to_create.append(grade) for grade in grades ] [grade.pop("id") for grade in grades_to_create] LmsGrade.objects.bulk_create( [LmsGrade(**item) for item in grades_to_create] ) # test = [LmsGrade(**item) for item in grades_to_create] LmsGrade.objects.bulk_update( [ LmsGrade(id=item.get("id"), marks_obtained=item.get("marks_obtained"),grade_obtained=item.get("grade_obtained"),present=item.get("present")) for item in grades_to_update ], ["value"], batch_size=1000 ) qs = LmsGrade.objects.filter(exam__id=request.data.get("exam")) serializer = self.get_serializer(data=qs, many=True) serializer.is_valid(raise_exception=True) serializer.save() …