Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - show bootstrap modal after successful save data to db
I'm new to Django and at this point , i set up a very simple post article page, i hope that when i successfully save the article, it will show the message of the bootstrap modal style model.py from django.db import models from django.utils import timezone class Article(models.Model): title = models.CharField(max_length=100,blank=False,null=False) slug = models.SlugField() content = models.TextField() cuser = models.CharField(max_length=100) cdate = models.DateField(auto_now_add=True) mdate = models.DateField(auto_now=True) forms.py from .models import Article from django.forms import ModelForm class ArticleModelForm(ModelForm): class Meta: model = Article fields = [ 'title', 'content', ] views.py from django.shortcuts import render from .forms import ArticleModelForm from django.contrib.auth.decorators import login_required from .models import Article @login_required def create_view(request): form = ArticleModelForm(request.POST or None) context={ 'form':form } if form.is_valid(): article_obj = Article(cuser=request.user) form = ArticleModelForm(request.POST,instance=article_obj) form.save() context['saved']=True context['form']=ArticleModelForm() return render(request,'article/create.html',context= context) my template > article/create.html {% extends 'base.html' %} {% block content %} <form method="POST"> {% csrf_token %} {{form.as_p}} <div><button data-bs-toggle="modal" data-bs-target="#saveModal" type="submit">create</button></div> </form> {% if saved %} <div class="modal fade" id="saveModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h3>save successfully!</h3> <button type="button" class="btn-close" data-bs-dismiss="modal"> </button> </div> </div> </div> </div> {% endif %} {% endblock content %} I use the saved variable in views.py to determine whether the content of the article … -
Is there a Python function I can use for a condition like "If condition is still true after (3) seconds then dosomething"(
I am running a opencv through django and trying to save the data in sqlite. I tried to use the sleep() in library time, but it only prevents my web app from running. color = (0, 0, 255) time.sleep(3) if color == (0, 0, 255): save time -
Django - get original object values in form_valid for UpdateView?
Using Django's UpdateView, I'm looking to update a version number if certain fields in the form.instance are actually updated. This requires comparing the values of these fields to the original value before the user set the updated value. In form_valid, is it possible to access the original object's values before the updating occurred? -
Django: usage of prefetch_related
I have some models with this relation: EmailReport --many-to-many--> PaymentReport --foreign-key--> Shop --many-to-many--> users Now I want to reach the users from EmailReport. I tried this query but failed: query = models.EmailReport.objects.prefetch_related('payment_report').prefetch_related('shop__users').filter(pk__in=ids) Anyone knows the correct query? -
JSONDecodeError when using json.loads
I am getting Expecting value: line 1 column 1 (char 0) when trying to use json.loads Went through similar questions but couldn't find a solution for my code. It gives the error for line: body = json.loads(body_unicode) network.js: //When user clicks the save button save_button.addEventListener("click", event => { new_content = document.getElementByID(`new_content_${postID}`); //Make fetch request to update the page fetch(`/edit/${postID}`,{ method: "POST", body: JSON.stringify({ content: new_content.value, }) }) .then(response => { if(response.ok || response.status == 400) { return response.json() } else { return.Promise.reject("Error:" + response.status) } }) .then(result => { new_content.innerHTML = result.content; cancelEdit(postID); }) .catch(error => { console.error(error); }) }) views.py: def edit(request, id): if request.method == "POST": body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) new_content = body['content'] AllPost.objects.filter(id = id).update(content = new_content) return JsonResponse({"message": "Post updated successfully.", "content": new_content}, status=200) return JsonResponse({"error": "Bad Request"}, status = 400) index.html: {% for post in page_obj %} {{ post.full_name|upper }}<br> <div class="frame"> <h4><a href="{% url 'profile' post.user.username %}" style="color: black;">{{post.user.username}}</a></h4> {% if post.user == user %} <button class="btn btn-sm btn-outline-primary" data-id="{{post.id}}" id="edit_button_{{post.id}}">Edit</button> {% endif %} <div id="content_{{post.id}}">{{post.content}}</div> <form action="{% url 'edit' post.id %}" method="post" id="edit_form_{{post.id}}" style="display: none;"> {% csrf_token %} <div class="form-group"><textarea id="new_content_{{post.id}}" name="new_content" cols="30"></textarea></div> <input class="btn btn-sm btn-success" id="save_{{post.id}}" type="submit" value="Save"> <input … -
How to access foreignkey table fields in template using django
` models.py class Locations(models.Model): region = models.ForeignKey(Regions, on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=255) class Regions(models.Model): region_name = models.CharField(max_length=255) serializer.py class LocationsSerializer(serializers.ModelSerializer): region = RegionSerializer() class Meta: model = Locations fields = "__all__" views.py def loc_reg(request): locations = Locations.objects.select_related('region').values('name','region__region_name') data = LocationSerializer(locations,many=True) return response.Response(data,status.HTTP_200_OK) template: <script> methods:{ fetchList(){ this.$axios.$post('/projects/loc_reg',config).then(response => { if(response){ this.locations =response.data; for(let i=0;i <this.locations.length; i++){ this.x=this.locations[i].name this.y=this.locations[i].region_name this.z=this.y + "-" +this.x this.result.push(this.z) } </script> After serialization I am getting null value in region_name. I am getting null in my template while try to get region_name.why so?`` -
how to resize an image and save it to storage using save function
how can i modify my save function to solve this problem ? i have a storage and when i wanted to upload an image i encountered this error . -
Django how to get days count of month in specific year [duplicate]
class MainYear(models.Model): year = models.CharField(max_length=4,blank=True,null=True,default=get_current_year()) def __str__(self): return str(self.year) @property def get_all_month(self): return self.MainMonth.all() def get_absolute_url(self): return reverse("agenda:ajax_month", kwargs={"pk": self.id}) class MainMonth(models.Model): main_year = models.ForeignKey(MainYear,on_delete=models.CASCADE,blank=True,null=True,related_name="MainYear") month = models.PositiveSmallIntegerField (validators=[MaxValueValidator(12)],default=1,blank=True,null=True) day_count = models.PositiveSmallIntegerField (validators=[MaxValueValidator(31)],blank=True,null=True) def __str__(self): return str(self.month) @property def get_day_count(self): # year = self.__main_year.year() year = self.objects.all().filter(main_year__MainYear_year='MainYear_year') for y in year: yea_to_days = self.year # You already have it days_count = monthrange(int(yea_to_days),int(self.month))[1] self.day_count = days_count return self.day_count My problem is i want if i select year like 2024 it should be in February 29 days how to make it i will be save it auto by using save method django python year month days -
how to implement autocomplete Search bar for a table in django
if i have a table of 4 team(python, java, php, ruby) and each team have 4 project then i searched py for python team in search bar and each bar show team name and then i select python then it filter the table and shows python team projects this is api `def searchteam_name(request): if request.method == 'GET': filterData2 = request.GET.get("query") try: u = TeamAndManager.objects.filter(name__istartswith = filterData2)#.filter(team__name = url[0]) print('<<<<<99999999999999999999>>>',u) except: print('<<<<<<<88888888>>>>>') pass if len(u) > 0: d = {} count = 0 for i in u: team_addon = {f'{count}' : f'{i.name}'} count = count +1 d.update(team_addon) else: d = { '0' : 'No Team Found' } return JsonResponse(d)` model.py `class TeamAndManager(models.Model): name = models.CharField(max_length=20,blank=False, null=False) manager = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{} : {}'.format(self.name, self.manager)` -
how to hide some field based on the forms.select django
i want to hide some fiel when the user will select an option, but when i'm trying to do so, it does not work, i don't know if i forget something in my code or if i make a mistake but i've tried many things and it does not work in my model i have a choices with "IN" and "Out" so what i want is when OUT is selected some field of my forms to be hidden, else to show the whole form. here is my model.py CHOICES = ( ("1", "IN"), ("2", "OUT") ) class addReport(models.Model): heure = models.TimeField(auto_now_add=True) mouve = models.CharField(max_length=12, choices = CHOICES) nom_Visiteur = models.CharField(max_length=26) fonction = models.CharField(max_length=26) service = models.CharField(max_length=26) motif = models.CharField(max_length=26) phoneNumber = models.CharField(max_length=12, unique= True) here is my forms.py from django import forms from .models import addReport from django.forms import ModelForm class PostForms(forms.ModelForm): class Meta: model = addReport fields = ('mouve','nom_Visiteur','fonction','service','motif','phoneNumber') widgets = { 'mouve': forms.Select(attrs={'class': 'form-control'}), 'nom_Visiteur': forms.TextInput(attrs={'class': 'form-control'}), 'fonction': forms.TextInput(attrs={'class': 'form-control'}), 'service': forms.TextInput(attrs={'class': 'form-control'}), 'motif': forms.Textarea(attrs={'class': 'form-control'}), 'phoneNumber': forms.TextInput(attrs={'class': 'form-control'}), } def __init__(self, data=None, *args, **kwargs): super().__init__(data, *args, **kwargs) # If 'later' is chosen, mark send_dt as required. if data and data.get('mouve', None) == self.OUT: self.fields['fonction'] = forms.HiddenInput(), self.fields['service'] … -
How can I concatenate two different model query and order by a field that both models has
How can I concatenate two different model query and order by a field that both models has like progress fields. For example models.py class Gig(models.Model): author= models.ForeignKey(User) title = models.CharFields() progress = models.IntegerField() class Project(models.Model): author= models.ForeignKey(User) title = models.CharFields() progress = models.IntegerField() Can I do my view.py like this, for me to achieve it? İf No, How can I achieve it? views.py def fetch_all_item(request): gig = Gig.objects.filter(author_id = request.user.id) project = Project.objects.filter(author_id = request.user.id) total_item = (gig + project).order_by("progress") return render(request, "all_product.html", {"item": total_item}) I am trying to join two query set from Gig and Project models then send it to frontend in an ordering form by a field name called progress. -
How to deploy django based website running on a docker compose to my local home network?
I have the following setup: docker-compose.yml # Mentioning which format of dockerfile version: "3.9" # services or nicknamed the container services: # web service for the web web: # you should use the --build flag for every node package added build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: python manage.py runserver 0.0.0.0:8000 volumes: - type: bind source: . target: /code ports: - "8000:8000" depends_on: - db environment: - "DJANGO_SECRET_KEY=django-insecure-m#x2vcrd_2un!9b4la%^)ou&hcib&nc9fvqn0s23z%i1e5))6&" - "DJANGO_DEBUG=True" expose: - 8000 db: image: postgres:13 # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - "POSTGRES_HOST_AUTH_METHOD=trust" # - "POSTGRES_USER=postgres" # Volumes set up volumes: postgres_data: and a settings file as ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1'] #127.0.0.1 is my localhost address. With my local wifi service's router IP as 192.168.0.1 Can you please help me deploy the django site on my local network? Do I have to set up something on my router? Or could you direct me towards resources(understanding networking) which will help me understand the same. -
django sqs makes request slower
Just installed sqs with django and celery to do background tasks like sending notifications and firebase messages I was using redis and it was fast when installed sqs the code is not async anymore, the errors even appear in the server terminal not the celery one! here's my settings.py CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "us-east-1", } CELERY_BROKER_TRANSPORT = 'sqs' CELERY_BROKER_URL = f"sqs://{AWS_ACCESS_KEY_ID}:{AWS_SECRET_ACCESS_KEY}@" CELERY_TASK_DEFAULT_QUEUE = "hikeapp" CELERY_RESULT_BACKEND = None CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' when moved back to redis it became fast again, what am I doing wrong? -
Setting up wildcard subdomain dynamically
I have a domain example.com. For each user, I want to dynamically create a subdomain for them. Say for user1, it will have user1.example.com. For user2, it will have user2.example.com. -
404 error not found when debug = False in django multilanguages web app
Hello I am making a multilanguages django web app, When DEBUG = True => the multilanguages works fine means when i click on localhost:8000 it redirect me to localhost:8000/en or the last language I am puting anyway. When DEBUG = FALSE => I enter to localhost:8000 it gives me an error of 404 not found, here is my setting.py: I am puting the '*' because I am testing if possible to work anyway I am testing all. ALLOWED_HOSTS = ['localhost','localhost:8000','127.0.0.1','127.0.0.1:8000','*'] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', ('English')), ('ko', ('Korean')), ] here is my urls.py from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns ( path('admin/', admin.site.urls), path('', include('app1.urls')), path('', include('app2.urls')), ) handler404='app1.views.handle_not_found' in my app1 urls.py urlpatterns = [ path('',views.index,name="index"), ] in debug = False it doesn't work so it doesn't know the path of locahost:8000 only it knows only localhost:8000/en how can I do so whenever. -
Django: normalize/modify and field in serializer
I have a model serializer like this: class FoooSerializers(serializers.ModelSerializer): class Meta: model = Food fields = [ 'id', 'price',] Here I have the price with trailing zeros like this: 50.000 and I want to .normalize() to remove the trailing zeros from it. Is this possible to do that in this serializer? -
Is it possible to update a value of a Typescript variable from external code in an html file?
in the .ts file: function showOrHideWarehouseTable(all_warehouses_table: string) { const checkBox = document.getElementById( "edit-" + all_warehouses_table ) as HTMLInputElement | null; if (checkBox != null) { if (checkBox.checked == true) { let table = document.getElementById("main-table"); let inside_table = document.createElement("table"); inside_table.setAttribute( "id", "warehouse-table-" + all_warehouses_table ); table.append(inside_table); let warehouse_table_row_0 = inside_table.insertRow(0); let cell0 = warehouse_table_row_0.insertCell(0); in the .html file: <script> let warehouse_table_row_0_cell_0 = ` {{ form.inventory_summary_as_skids_final_number.label }} `; cell0.innerHTML = warehouse_table_row_0_cell_0 </script> is this possible with some configuration? FYI I am trying to capute the django render code -
Django serialize function returns error JSONEncoder.__init__() got an unexpected keyword argument 'fields'
I'm trying to serilize my salesnetwork.agency model into a geojson file, and according to Django docs I'm using the following code: markers = Agency.objects.all() geojson_file = serialize("geojson", markers, geometry_field="location", fields=("province",) ) But this code results in the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Vahid Moradi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\Vahid Moradi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\.venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) ... return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\navidmotor\urls.py", line 5, in <module> path("", include("core.urls")), File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\.venv\lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "C:\Users\Vahid Moradi\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in … -
I cant add item via django admin panel
when i try to add remove or change something by djangos admin panel i get IntegrityError at /admin/app/place/2/delete/ FOREIGN KEY constraint failed Models.py class User(AbstractUser): pass class Currency(models.Model): name = models.CharField(max_length=64) sign = models.CharField(max_length=64) def __str__(self): return self.name class Place(models.Model): name = models.CharField(max_length=64, blank=True, null=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE, blank=True, null=True, related_name="currency") fb = models.CharField(max_length=128, blank=True, null=True) ig = models.CharField(max_length=128, blank=True, null=True) address = models.CharField(max_length=128, blank=True, null=True) wifi = models.CharField(max_length=32, blank=True, null=True) phone = models.CharField(max_length=16, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="creator") def __str__(self): return self.name Admin.py admin.site.register(User) admin.site.register(Currency) admin.site.register(Place) i tried to remove an item and it gives me this error -
absolute path problem with saving image to s3 storage [closed]
when I want to create a new post from adminpanel and add an image file this happens .i searched but i couldn't solve the problem . i would be happy if you help -
Send Choices in Serilizer Django
models.py: class Distributor(models.Model): class ModeChoices(models.IntegerChoices): physical = 1, _('physical') digital = 2, _('digital') class StatusChoices(models.IntegerChoices): publish = 1, _('publish') pending = 2, _('pending') dont_publish = 3, _('dont_publish') serializers.py: modes = serializers.DictField(source=Distributor.ModeChoices.choices) not working ... -
I want to make a employee attendance and payroll management system in django . can anyone help me to design a database for the same
I want to design the database but I have no clue and this is my first project in college, I recently learn Django but to make a database for a real time project is very confusing for me . My task is to :- create login/sign up store Different businesses with different id of each business name create 2 roles :-employees and employer ,for every company (a user can work in more than one company with different roles) keep track of their attendance and salary -
Elasticsearch error: unavailable_shards_exception
I implemented elastic search in my django project. However due to an issue i had to uninstall my old mysql and instal again in my laptop. So had to create new db for the project. After that from today i see the following error when i try to create a new product. I cannot understand the error. Any help would be appreciated. Exception Type: BulkIndexError Exception Value: ('1 document(s) failed to index.', [{'index': {'_index': 'products', '_id': '13', 'status': 503, 'error': {'type': 'unavailable_shards_exception', 'reason': '[products][0] primary shard is not active Timeout: [1m], request: [BulkShardRequest [[products][0]] containing [index {[products][13], source[{"name":"test"}]}] and a refresh]'}, 'data': {'name': 'test'}}}]) I tried to update my documents file. But still the problem persists. I tried to restart elastic search. Still i have the same problem. However everything works fine in server. Only in local i face this problem. I am confused if it was caused because of using new db. -
How can I display something from data base after multiple criteria is satisfied in django
Here i have a Model Recommenders: ` class Recommenders(models.Model): objects = None Subject = models.ForeignKey(SendApproval, on_delete=models.CASCADE, null=True) Recommender = models.CharField(max_length=20, null=True) Status = models.CharField(null=True, max_length=8, default="Pending") Time = models.DateTimeField(auto_now_add=True) ` And another model Approvers: ` class Approvers(models.Model): objects = None Subject = models.ForeignKey(SendApproval, on_delete=models.CASCADE, null=True) Approver = models.CharField(max_length=20, null=True) Status = models.CharField(null=True, max_length=8, default="Pending") Time = models.DateTimeField(auto_now_add=True) ` And my SendApproval model as: ` class SendApproval(models.Model): Subject = models.CharField(max_length=256) Date = models.DateField(null=True) Attachment = models.FileField(upload_to=get_file_path) SentBy = models.CharField(null=True, max_length=100) Status = models.CharField(null= True, max_length=8, default="Pending") ` Now my problem is that I have to display the Subject and Attachment from SendApproval table only when all the recommenders Status in Recommenders table related to that subject is "Approved" Don't know how can i know that..Thanks in advance... Actually not having any Idea but the best answer will be appreciated...By the way I am new to StackOverflow...So please let me know it there is some ambiguity in my question. -
How to add an argument to a function in a python .bat file
I have a file with a function and a file that calls the functions. Finally, I run .bat I don't know how I can add an argument when calling the .bat file. So that the argument was added to the function as below. file_with_func.py def some_func(val): print(val) run_bat.py from bin.file_with_func import some_func some_func(val) myBat.bat set basePath=%cd% cd %~dp0 cd .. python manage.py shell < bin/run_bat.py cd %basePath% Now I would like to run .bat like this. \bin>.\myBat.bat "mystring" Or after starting, get options to choose from, e.g. \bin>.\myBat.bat >>> Choose 1 or 2 >>> 1 And then the function returns "You chose 1"