Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration error: App doesn't provide model
I have a situation where I have to move a model from app B to app A. For this I created 3 migrations: An auto migration that creates the "destination" model for all the data in the old model A manual migration that deletes the model from app B Another manual migration that creates a ProxyModel where the deleted model was (so other apps can still find the moved model in the place it was) I renamed the table and faked the creation of the destination model, I also faked the deletion of the moved model (because those were done directly in the DBMS, so I wouldn't lose data) but I'm stuck in the last step because when I try to run the migration that creates the proxy model, the other models that had relations to the moved model complain that app B doesn't provide the (now moved) model: ValueError: The field b_app.BModel.afield was declared with a lazy reference to 'b_app.moved_model', but app 'b_app' doesn't provide model 'moved_model'. What can I do? -
media folder images are not displaying in Template Page
I'm new to Django. Medial folder images are not displaying in Template file. please help me in that. models.py class Images(models.Model): image = models. ImageField(upload_to='images', blank=True, null=True) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ ...... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def image_display(request): image_obj = Images.objects.all() return render(request, 'index.html', {'image_obj': image_obj}) index.html <body> {% for item in myoffers_objs %} <div> <img src="{{ item.image.url }}" alt="Images"/> </div> {% endfor %} </body> Project details where i did mistake. why its displaying like this. Image displaying like this -
TypeError missing 'base_field' at inspectdb
django 2.2.1 I created database via sql code and want to get model via inspectdb. The column was created as times VARCHAR[] When i run inspectdb > models.py i get: times = ArrayField(blank=True, null=True) #This field type is a guess TypeError: __init__() missing 1 required positional argument 'base_field' The models.py file was created as empty file. How to solve? -
DRF ImageField Inconsistent behavior
I'm creating a Django API with DRF. I have a custom User Model like this : models.py : from typing import Type, List from uuid import uuid4 from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from django_extensions.db.models import TimeStampedModel from main.apps.user.managers import UserManager def to_profile_picture(instance: "User", filename: str) -> str: return f"profile_pictures/{instance.email}/{uuid4()}_{filename}" class User(AbstractBaseUser, TimeStampedModel, PermissionsMixin): email = models.EmailField(_("Email Address"), unique=True) first_name = models.CharField( _("First Name"), max_length=128, blank=True, null=True ) last_name = models.CharField(_("Last Name"), max_length=128, blank=True, null=True) display_name = models.CharField(_("Display Name"), max_length=128) is_active = models.BooleanField(_("Active"), default=True) is_staff = models.BooleanField(_("Is staff"), default=False) profile_picture = models.ImageField( upload_to=to_profile_picture, null=True, blank=True ) objects: Type[UserManager] = UserManager() USERNAME_FIELD: str = "email" REQUIRED_FIELDS: List[str] = [] class Meta: verbose_name: str = _("User") verbose_name_plural: str = _("Users") @property def get_full_name(self) -> str: return f"{self.first_name} {self.last_name}" managers.py : from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email: str, password: str = None, **extra_fields): extra_fields.setdefault("is_superuser", False) extra_fields.setdefault("is_staff", … -
Django. How to make a condition for hide/show fields in the form so that it depends on the backend?
I want to make a condition under which it will not be necessary to change the code if the data in the database has been deleted. Now I have a simple condition: $('#category_id').change(function () { var optionSelected = $("option:selected", this); var valueSelected = $(this).val(); if (valueSelected === '1') { $('#rooms_id').hide(); $('#series_id').hide(); } else if (valueSelected === '2') { $('#rooms_id').hide(); $('#series_id').hide(); } else { $('#rooms_id').show(); $('#series_id').show(); } }); That is, when you select a specific category, unnecessary fields are hidden. But, if you delete the categories in the database, and the flow is added again in the wrong order as they were before, the condition will stop working. Because select will be different. <div class="col-md-3 mb-3"> <label class="sr-only">Categories</label> <select name="category" class="form-control" id="category_id"> <option selected="true" disabled="disabled">Categories</option> {% for category in categories %} <option value="{{ category.pk }}">{{ category.name }}</option> {% endfor %} </select> </div> This fields must be hide: <div class="col-md-6 mb-3"> <label class="sr-only">Комнаты</label> <select name="rooms" class="form-control" id="rooms_id"> <option selected="true" disabled="disabled">Комнаты</option> {% for key, value in room_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-md-6 mb-3"> <label class="sr-only">Серия</label> <select name="series" class="form-control" id="series_id"> <option selected="true" disabled="disabled">Серия</option> {% for series in series %} <option value="{{ series.pk }}">{{ series.name }}</option> … -
How to render data from external tables (Oracle) using datatables in Django Python?
I am retrieving data from external Oracle table and want to show data on web page using datatables. The retrieved data is in list form please suggest the way how to render list data in tabular form using datatables in Python Django. Since I am connecting to external database and storing data in on single variable hence I am not able to find any solutions through standard models.py. The code is not giving any error but empty table is being rendered on web page. My expectation is it should show desired data on web page in tabular form. Please let me know of any other detail or code is required ? #views.py #Necessary imports def show_data(request): dsn_str = cx_Oracle.makedsn("<<HOSTNAME>>","<<PORT_NO>>","<<SCHEMA>>") con = cx_Oracle.connect(user="user", password="***", dsn=dsn_str , encoding='UTF-8') cursor=con.cursor() cursor.execute("select abc, pqr, xyz from myDB.myTable") data_set=cursor.fetchall() con.close() return render(request, 'index.html', {"form":data_set}) #index.html {% extends "base.html" %} {% load static %} {% block content %} {% csrf_token %} <div class="container"> <table id = "table" class= "table table-bordered"> <thead> <tr> <th>ABC</th> <th>PQR</th> <th>XYZ</th> </tr> </thead> <tbody> {% for data in form %} <tr> <td>{{ data.ABC }}</td> <td>{{ data.PQR }}</td> <td>{{ data.XYZ }}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock content %} -
what is the reference root of the wsl?
I am trying to reference my static file which is located in d partition using wsl. this is the current directory: (venv) root@DESKTOP-xxxxx:/d/projects/ now in the ngnix conf file I am trying to reference django static file which is in the same directory as expected. is it right to reference the same directory as django do in settings file? I even tried to import os and make base_dir, it doesn't work. note that I have an empty folders for c, d in mnt directory. -
ImproperlyConfigured: The included URLconf 'buttonpython.urls' does not appear to have any patterns in it
The error im getting is django.core.exceptions.ImproperlyConfigured: The included URLconf 'buttonpython.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I am following an older django tutorial because those are literally all i can find and got his error. Here is the urls.py: from . import views from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', views.button) ] Settings.py (i included this because i found the buttonpython.urls variable in it): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'buttonpython.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'buttonpython.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = … -
Update database from another model\view
views.py @login_required def UnosPosudbe(request): if request.method == 'GET': forma = PosudbaForma() elif request.method == 'POST': forma = PosudbaForma(request.POST,request.FILES) if forma.is_valid(): #Dohvacanje Kolicine kolicinaKnjige = str(forma.cleaned_data['nazivKnjige']) IDKnjige = kolicinaKnjige kolicinaKnjige = kolicinaKnjige[-1:] IDKnjige = IDKnjige[:1] unesenaKolicina = forma.cleaned_data['kolicina'] if(int(kolicinaKnjige)>=unesenaKolicina and unesenaKolicina > 0): forma.save() return redirect('pregledPosudbe') return render(request, 'unosPosudbe.html', {'forma':forma}) I have to update another model from this view by ID. Model that I need to update is: models.py class Knjiga(models.Model): naziv = models.CharField(null=False, blank=True, max_length=120) autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True) datumObjave = models.DateField(null=True, blank=False) izdanje = models.CharField(null=True, blank=True, max_length=120) slika= models.FileField(upload_to='images/', null=True, verbose_name="") #videofile kolicina = models.IntegerField(null=False, blank=False) def __str__(self): return str(self.id) + ', ' +str(self.naziv) + ', ' + str(self.autor) + ', Kolicina:' + str(self.kolicina) In my view I have ID that need to be updated it "IDKnjige" variable. I need to update field "kolicina" from models.py like: kolicina = kolicina - unesenaKolicina #"unesenaKolicina" is variable from view It needs to be updated in "views.py" if this condition is true: if(int(kolicinaKnjige)>=unesenaKolicina and unesenaKolicina > 0): How can I do something like that? -
Django: form is not displaying
After user registers I am using signals to create a user profile, so they can fill in additional details (like country or website) that standard registration form can't offer. Problem is the form is not displaying the contents. However I can fill in same form on admin site easily, but I want to allow user to do it by themselves. On chrome i tried to inspect the problem, and where there is a form it says input='hidden'. What might be the problem? Thank you in advance my views def edit_profile(request): if request.method == 'POST': edit_form = EditProfileForm(request.POST, instance=request.user.profile) if edit_form.is_valid(): edit_form.save() messages.success(request, 'Your account has been updated!') return redirect(profile) else: edit_form = EditProfileForm(instance=request.user.profile) context = {'edit_form': edit_form} return render(request, 'profile.html', context) my profile.html <form method='POST'> {% csrf_token %} {{ edit_form }} <button type="submit">Update</button> </form> models: class Profile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') country = models.CharField(max_length=100, default='') website = models.URLField(default='') image = models.ImageField(default='images/profile.jpg', upload_to='images') def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py: class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('status', 'website', 'description', 'country', 'user', ) -
Convert Html to raw text in python
I have set up a function in my Django views that requests data from an API and save them into my database by clicking a button, but I have a problem with the format of the data. The goal is fairly simple: Remove all html code from the product description. Here's an example of the current format of a description: <ul>\n <li>\n <p>Based on the legendary Roald Dahl’s classic children’s book of the same name, “Matilda! The Musical” is all about little Matilda Wormwood, an extremely smart and bright girl whose genius is unfortunately, unrecognized by her dull parents.</p></li>\n <li>\n <p>Meet other characters you will love to hate such as the wicked Mrs. Trunchbull, her evil headmistress and meet Miss Honey, the only one who understands love Matilda with her sharp mind and vivid imagination</p></li>\n <li>\n <p>\"Once in a blue moon, a show comes out blazing and restores your faith in Broadway. 'Matilda The Musical' is that show\" <strong>-Elisabeth Vincentelli, NEW YORK POST</strong></p></li>\n <li>\n <p>Winner of <strong>5 Tony Awards</strong> and <strong>7 Olivier Awards</strong></p></li>\n</ul>\n<p><strong>FAQ's</strong></p>\n<p>1) <strong>Is there a possibility that I will get partial view seating with my Matilda tickets?</strong></p>\n<p>No, you will only receive full view seats. Although, there are a few … -
How to show full content of another website in Django?
I am trying to get the full content of another website, or modify the links that are clicked on when people use other websites on my site in django? import requests import urllib.request def one(request, myurl='google.com'): url = 'http://' + myurl r = requests.get(url) return HttpResponse(r) -
How do I display Django ManyToMany on a template? Simple code needed
I am trying to display ManyToMany field on the template in reversed order. Here is what I mean: I managed to display ManyToMany field on template when ManyToMany field was a field in model used so for example: <br/>{% for tag in post.tag.all %}{{ tag }}<br/>{% endfor %} will display all of the tags(meaning categories) that the post belongs to based on this model: class Post(models.Model): tag = models.ManyToManyField(Tag,blank=True,null=True,related_name='tag') Now I want something opposite - display authors of the post when ManyToMany field is in the Author model (Post model above stays the same): class Person(models.Model): post=models.ManyToManyField(Post,blank=True,null=True,related_name='post') I am quite sure it has something to do with Related Object Reference ( https://docs.djangoproject.com/en/2.2/ref/models/relations/) Just can not make it work. I have tried the following on the template. {% for post in posts %} {% for author in post.person_set.all %}{{author}}<br/>{% endfor %} {% endfor %} Also, shall I do this kind of searches on the template like above or is it a better practice put this kind of searches in views...resourcewise. Thanks for help. -
django - Upload a folder under media
I'm trying to upload an entire folder (of images) inside the media_root in django. I want something like im = models.ImageField(upload_to="images/", blank=True, null=True) but I do not want to upload many images one by one. How can I do that? There is a simple way to use FileField or ImageField that upload directly the folder instead of a file/image? -
Why is if-function not working, using two strings?
I try to compare two strings (one coming from a database - sqlite3 - via object.get() and the other one is coming from a cell in a csv file) within an if-clause using python (PyCharm). I want to insert the data (around 13.000 listings) from the csv file into a database/table. Problem is that one "csv-column" contains values which should refer to a foreign key table (already created). I don't understand why the two strings are not equal, although they should be. Perhaps you guys can help me with this issue. Thanks, nicdreifuss I used cmd, opend a pyhton manage.py shell, imported all models from models and imported the python file which contains the function (works fine). Then I ran the function and the problem is that the condition b11==b12 is always NOT true, although seem to be equal. Therefore I always get to else and get the return = Its not working. I tried to import the data without the if-clause and it works just fine, but I have to make a selection of the foreign Key in the table depending on what the value is in column 3 (index[2]). So infact there will be a b2, b3, b4... … -
How can I condense all these similar views into one?
All of these views are very similar, and I would like to condense them into one view. class SummerIntents(TemplateView): template_name = 'admin/hr/intent_forms/summer_intents.html' @user_is_staff def dispatch(self, request, *args, **kwargs): return super(SummerIntents, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(SummerIntents, self).get_context_data(**kwargs) # These functions are found in util.py update_date = get_update_date() active_users = get_active_users(self) context['summer_info'] = SummerInfo.objects.filter(employee__in=active_users, date_modified__gte=update_date.date, active=True).order_by('position','employee__last_name') return context def post(self, request, *args, **kwargs): context = super(SummerIntents, self).get_context_data(**kwargs) file_name = "summer_intent_forms" update_date = get_update_date() active_users = get_active_users(self) info = SummerInfo.objects.filter(employee__in=active_users, date_modified__gte=update_date.date, active=True).order_by('position','employee__last_name') student_intents = get_student_intents(active_users, update_date, 'summer', info) return intents_to_csv(student_intents, file_name) class WinterIntents(TemplateView): template_name = 'admin/hr/intent_forms/winter_intents.html' @user_is_staff def dispatch(self, request, *args, **kwargs): return super(WinterIntents, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(WinterIntents, self).get_context_data(**kwargs) # These functions are found in util.py update_date = get_update_date() active_users = get_active_users(self) context['winter_info'] = WinterInfo.objects.filter(employee__in=active_users, date_modified__gte=update_date.date, active=True).order_by('position','employee__last_name') return context def post(self, request, *args, **kwargs): context = super(WinterIntents, self).get_context_data(**kwargs) file_name = "winter_intent_forms" update_date = get_update_date() active_users = get_active_users(self) info = WinterInfo.objects.filter(employee__in=active_users, date_modified__gte=update_date.date, active=True).order_by('position','employee__last_name') student_intents = get_student_intents(active_users, update_date, 'winter', info) return intents_to_csv(student_intents, file_name) class FallIntents(TemplateView): template_name = 'admin/hr/intent_forms/fall_intents.html' @user_is_staff def dispatch(self, request, *args, **kwargs): return super(FallIntents, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(FallIntents, self).get_context_data(**kwargs) # These functions are found in util.py update_date = get_update_date() … -
Input Date value Property django
I'm trying to display the value of a date field from the database in my HTML but the field still shows blank text I've tried using the Django pipe when setting the value of the date. When I even use the same exact code in the label it works well but doesn't just work in the date field This is my views.py file def all(request): employees = Employee.objects.all().order_by('last_name') departments = Department.objects.all() table = EmployeeTable(employees) RequestConfig(request).configure(table) context = { 'table':table, 'employees':employees, 'departments':departments } if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] name = last_name +' '+first_name employee_id = request.POST['employee_id'] email = request.POST['email'] department = Department.objects.get(dept_name = request.POST['department']) address = request.POST['address'] employment_type = request.POST['employment_type'] employment_status = request.POST['employment_status'] role = request.POST['role'] marital_status = request.POST['marital_status'] gender = request.POST['gender'] join_date = request.POST['join_date'] end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date'] location = request.POST['location'] credentials = request.POST['credentials'] passport = request.POST['passport'] hod = request.POST['hod'] phone_number = request.POST['phone_number'] date_of_birth = request.POST['date_of_birth'] date_added = datetime.now() This my HTML code <div class="col-sm-6"> <div class="form-group"> <label for='date_of_birth' class="control-label">Date of Birth {{employee.date_of_birth|date:'Y/m/d'}} {{employee.date_of_birth|date:'m-d-Y'}} {{employee.date_of_birth|date:'SHORT_DATE_FORMAT'}} <span class="text- danger">*</span> </label> <input name='date_of_birth' type="date" class="form-control" value = " {{employee.date_of_birth|date:'m/d/Y'}} " > </div> </div> -
Ordered list in Django
Can anyone help, I want to return an ordered list based on forloop in Django using a field in the model that contains both integer and string in the format MM/1234. The loop should return the values with the least interger(1234) in ascending order in the html template. -
Check if date crash with another
I have two variables: start_time, end_time, which I need to compare with two other identical variables to see if they collide. Is there a function I can use? -
Django model object's boolean value not getting rendered
I am trying to show a field value in Django template. All values are getting rendered successfully but the one boolean value is not getting rendered. template.html {{user.username}}{{user.email}} /*{{user.is_email_confirmed}} This is not working*/ -
How to redirect html pages internally in Django?
I've included Product and services links, If I click on Product link it should redirect services page. I'm Using Django-Oscar. So I don't want to mess around with the urls.py and view.py. -
Removing html code in text and translate it to another language in python
I have set up a function in my Django views that requests datas from an API and save them into my database, but I have a problem with the format of the data. The goal is farely simple: Remove all html code and translate the description datas before saving it into my database. Here's an example of the current format of a descritpion: <ul>\n <li>\n <p>Based on the legendary Roald Dahl’s classic children’s book of the same name, “Matilda! The Musical” is all about little Matilda Wormwood, an extremely smart and bright girl whose genius is unfortunately, unrecognized by her dull parents.</p></li>\n <li>\n <p>Meet other characters you will love to hate such as the wicked Mrs. Trunchbull, her evil headmistress and meet Miss Honey, the only one who understands love Matilda with her sharp mind and vivid imagination</p></li>\n <li>\n <p>\"Once in a blue moon, a show comes out blazing and restores your faith in Broadway. 'Matilda The Musical' is that show\" <strong>-Elisabeth Vincentelli, NEW YORK POST</strong></p></li>\n <li>\n <p>Winner of <strong>5 Tony Awards</strong> and <strong>7 Olivier Awards</strong></p></li>\n</ul>\n<p><strong>FAQ's</strong></p>\n<p>1) <strong>Is there a possibility that I will get partial view seating with my Matilda tickets?</strong></p>\n<p>No, you will only receive full view seats. Although, there … -
running django project on client's pc hiding the source code
I need to know how to run Django on the client's pc using IIS or any other method. but I need to somehow encrypt or hide the source code of the program. any help? I've searched a lot for this but found nothing useful. -
Incorrect use of ManyToMany instead of ForeignKey
I have come across a programming project in Django where all OneToMany relationships were modelled as OneToMany relationships. So instead of putting a ForeignKey in the side of "One" of the OneToMany, there is a ManyToMany in the side of "Many". This was really striking to me as I found many disadvantages and reasons why this should be discouraged: It simply models the relation constraint incorrectly, and it will allow incorrect data validation and dirty model and codebase, and there would be no reason to do it unless there is a significant improvement. It creates an additional table between the two entities, that slows down database lookup time (joins are performed with three tables and not two). It will allow to assign an object to multiple entities that should not be allowed. The person responsibly alleges that with good code this should not happen, but I don't think this is right. If there is a bug in the code, it can create incorrect entries with no way of knowing which is the correct relation. There are several drawbacks when querying from Django ORM, among which, when filtering, the query always returns a list of length 1, instead of fetching the … -
Django file upload with "application/octet-stream" content-type
I have a 3rd side service which making a POST request with file to my Django application.To success upload to Django application request must have 'multipart/form-data' content type but content type is 'octet-stream' in my case and Request.FILES is always empty. How can i receive file with 'octet-stream' content type in django? form = UploadFileForm(request.POST, files=request.FILES) file = form.cleaned_data[file_name]