Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid username change through URL in django application
I am working on a basic django chat application where the user can login and then enter the room id to join a specific room where they can chat with other users. The room looks like this Chat login Now the problem is that if I change my username in URL to some other registered username then I am able to chat as if I am that user (By passing all the login). What changes I need to make to avoid this or the things that are to be added so that even if someone tries to attempt to change, it redirects it to the login page and after proper login only that person will be able to use that. I avoided the problem of accessing the unregistered user i.e. if someone enters the username that is not registered then he will not be able to chat with that username but it still is not redirecting them to login page. This code shows the above logic: def send(request): message = request.POST['message'] username = request.POST['username'] room_name = request.POST['room_name'] print("**********************************************************************") print(username) print(request) print("......................................................................") if(User.objects.filter(uname=username).exists()): #if(User.objects.filter(uname=username).is_authenticated) new_message = Message.objects.create(value=message, uname=username, rname=room_name) new_message.save() return HttpResponse('Message sent successfully') else: return redirect('/') Please suggest changes here … -
Django- How to replace list of items of a related set
I have table Group and UserConfig A group has many users, each user in a group has a config item UserConfig: unique (group_id, user_id) Example: class Group(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) class UserConfig(models.Model): id = models.BigAutoField(primary_key=True) group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='user_configs') user_id = models.IntegerField() config = models.JSONField() I want to replace all UserConfig instances of a group (update existing rows, add new rows and remove which rows are not in the new list) # list_replace_configs: List[UserConfig] group.user_configs.set(list_replace_configs, bulk=False, clear=False) This method not working because it uses method remove() remove(*objs, bulk=True): only exists if ForeignKey field has null=True if ForeignKey field has null=True: it does not removed UserConfig object, but just set user_config.group = None I don't understand why django designs this method. How to replace all UserConfig instances of a group ? -
Facing issue with django_admin_hstore_widget in production
at HTMLDocument.<anonymous> ((index):3024:36) at j (jquery.min.js:2:26911) at Object.fireWith [as resolveWith] (jquery.min.js:2:27724) at Function.ready (jquery.min.js:2:29518) at HTMLDocument.I (jquery.min.js:2:29709) This works fine in local server. -
Django get parameters deleted upon post request
On my page i have a users portfolio of items which they own. On this page 16 items can be displayed per page, so if the user has more than 16 items they will need to be able to navigate through pages 1,2,3, etc... To achieve this I use a form using the GET method which has two submit buttons, one for going back one page and another for going forward one page. The page number will be visible in the URL, http://127.0.0.1:8000/portfolio/?page=2 I also have a form using the POST method where a user can add items to their portfolio where they enter item_id, condition, quantity. My problem is when a user submits the POST form, the page number from the URL gets deleted and therefore puts the user back to page one as 1 is the default value in my get method in views.py. page = int(request.GET.get("page", 1)) How can i submit a POST form without deleting GET parameters from the URL and stay on the current page? portfolio.html <form action="{% url 'portfolio' %}" method="post"> <input type="hidden" name="form-type" value="add-item-form"> <!-- Inputs for name, condition, quantity --> <input type="submit" value="Add to Portfolio"> </form> <form action="{% url 'portfolio' %}" method="get"> … -
Django query to get frequency-per-day of events with a DateTimeField
I have a model with events that each have a DateTimeField and can readily write a query that gets me the count of events per day: MyEvents.objects.annotate(day=TruncDate('date_time')).values('day').annotate(count=Count('id')) which produces (Postgresql) SQL like: SELECT ("MyEvents"."date_time")::date AS "day", COUNT("MyEvents"."id") AS "count" FROM "Doors_visit" GROUP BY ("MyEvents"."date_time")::date which produces a QuerySet that returns dicts containing 'date' and 'count'. What I would like is to produce a histogram of such counts, by which I mean plotting hte 'count' as a category along the x-axis and the number of times we've seen that 'count' on the y-axis. In short, I want to aggregate the counts, or count the counts if you prefer. Alas, Django complains vehemently when I try: MyEvents.objects.annotate(day=TruncDate('date_time')).values('day').annotate(count=Count('id')).annotate(count_count=Count('count')) produces: django.core.exceptions.FieldError: Cannot compute Count('count'): 'count' is an aggregate Fair enough. Which raises the question, can this be done in one Django Query without resorting to Raw SQL? I mean in SQL it's easy enough to query the results of a query (subquerying). Django seems to lack the smarts for this (I mean, rather than complain it could just wrap the query to date as a subquery and build a query from there, but it elects not to). I mean, one work around is to … -
How to perform data validation from the DB and raise an nonFieldError in the form without saving using generic?
How best to perform data validation using Form_Class and CreateView. How to cause an error in the form and not lose the entered data. sing form_valid() or pre_save signal? HOW COULD IT BE USING DEF VIEW & RENDER if request.method == "POST": form = Buy_add_form(request.POST, instance=instance) if form.is_valid(): hasPrice = SellingPrice.objects.filter(item=form.instance.item, date=form.instance.date) if not hasPrice: form.save() return redirect("storage:index") else: form = Buy_add_form(instance=instance) return render(request, 'storage/add_flow.html', { 'form': form, }) I'm writing a small inventory application. Data on the price of each product should be recorded in the database no more than once a day. In this example, I'm trying to see if there is a record in the table for this product on the date specified in the form. If there is, I want to notify the user in the form and break the data saving process. I need to save the filled form data. MODELS.PY class SellingPrice(models.Model): date = models.DateField(blank=False) item = models.ForeignKey(Items, on_delete=models.PROTECT, blank=False) price = models.FloatField(blank=False) def __str__(self): return f"{self.date}_{self.item}_{self.price}" FORMS.PY class SetPrise_add_form(forms.ModelForm): date = forms.DateField(input_formats=['%d-%m-%Y'], initial=now().strftime('%d-%m-%Y'), widget=forms.DateInput(attrs={'data-mask': '00-00-0000'})) class Meta: model = SellingPrice fields = ["date", "item", "price"] VIEW.PY class setPrice(CreateView): form_class = SetPrise_add_form template_name = "storage/setPrise_create.html" success_url = reverse_lazy('storage:prices-view') def form_valid(self, form): last = SellingPrice.objects.filter(item=form.instance.item, … -
How to use getElementById in django
I'm trying to generate a code for editing posts using modal that are made before but it shows "Identifier or string literal or numeric literal expected" and "Statement expected" ERROR here is my code: ` function submitHandler(){ const textareaValue = document.getElementById("textarea_"${post.id}).value </script> <button type="button" class="btn btn-secondary"onclick=submitHandler({{post.id}}) > Save Changes</button> ` want to submit change to editing posts. -
how can i load another question from the database after i have clicked on a button
enter image description here I have a quiz game. After I click on the "Next" button (see picture), I want the next question to be loaded from the database. Only one question is currently displayed, but I don't know how to load more questions from the database. Summarized again: After clicking on the Next button, another question should be loaded from the database. I'm new to django, would be cool if someone could help me further views.py def quiz_math(request): if request.method == 'POST': questions = QuesModel.objects.filter(kategorie__exact="Math") score = 0 wrong = 0 correct = 0 total = 0 for q in questions: total += 1 answer = request.POST.get(q.question) print(answer) if q.ans == answer: score += 10 correct += 1 else: wrong += 1 percent = score / (total * 10) * 100 context = { 'score': score, 'time': request.POST.get('timer'), 'correct': correct, 'wrong': wrong, 'percent': percent, 'total': total, } return render(request, 'result.html', context) else: questions = QuesModel.objects.all() context = { 'questions': questions } return render(request, 'quiz_math.html', context) model.py class QuesModel(models.Model): Kategorie = ( ("Math", "Math"), ("Digital Skills", "Digital Skills"), ) kategorie = models.CharField(max_length=400, null=True, choices=Kategorie) user = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) question = models.CharField(max_length=200, null=True,) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, … -
IntegrityError at /accounts/ProfileRegister/ UNIQUE constraint failed: auth_user.id
I am creating a registration page, and after finishing the work, I received this error, everything is saved, but the information is not displayed in the profile section. I am a beginner. Views def ProfileRegisterView(request): if request.method=='POST': profileRegisterForm=ProfileRegisterForm(request.POST,request.FILES) if profileRegisterForm.is_valid(): user=User.objects.create_user( username=profileRegisterForm.cleaned_data['username'], email=profileRegisterForm.cleaned_data['email'], password=profileRegisterForm.cleaned_data['password'], first_name=profileRegisterForm.cleaned_data['first_name'], last_name=profileRegisterForm.cleaned_data['last_name'],) user.save(profileRegisterForm) profileModel=ProfileModel(user=user, profileImage=profileRegisterForm.cleaned_data['profileImage'], Gender=profileRegisterForm.cleaned_data['Gender'], Credit=profileRegisterForm.cleaned_data['Credit']) profileModel.save() return HttpResponseRedirect(reverse(ticketsale.views.concertListView)) else: profileRegisterForm=ProfileRegisterForm() context={ "formData":profileRegisterForm } return render(request,"accounts/ProfileRegister.html",context) template {% extends 'ticketsale/layout.html' %} {%block titlepage%} ثبت نام {% endblock %} {%block mainContent%} <form action="" method="POST" class="form form-control bg-dark p-5" enctype="multipart/form-data"> {% csrf_token %} {% comment %} {{ Concertform }} {% endcomment %} <div class="container"> <div class="row"> <div class="col-md-6"> <p class="form form-control">نام: {{ formData.first_name }}</p> <p class="form form-control">نام خانوادگی: {{ formData.last_name }}</p> <p class="form form-control">جنسیت : {{ formData.Gender}}</p> <p class="form form-control">مقداراعتبار : {{ formData.Credit }}</p> </div> <div class="col-md-6"> <p class="form form-control">ایمیل: {{ formData.email }}</p> <p class="form form-control">نام کاربری: {{ formData.username }}</p> <p class="form form-control">رمز عبور: {{ formData.password }}</p> {{ formData.profileImage }} </div> </div> </div> <button type="submit" class="btn btn-info">ثبت نام</button> </form> {% endblock %} Models class ProfileModel(models.Model): class Meta: verbose_name="کاربر" verbose_name_plural="کاربر" user=models.OneToOneField(User,on_delete=models.CASCADE,verbose_name="کاربری",related_name="profile") # Name=models.CharField(max_length=100,verbose_name="نام") # Family=models.CharField(max_length=100,verbose_name="نام خانوادگی") profileImage=models.ImageField(upload_to="profileImage/",verbose_name="عکس") Man=1 Woman=2 status_chioces=((Man,"مرد"),(Woman,"زن")) Gender=models.IntegerField(choices=status_chioces,verbose_name="جنسیت") Credit=models.IntegerField(verbose_name="اعتبار",default=0) forms class ProfileRegisterForm(forms.ModelForm): first_name=forms.CharField(max_length=100) last_name=forms.CharField(max_length=100) username=forms.CharField(max_length=100) password=forms.CharField(widget=forms.PasswordInput) email=forms.CharField(widget=forms.EmailInput) class Meta: model=ProfileModel fields=['profileImage','Gender','Credit'] I expect that after … -
How to solve the error "could not install packages due to an OSError: [Errno 2] No such file or directory" after trying to install requirements.txt
After updating Python to the latest version, previous files were over-written and I was left with this error when trying to run: pip install -r requirements.txt Error: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/System/Volumes/Data/SWE/Apps/DT/BuildRoots/BuildRoot1/ActiveBuildRoot/Library/Caches/com.apple.xbs/Sources/python3/python3-124/altgraph-0.17.2-py2.py3-none-any.whl' How would one go about solving or understanding the approach to fixing this issue? I am not quite sure where to begin, so any help would be really appreciated. I should be expecting the line to run without any errors and the web app should be able to run as well, but I encountered the previous error. When I ran: python manage.py runserver I encountered this error too: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
django-filters - field_labels not working for OrderingFilter
There is a model: class Calendar(models.Model): ... vendor_code = models.TextField() ... FilterSet class: from django_filters import OrderingFilter from django_filters.rest_framework import FilterSet, DjangoFilterBackend class CalendarFilter(FilterSet): ordering = OrderingFilter( fields=( ('vendor_code', 'vendor_code'), ), field_labels={ 'vendor_code': 'Vendor code', } ) class Meta: model = Calendar fields = ['vendor_code'] The view: class CalendarsView(mixins.ListModelMixin, GenericViewSet): ... filter_backends = (DjangoFilterBackend,) filterset_class = CalendarFilter I expected that if define field_labels param the label Vendor code would appear in swagger but there is only ordering without any description: What am I doing wrong? -
Trying to add a field to Django many-to-many relation
Right now I'm working on django project responsible for warehouse mangement system. I got product, customers, warehouse-branches, product type, orders, etc... products can be [Milk 1L bottle, cheese 500g pack, ....] The problem I been facing is that I'm trying to make a many-to-many relation between orders and products so I can track the products sold in each order. Yet, I want to add 'amount' coloumn to that table created by many-to-many because a customer can order 5 cheese packs and 2 milk bottles. I know that I can add 'ManyToManyField.through' but it takes string for a model as args and that's what i don't want. I wish to easily have extra IntegerField called amount. Here's how i wish my table to look-like enter image description here -
What are json.loads and json.dumps function doing?
class Realm(models.Model): server = models.ForeignKey(Server, related_name='realms', on_delete=models.CASCADE) name = models.CharField(max_length=255, unique=True, help_text='Name as known on the Keycloak server. ' 'This name is used in the API paths ' 'of this Realm.') _certs = models.TextField() @property def certs(self): return json.loads(self._certs) @certs.setter def certs(self, content): self._certs = json.dumps(content) I just wanted to know what is the (_) underscore is doing there and what is happing in this model with json.loads and json.dumps -
How to delete object using Django Inline Formset
I am having a trouble with deleting an object in inline formset. The formset is not saving if there are objects to be deleted, but it just works properly when there is not. Here is my views.py: def submission(request): if request.method == "POST": formset = AuthorFormSet(request.POST) form = thesisForm(request.POST, request.FILES) if form.is_valid() & formset.is_valid(): thesis = form.instance.thesis_id title = form.instance.title form.instance.uploaded_by = request.user # set the user thesis = form.save() # save the form for obj in formset.deleted_objects: obj.delete() for forms in formset: forms.instance.thesis = thesis forms.save() else: form = thesisForm() formset = AuthorFormSet() return render(request,'StudentSubmitProject.html',{'form':form, 'formset':formset,}) And this is my template: <form method="POST" class="mt-5 form-group profile_form" enctype="multipart/form-data"> {% csrf_token %} <h4 class="textmaroon mt-5">Describe the thesis</h4> <p>Define the thesis project</p> <hr></hr> {{form.as_p}} <h4 class="textmaroon mt-5">Add Author</h4> <p>Input the authors of the thesis</p> <hr></hr> {% for forms in formset %} <div class="d-flex flex-wrap justify-content-between">{{forms.as_p}}</div> <hr class="text-muted"></hr> {% endfor %} {{ formset.management_data }} <div class="row mt-5"> <hr></hr> <div class="col-md-12"> <button type="submit" class="btn btn-danger float-end">Submit</button> <button type="reset" class="btn btn-secondary me-2 float-end">Reset</button> </div> </div> </form> -
Django form with Jstree checkbox ( Jquery Array)
I try to use Jstree checkbox in a Django form, but Jquery array is stopped by form is_valid() method : La valeur « 584a6392-8958-40c8-b318-77c1d2df623d,a9f2deec-eda2-4c43-a080-cd070e9ff25f » n’est pas un UUID valide. This code run if i choose only a checkbox HTML <input type="hidden" name="regroupements" id="regroupements" value=""> <div id="kt_docs_jstree_basic"> <ul> <li value="584a6392-8958-40c8-b318-77c1d2df623d"> Groupe 1 </li> <li value="a9f2deec-eda2-4c43-a080-cd070e9ff25f"> Groupe 2 </li> </ul> </div> JS $(function () { $('#kt_docs_jstree_basic').jstree(); $("#kt_docs_jstree_basic").on("select_node.jstree", function(e){ var selected_regroupements = []; var selectedIndexes = $("#kt_docs_jstree_basic").jstree("get_selected", true); $.each(selectedIndexes,function () { selected_regroupements.push(this['li_attr'].value); }); $("#regroupements").val(selected_regroupements) } ); }); ViEWS.PY def post(self, request, **kwargs): context = super().get_context_data(**kwargs) context = KTLayout.init(context) form = forms.UtilisateursAddUpdate(request.POST, request.FILES) choices = request.POST.getlist("regroupements") if form.is_valid(): instance = form.save(commit=False) ... instance.save() for item in choices: instance.regroupements.add(item) I don't understand why this code run with one checkbox "checked" but not with more. How should i change my code ? -
I want to save the content from the ai and show it to the frontend
i am creating an AI using openai in django and have made a basic page, now i awant to save the response and show the response to the front-end, just like a chat bot here is my views.py: from django.shortcuts import render, redirect import openai from django.http import HttpResponse from django.views import View from myapp.models import Chat from myapp.forms import ChatForm from django.contrib import messages # Create your views here. openai.api_key = "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" start_sequence = "\nA:" restart_sequence = "\n\nQ: " def home(request): return render(request, "home.html") def chatbot_response(user_input): response = openai.Completion.create( engine="text-davinci-003", prompt=user_input, temperature=0.7, max_tokens=256, top_p=1, best_of=4, frequency_penalty=0, presence_penalty=0, ) return response["choices"][0]["text"] class ChatbotView(View): def post(self, request): user_input = request.POST["user_input"] response = chatbot_response(user_input) context={ 'response':response, } return render(request, "home.html",context) Here is the models.py: from django.db import models # Create your models here. class Chat(models.Model): question = models.TextField() answer = models.TextField() Here is the forms.py: from django import forms from myapp.models import Chat class ChatForm(forms.ModelForm): # validations can be set here class Meta(): model = Chat fields = ['question', 'answer'] here is the urls: from django.contrib import admin from django.urls import path from myapp.views import chatbot_response, home, ChatbotView urlpatterns = [ path('admin/', admin.site.urls), path('', home, name="home"), path('chatbot/', chatbot_response, name="user_response"), path('user_response/', ChatbotView.as_view(), name="chatbot"), … -
Is it possible to make Django switch model variables based on a language?
I have a model with two columns where one is in English, one is in Bulgarian. Currently I am doing this: {% if L == "bg" %} {{adoption.fields.story_bg|safe}} {% else %} {{adoption.fields.story_eng|safe}} {% endif %} But this is too much code and it is annoying to type and look at. Is there a simpler way of doing this? -
How can I combine 2 different models with union?
I want to combine the results of the queries of two different models with unnion, but my sql code is different, I need your help in this regard. Exception is Unable to get repr for <class 'django.db.models.query.QuerySet'> django.db.utils.ProgrammingError: UNION types numeric and character varying cannot be matched LINE 1: ...order"."update_date", "core_filled"."status", "core_trig.. custom_qs = active_qs.annotate(**{'order_numberx': F('order_number'), 'condition_side': Value('GTE', output_field=CharField()), }).values("order_number", "account_id", "order_type", "price", "buy_sell", "status", "add_date", "update_date", "status", "condition_side", "total_price") filled_qs = trigger_qs.annotate(**{'order_numberx': F('order_number'), 'total_price': Value(0, output_field=DecimalField()) }).values("order_number", "account_id", "order_type", "price", "buy_sell", "status", "add_date", "update_date", "status", "condition_side", "total_price") orders_qs = active_qs.union(trigger_qs) SQL QUERY (SELECT "core_custom"."order_number", "core_custom"."account_id", "core_custom"."order_type", "core_custom"."market_code", "core_custom"."channel_code", "core_custom"."price", "core_custom"."volume", "core_custom"."volume_executed", "core_custom"."buy_sell", "core_custom"."status", "core_custom"."add_date", "core_custom"."update_date", "core_custom"."client_id", "core_custom"."post_only", "core_custom"."status", "core_custom"."total_price", GTE AS "condition_side" FROM "core_custom" WHERE ("core_custom"."account_id" = 1549 AND "core_custom"."status" IN (N, P))) UNION (SELECT "core_filled"."order_number", "core_filled"."account_id", "core_filled"."order_type", "core_filled"."market_code", "core_filled"."channel_code", "core_filled"."price", "core_triggerorder"."volume", "core_filled"."volume_executed", "core_filled"."buy_sell", "core_filled"."status", "core_filled"."add_date", "core_filled"."update_date", "core_filled"."client_id", "core_filled"."post_only", "core_filled"."status", "core_filled"."condition_side", 0 AS "total_price" FROM "core_filled" WHERE ("core_triggerorder"."account_id" = 1549 AND "core_filled"."status" = N)) how can i edit order in sql query Combining the results of two queries and returning. I changed the value rows -
I/O operation on closed file. when trying to read a file content on django model save()
This is my Django Model where I'm trying to store the content of an uploaded file in field attachments: class CsvFile(models.Model): processed = models.BooleanField(default=False) uid = models.UUIDField(unique=True, default=str(uuid4())) date = models.DateField(null=False, default=datetime.datetime.now().date()) time = models.TimeField(null=False, default=datetime.datetime.now().time()) original_filename = models.CharField(max_length=600, blank=True) attachment = models.TextField(blank=True) file = models.FileField(upload_to=f"csv/", blank=True) def save_file_content_to_attachment(self, file): try: with file.open('r') as f: self.attachment = f.read() except (FileNotFoundError, ValueError): self.attachment = '' def save(self, *args, **kwargs): # Save the uploaded file to the csv_path field self.original_filename = self.file.name # Print a message to help troubleshoot the issue print(f"Saving file content to attachment for file {self.file.name}") # Save the file content to the attachment field self.save_file_content_to_attachment(self.file) super(CsvFile, self).save(*args, **kwargs) def delete(self, *args, **kwargs): # Delete the file from storage try: default_storage.delete(self.file.name) except FileNotFoundError: pass # File does not exist, so we can ignore the exception super(CsvFile, self).delete(*args, **kwargs) Unfotunately an upload of a file fails with I/O error Can somebody shed light into why this is not working? -
How to safely update the balance field in django
I need to use a wallet model in my project. If I need to update the balance of the wallet, what is the safest way to do it? For example, if different threads or different processes increase the balance of the wallet at the same time, will there be any problems? class Wallet(models.Model): balance = models.DecimalField(_('Balance'), max_digits=18, decimal_places=8, default=0) def withdraw(self,amount): self.balance = self.balance - amount def deposit(self,amount): self.balance = self.balance + amount Is this model above safe? If not, what is the best practice? -
Jinja code rendered using ajax is enclosed witin doublequorts in django project
I am developing a todo app using django as backend and html,css,bootstrap for frontend, I used Ajax in this project to load data from server without refresh. **Look at the image ** the {%csrf_token%} is passed through ajax but is is renderd in html page as a text within a double quort. How to fix this I want to render the {%csrf_token%} in the webpage without double quorts. Ajax code $.ajax({ type:'POST', url:'/task/'+todo_id+'/new_todo/', processData: false, contentType: false, data: data, success: function(response){ console.log("**********Data send to backend"); var new_id = response['new_id']; var new_color = response['new_color']; var new_status = response['new_status'] var new_todo_note = response['new_todo_note'] if (new_todo_note == null){ my_note = " " } else{ my_note = new_todo_note } $("#"+todo_id).hide(); $.ajax({ type:'GET', url:'/task/'+todo_id+'/new_todo/', data:data, dataType:'json', success: function(response){ var todo_section = `<ol class="list-group mb-3 v1" id="${response.latest_todo.id}right"> <li class="list-group-item d-flex justify-content-between align-items-start"> <div class="ms-2 me-auto d-flex"> <div> <div class="fw-bold">${response.latest_todo_name}</div> <p style="font-size: x-small; margin:0;">${response.latest_todo_added_date}</p> <div style="max-width: 100px; display:flex; "> <div id="${new_id}task_note"> ${my_note} </div> </div> </div> <div class="mt-1 ms-4"> <a href="{%url 'todo-details' todo.id%}"> <i class="fa-solid fa-arrow-up-right-from-square text-muted"></i> </a> </div> </div> <div class="d-flex flex-column"> <div style="align-self: flex-end;" id="${new_id}badge_live"> <span class="badge rounded-pill" id="${new_id}badge" style="background-color:${new_color};">&nbsp&nbsp&nbsp </span> </div> <div class="mt-2 d-flex"> <div class="me-2"> <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#exampleModal" style="font-size: xx-small;"> Note … -
changes in views.py are not reflected in html page
I have noticed that my modifications in views.py function are reflecting in my html page after some hours. But if I make further modifications in the function, it is not getting reflected. Is there any logic behind that in django? I have a file called templates/app/token.html and a views.py where I have def token which will render to token.html. when I created that function for the 1st time it worked. After that however I make changes to the views function, it was not reflected in the html file. When I opened that html file after hours, the changes were reflected in the html page. Now I'm trying to make changes, but it is not reflecting as before. Is there any reason in django where this kind of behaviour will be observed in the templates files and is there any solution to it? -
django.db.utils.OperationalError: (1054, "Unknown column 'django_migrations.app' in 'field list'")
I have Django project it was on local server and shifted to cloud host and I want want to transfer my database from Postgres (local) to MySQL , but when I transferred using third party it shows this error when I run it on server how can I solved this issue -
Unable to install mysqlclient in django
I am using the latest python version 3.11 in django framework, for that I need to install mysqlclient . But there was error when I try to install pip install mysqlclient Output like this as error: Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win32-cpython-311 creating build\lib.win32-cpython-311\MySQLdb copying MySQLdb_init_.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\release.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\times.py -> build\lib.win32-cpython-311\MySQLdb creating build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-cpython-311\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools / [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to … -
trigger a function only once per user
I have an application where each user who has previously authenticated can access the index.html page with a button to trigger a time.sleep(t) function. What I would like is that the same user cannot retrigger the function. urls.py from . import views from django.contrib.auth.decorators import login_required urlpatterns = [ path('page1', login_required(function=views.page1, login_url="login"), name="page1"), ] views.py def page1(request): if(request.GET.get("arg")=="nap" and request.session.get("nap") == None): request.session["nap"] = True sleep(1, 5) request.session["nap"] = None return render(request, 'page1.html') def sleep(t, n): for i in range(0,n): time.sleep(t) print(f"nap n°{i}") index.html <button type="button"> <a href="{% url 'page1' %}?arg=nap"> NAP </a> </button>