Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Models design for dynamic user choice
I want to make a clone of a website, link, in which one can select custom design of his/her own choice. However being novice I am confused about how should I design the models for them. The app is like: There are items, each has a category and a sport There is cut for specifying the gender or age, e.g (men, junior, women) for each item. There is a custom graphic design which consist of several patches, where some patches can be colored separately from one another. Each item (e.g shirt), can have custom given collars and it can be half or full-sleeved And few others. The front end has a feature of displaying the item in 3D, how can I achieve that? If anyone can help me with that, then it would grateful. -
MultiValueDictKeyError at /food/restaurant/menu/ 'item'
help solve this error from my views.py i am making a restuarant website, but am having troubles when trying to add, something am doing wrong but i don't know what itemid = (request.POST['item'])error message @login_required(login_url='/login/restaurant/') def menuManipulation(request): if not request.user.is_authenticated: return redirect("rlogin") rest = Restaurant.objects.filter(id=request.user.restaurant.id); rest = rest[0] if request.POST: type = request.POST['submit'] if type == "Modify": menuid = int(request.POST['menuid']) memu = Menu.objects.filter(id=menuid). \ update(price=int(request.POST['price']), quantity=int(request.POST['quantity'])) elif type == "Add": itemid = (request.POST['item']) item = Item.objects.filter(id=itemid) item = item[0] menu = Menu() menu.item_id = item menu.r_id = rest menu.price = int(request.POST['price']) menu.quantity = int(request.POST['quantity']) menu.save() else: menuid = int(request.POST['menuid']) menu = Menu.objects.filter(id=menuid) menu[0].delete() menuitems = Menu.objects.filter(r_id=rest) menu = [] for x in menuitems: cmenu = [] cmenu.append(x.item_id) cmenu.append(x.price) cmenu.append(x.quantity) cmenu.append(x.id) menu.append(cmenu) menuitems = Item.objects.all() items = [] for y in menuitems: citem = [] citem.append(y.id) citem.append(y.fname) items.append(citem) context = { "menu": menu, "items": items, "username": request.user.username, } return render(request, 'webapp/menu_modify.html', context) -
The joined path is located outside of the base path component - Django image upload
I have a model with a ImageField. I want to upload the image to the folder media/item_image. Afterwards I want to be able to delete the image from the item, as well as the image file from the item_image folder. I was able to upload the image by altering the media root in the settings.py file, but I think this broke my delete function. Also it was not uploading the image in the right folder as intended. Now I am trying it the other way around but I am getting the following error: "The joined path is located outside of the base path component" settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' models.py class Item(models.Model): item_image = models.ImageField(upload_to='item_image', null=True, blank=True) def delete(self, *args, **kwargs): item = Item.objects.all() for i in item: i.delete() os.remove(os.path.join(settings.MEDIA_ROOT, self.item_image.name)) super(Item, self).delete(*args, **kwargs) I am a little stuck on how to approach this the right way. Is it because I am updating the Item instance and not deleting the instance? Does anyone have a clue? -
Django passing form_valid inline formset context to get_context_data()
I have a form with multiple nested inline formsets. I am validating the inline formsets in form_valid, which errors are added to forms with errors. Once the form_invalid fires, it returns-> return self.render_to_response( self.get_context_data(form=form, note=note, enrollment=enrollment, mealCount=mealCount)) where note, enrollment, and mealCount are all inline formsets. get_context_data, overrides any context saved in the form_valid method. how can the context from form_valid be passed through to the get_context_data, so that the formsets can be instantiated with the correct context if available, or blank instances if no context was created in form_valid? def get_context_data(self, **kwargs): context = super(RoomCreateView, self).get_context_data(**kwargs) #post data was passed in form valid! if self.request.POST: context['enrollment'] = kwargs['enrollment'] context['note'] = kwargs['note'] context['mealCount'] = kwargs['mealCount'] return context Above, kwargs['formsetname'] gives 'NoneType' object has no attribute '_state'. There is no instance of the inlineformset although an object exists. at the time of the error this is the object in the stack: <django.forms.formsets.RoomEnrollmentFormFormSet object at 0x00000203C0991B80> -
How to perform check on each object when querying in django? 'QuerySet' object has no attribute 'has_group_permission'
I have this property which I will use to return all users with a given permission: @property def assignable(self): return User.objects.all().has_group_permission('help_desk', 'ticket', 'view', self.group) However, when used the following is returned: 'QuerySet' object has no attribute 'has_group_permission' In theory, I'm using the function has_group_permission on every object returned from User.objects.all() and checking if it has the required permission. But this obviously doesn't work. What solutions are there? -
Not able to upload images to Django Server using React Native app
I have a react native android app and a Django REST API. Using react-native-image-picker the user is able to select an image and the image successfully shows up in the react native app. But then, I want to upload it to the API. For this, I am sending an axios request. When I send the request with image as null the request has a successful response. But, when the user selects an image then this request gives the following error: [Error: Request failed with status code 400] In the Django API, this image is defined as: image = models.ImageField(upload_to='media/Images/Groups/', null=True) I know this is not the issue, because when I upload an image from the Django Administration, it successfully uploads the image as required. And here is the API request to upload this image (and I know this is also not causing the issue): const axios = require("axios"); await axios.post('http://the url..., { //other fields I'm adding here "image": this.state.gImage, }) .then((response) => { console.log(response); }, (error) => { console.log(error); }); What I think the issue is, its in uri of the image that the user selects. When the user selects the image from the phone's gallery, then the image uri … -
Django - Save checkbox input to database and update page
My problem is that I have a list of 'Assignment' objects which all have a field called 'status'. The status is either true or false, and the user can choose to change the value by clicking on a checkbox for a specific assignment. This is what the frontend looks like, each assignment has a checkbox which is its 'status' My current solution is this: course-detail.html: {% for assignment in assignments %} <tr> <td scope="row" style="text-align: center"> <form> {% csrf_token %} {% if assignment.status %} <input type="checkbox" checked onclick='assignmentFinish("False","{{assignment.id}}")'> {% else %} <input type="checkbox" onclick='assignmentFinish("True","{{assignment.id}}")'> {% endif %} </form> </td> <td><h5><span class="badge badge-{{assignment.module.colour}}">{{assignment.module}}</span></td> <td><a href="{{ assignment.assigmentFile.url }}">{{assignment.title}}</a></td> <td>{{assignment.deadline}}</td> ... </tr> {% endfor %} ajax code: function assignmentFinish(value,assignment) { link = "{% url 'uni:finish-assignment' %}"; $.ajax({ type:'POST', url: link, data:{ status: value, assignmentID: assignment, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(){ } }); } views.py: def finishAssignment(request): # Get the product that user has wished for assignmentID = request.POST['assignmentID'] status = request.POST['status'] assignment = Assignment.objects.get(pk=assignmentID) print(status) if status == 'True': print("saving to true") assignment.status = True else: print("saving to false") assignment.status = False assignment.save() return HttpResponse('') enter code here models.py class Assignment(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) course = models.ForeignKey(Course, on_delete=models.CASCADE, default=None) module … -
if == condition does not output expected results in django template
A beginner here. Apologies if this is a very basic question. I am working with the Django template using python. My if conditional doesn't seem to work. Here I assumed a basic string comparison between a and be should yield "Very Happy," the second block. It doesn't. I output to display in my browser window and the result is always "Very Frustrating." I never get "Very Happy" the 2nd block. Here is a simplified version of my code: a = "test4" b = "test5" {% if a == b %} <strong>Very Frustrating</strong> {% else %} <strong>Very Happy</strong> {% endif %} My actual code will have a and b be variable imports (in order to ensure only logged in users can do certain things). Like so: a = {{logged_user}} b = {{clicked_username}} I put in the simplest test values for a and b (2 different strings) to isolate the issue for clarity. I can provide the actual code. But I figured if this doesn't work as expected with simple strings as is, this is where the problem is. Thank you for your time. -
AWS Django Deployment Error - Fix my error and I'll venmo you $5
IF YOU FIX THIS I'LL VENMO YOU $5. I'm trying to deploy a Django App on AWS Elastic Beanstalk. I've followed the tutorial [here]https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html, except with my own app instead of their sample app. The app works perfectly when i run it locally. Whenever I try to deploy it on Elastic Beanstalk, I run into an error: Your WSGIPath refers to a file that does not exist. I've looked at many other similar posts, but none of their fixes worked for me. Attached below is the error from eb logs, my project directory, and my config file that is supposed to point to the application object (named application) inside the wsgi file. I'm using the eb command line interface. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: mysite.wsgi:application -
Image field gets cleared off in django when i submit it
I am trying to create a social media app similar to Instagram however for some reason when I load the picture into the image field and submit it, the image gets cleared, and says that the field is required. Before submission After submission In django, the code for views.py @login_required def new_post(request): if request.method == 'POST': form = CreateNewPost(request.POST) if form.is_valid(): messages.success(request, "Post has been created") form.save() return redirect('home') else: form = CreateNewPost() return render (request, "posts/post_form.html", {"form":form}) I have kept the default user to none temporarily as it insisted me to choose one when I created the models initially. Is that the reason for this problem? If so how do I get rid of it. Html code... <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Add a Post!</legend> {{ form | crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> models.py class Post(models.Model): image = models.ImageField(upload_to='post_images') caption = models.CharField(blank=True, max_length=254) date_posted = models.DateTimeField(auto_now_add=timezone.now) author = models.ForeignKey(User, on_delete = models.CASCADE) def save(self): super().save() img = Image.open(self.image.path) width, height = img.size ratio = width/height if img.height > 500: outputsize = (500, (height/ratio)) img.thumbnail(outputsize) img.save(self.image.path) forms.py class CreateNewPost(forms.ModelForm): class Meta: model = Post fields = ["image","caption"] and just … -
how to use if condition in html
I'm new to Django and I want to create html template but I dont know how to use if condition here is my code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Fehreste Filmha: </title> </head> <body> <h1> 11 </h1> <h2> 22 </h2> {%if movie_list%} {%else%} <p style="color = red"> 33 </p> {%endif%} </body> </html> output is: 11 22 {%if movie_list%} {%else%} 33 {%endif%} does anybody know the problem? -
TypeError at /register/ 'builtin_function_or_method' object is not subscriptable
This method I am Calling Weather API with data and the parameter in the form of dictinoary, but its throwing error in line: email=form.cleaned_data.get['email'] TypeError: 'dict' object is not Callable def register(request): headers = { 'Content-type': 'application/json','PRIVATE-TOKEN': '3YhXE1DsLE-xXs15ECg7', 'Authorization': 'Bearer 3YhXE1DsLE-xXs15ECg7', 'Authorization': 'Basic YWRtaW46YXplcnR5cmVkbWluZQ=='} form = UserRegisterForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save() email=form.cleaned_data.get['email'] username = form.cleaned_data.get('username') password =form.cleaned_data.get['password'] data={"username":username,"email":email,"password":password} response = requests.post('http://172.16.0.111/api/v4/users/', headers=headers, data=data) response.json() messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) -
Is there a way to generate SearchVector field content on runtime?
Model have a SearchVector field and a CharField content field. class AModel(models.Model): content = models.CharField(...) vector = SearchVectorField() When content field changed, vector field is updated by query below: AModel.objects.filter(id=xx).update(vector=SearchVector('content')) If I fetch the vector field and lookup in to the content of the field is looks like below: "'2':38 '3':32 '4':26 '5':20 'bskl':14,19,25,31,37 'ck':2 'clb':13,18,24,30,36 'club':4 'f':1 'fck':11,16,22,28,34 'clb-bskl':10,15,21,27,33 'kargo':9 'pv':12,17,23,29,35 'trt':6 'tsrt':7" I want to generate this output on the runtime without updating vector field. I took a look at the SearchVector class but I can't figured out how it can be possible. -
I am trying to create a favourite content btn but i am getting the ( AttributeError at /contents/ 'QuerySet' object has no attribute 'favourite' )?
My HTML code: {% for i in content reversed %} <div class="col-lg-4 content" data-aos="zoom-out-up" data-aos-duration="800"> <div class="card card-body cardbody"> <h4 class="content_title">{{ i.content_title }}</h4><hr> <img src="/media/{{i.content_img}}" class="content_img"><hr> <div class="favourite-section"> {% if is_favourite %} <a href="{% url 'favourite_content' id=i.id %}"><i class="fas fa-heart fa-lg"></i></a> {% else %} <a href="{% url 'favourite_content' id=i.id %}"><i class="far fa-heart fa-lg"></i></a> {% endif %} </div> </div> </div> {% endfor %} Here is the urls.py file path('', views.contents, name="contents"), path(r'(?P<id>\d+)/favourite_content', views.favourite_content, name="favourite_content"), Here is the view.py file def contents(request): content = Content.objects.all() is_favourite = False if content.favourite.filter(id=request.user.id).exists(): is_favourite = True params = {'content': content, 'is_favourite': is_favourite} return render(request, 'contents.html', params) def favourite_content(request, id): content = get_object_or_404(Content, id=id) if content.favourite.filter(id=request.user.id).exists(): content.favourite.remove(request.user) else: content.favourite.add(request.user) return HttpResponseRedirect(content.get_absolute_url()) Here is the models.py code favourite = models.ManyToManyField(CustomUser, related_name="favourite", blank=True) How to edit the views.py file so it is registered in the database that the user has favorited this video ? -
Accessing MySQL Views in Django
How can I access a MySQL view in Django? I find it hard to believe that I am the first to want to do this with Django, but because both Django and MySQL use the term 'view' the search results have not been helpful. I have read the Django documentation on running raw SQL queries and accessing stored procedures, but it doesn't quite solve my particular need. Basically, there are several MySQL views in the database that I need to manage/access via Django like I can with tables. I realize that I can access views by running raw SQL queries in Django, but I value the control Django models and migrations provide and would like to be able to do the same with views. Ideally, I would like the official Django way of doing this but if that doesn't exist I would also value your hacks/workarounds for this. -
How to test initial data for ManyToMany field in Django form?
I want to write a unittest to check the initial value of a ManyToMany field. Here's what I have so far: def test_field_initial(self): instance = MyModel.objects.create(name='myinstance') m2m_obj = OtherModel.objects.create(name='mym2mrel') instance.m2mfield.add(m2m_obj) instance.save() self.assertQuerysetEqual( instance.m2mfield.all(), [repr(m2m_obj_1)], ordered=False) form = MyForm(instance=instance) self.assertEqual([repr(m2m_obj)], list(form.fields['m2mfield'].initial)) I haven't shown all the example models for clarity; it's just a generic ManyToMany field relationship. The problem I have is form.fields['m2mfield'].initial results in None, so the second assertion fails. The M2M relationship is clearly there as the first assertion passes. The form also renders the correct HTML properly. Why does field.initial show None and how do I properly test for expected values? -
Django formsets with ArrayField
I have a ArrayField of CharFields and i need to add\delete elements of my array dynamicaly. For my admin panel i found django-better-admin-arrayfield package and it works just the way i want it to (on picture). However, i don't know how to do similar with template form. I found that formsets allow you to do something similar, but in all examples i found they create different objects( like here and i need to add values to my ArrayField. So my question is: can i emplement formsets with ArrayField? from django.db import models from django_better_admin_arrayfield.models.fields import ArrayField class Patient(models.Model): Privilege_type = ( ('Ветеран', 'Ветеран'), ('Чернобыль', 'Чернобыль'), ('Ребёнок-инвалид до 18 лет', 'Ребёнок-инвалид до 18 лет'), ('Инвалид I - II группы', 'Инвалид I - II группы'), ('Инвалид III группы', 'Инвалид III группы'), ) first_name = models.CharField(max_length=90, blank=False, null=True, verbose_name='Имя') last_name = models.CharField(max_length=90, blank=False, null=True, verbose_name='Фамилия') middle_name = models.CharField(max_length=90, verbose_name='Отчество') birth_date = models.DateField(verbose_name='Дата рождения') privilege_type = models.CharField(max_length=90, choices=Privilege_type, default=0, verbose_name='Льгота') medication = ArrayField(models.CharField(max_length=90, blank=True, null=False)) date_of_recipe = models.DateField(verbose_name='Дата выдачи рецепта') medication.verbose_name = 'Препарат' medication.blank = True medication.null = True class Meta: verbose_name_plural = 'Льготники' def __str__(self): return self.first_name + ' ' + self.last_name -
How do I enforce a ManyToMany blank=False constraint on my Django model?
I'm using Django 3 and Python 3.8. I have the below model, Note the "types" ManyToMany field, in which I set "blank" to False. class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() I want verify a validation error occurs if I leave that field blank, so I have @pytest.mark.django_db def test_coop_create_with_no_types(self): """ Verify can't create coop if no """ coop = CoopFactory.create(types=[]) self.assertIsNotNone(coop) self.assertNone( coop.id ) and use the following factory (with FactoryBoy) to build the model class CoopFactory(factory.DjangoModelFactory): """ Define Coop Factory """ class Meta: model = Coop name = "test model" enabled = True phone = factory.SubFactory(PhoneContactMethodFactory) email = factory.SubFactory(EmailContactMethodFactory) web_site = "http://www.hello.com" @factory.post_generation def addresses(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of types were passed in, use them for address in extracted: self.addresses.add(address) else: address = AddressFactory() self.addresses.add( address ) @factory.post_generation def types(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of types were passed in, use them for _ … -
Django translation in python code, wont translate using my language switch
Im currently using Django for internationalization. Ive done a bunch of translations in JS and HTML however moving on to python code, all my translations are stuck in whatever default language i chose in my "settings.py" file at the "LANGUAGE_CODE" variable. IE. the translations are working fine when manually switching in the code, but my language switcher only changes JS and HTML strings, not python. The python strings im translating are located in the "views.py" file. My language switcher looks the following way: {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <div class="col-xs-6 r-col-pad"> <form action="{% url 'set_language' %}" method="post" id="form_{{ language.code }}" style="display:inline!important;"> {% csrf_token %} <input name="next" type="hidden" value="{{ request.get_full_path }}" /> <input name="language" type="hidden" value="{{ language.code }}" /> </form> <input class='glyphicons xxl-text' type="image" form="form_{{ language.code }}" src='../static/icons/{{language.code}}.png'width="20" height="20"></input> </div> {% endfor %} My internationalization settings looks like this: (settings.py) # Internationalization LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ('da', 'Danish'), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] My URLS looks like this: (urls.py) urlpatterns = [ # App urls … -
Using save method's kwargs to create another object
My models structure is composed by 2 models, Counts and AccessRecords. Every AccessRecord is linked to one Count and one User. In one of my current views i usually create the Count object and then the AccessRecord. Like this: count = CountAddForm(request.POST).save() AccessRecord.objects.create(user = request.user, count = count) This works, but i might need to save Counts again in other views and i would rather have the AccessRecord creation bound to the save method. count.save(**{'request_user':request.user}) And re-cofiguring the save method to create the AccessRecord: class Count(models.Model): task = models.ForeignKey(Task, related_name = 'counts', on_delete = models.CASCADE) start_time = models.DateTimeField(null = True, blank = True) end_time = models.DateTimeField(null = True, blank = True) time_spent = models.PositiveIntegerField() stamped_date = models.DateTimeField(null = True, blank = True) def save(self, *args, **kwargs): if self.start_time and self.end_time: self.time_spent = date(self.end_time) - date(self.start_time) super().save(*args, **kwargs) if self.accesses.count() == 0: if (not self.start_time): self.stamped_date = timezone.now() AccessRecord.objects.create(user = kwargs['request_user'], count = self) class AccessRecord(models.Model): date = models.DateTimeField(default = timezone.now) user = models.ForeignKey(get_user_model(), related_name = 'accesses', on_delete = models.CASCADE) count = models.ForeignKey(Count, related_name = 'accesses', on_delete = models.CASCADE) However this gives me an KeyError: 'request_user' at the line AccessRecord.objects.create(user = kwargs['request_user'], count = self) I don't understand why is this … -
Django ORM Annotate Latest Entry of related model
I have 2 models as below. 1. Order 2. OrderStatus Order Fk created_at status On the get_queryset of the Order ModelViewset, I want to annotate the latest OrderStatus entry on the Order model. The OrderStatus entry has to be latest also i.e. based on created_at Thanks! -
How to Join two tables from two different databases in Django?
In one of my project I came across the requirement of joining two tables from different databases in Django and couldn't figure out optimal solution yet. The problem is I have two databases with tables that are correlated with each other and I want to make a join between tables of two different databases. SQL query works fine inside MS SQL Server but how to do that in Django is the main issue. I want to run the RawSQL Query inside Django and pass it to ORM. For a single database it is fine but for two databases it is not working. For example, I have two Databases Like DB1 with table CashAccount and DB2 with table teamAccount. SQL Query: SELECT (t1.unique_name) as unique_name, (t1.AccountBalanceAmount) AS AccountBalanceAmount, (t2.TeamName) AS TeamName, (t2.ProjectDesc) AS ProjectDesc, FROM ( SELECT CONCAT(ID,'_',ProjectName) AS unique_name, AccountBalanceAmount FROM DB1.CashAccount ) t1 INNER JOIN ( SELECT CONCAT(ID,'_',ProjectName) AS unique_name, TeamName ProjectDesc FROM DB2.TeamAccount ) t2 ON t1.unique_name = t2.unique_name How do I execute this query using Django ORM or raw SQL Query using raw()? -
How to avoid ordering by in django queryset, order_by() not working
I have a "big" db whith over 60M records, and I'm trying to paginate by 50. I have another db whith ~8M records and it works perfectly, but with the 60M amount it just never loads and overflows the db. I found that the problem was the order_by(id) made by django so I tried using a mysql view already ordered by id, but then django tries to order it again. To avoid this, I used order_by(), which is supposed to avoid any ordering, but it still does it. def get_queryset(self, request): qs = super(CropAdmin, self).get_queryset(request) qs1 = qs.only('id', 'grain__id', 'scan__id', 'scan__acquisition__id', 'validated', 'area', 'crop_date', 'matched_label', 'grain__grain_number', 'filename').order_by() if request.user.is_superuser: return qs1 The query made is still using order_by: SELECT `crops_ordered`.`crop_id`, `crops_ordered`.`crop_date`, `crops_ordered`.`area`, `crops_ordered`.`matched_label`, `crops_ordered`.`validated`, `crops_ordered`.`scan_id`, `crops_ordered`.`grain_id`, `crops_ordered`.`filename`, `scans`.`scan_id`, `scans`.`acquisition_id`, `acquisitions`.`acquisition_id`, `grains`.`grain_id`, `grains`.`grain_number` FROM `crops_ordered` INNER JOIN `scans` ON (`crops_ordered`.`scan_id` = `scans`.`scan_id`) INNER JOIN `acquisitions` ON (`scans`.`acquisition_id` = `acquisitions`.`acquisition_id`) INNER JOIN `grains` ON (`crops_ordered`.`grain_id` = `grains`.`grain_id`) **ORDER BY `crops_ordered`.`crop_id` DESC** LIMIT 50 Any idea on how to fix this? Or a better way to work with a db of this size? -
AdminLTE3 and DataTables
I am trying to develop a web app using Django and AdminLTE3. I'm using DataTables in one of my templates, and even if it's functional, it doesn't look as expected. Here is how it looks like: [![Here is how it looks like:][1]][1] Here is how it should look like: [![Here is how it should look like:][2]][2] Here is my base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Tensor</title> <link href="{% static 'img/favicon.ico' %}" rel="shortcut icon"/> <!-- Font Awesome Icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css"> <!-- Theme style --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/admin-lte/3.0.5/css/adminlte.min.css"> <!-- Google Font: Source Sans Pro --> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet"> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables.net-responsive-bs4/2.2.5/responsive.bootstrap4.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.1/showdown.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script> </head> <body class="hold-transition sidebar-mini"> <div class="wrapper"> <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="/" class="nav-link">Home</a> </li> <li class="nav-item d-none d-sm-inline-block"> <a class="nav-link" href="http://discord.tensor.fr" role="button"><i class="fab fa-discord fa-2x"></i></a> </li> </ul> </nav> <!-- /.navbar --> {% block content %}{% endblock %} <!-- Control Sidebar --> <aside class="control-sidebar … -
How can I update correctly a django model?
I have this model in Django: dms_dok_titel = models.CharField(max_length=255, blank=True) dms_dok_beschreibung = models.CharField(max_length=3000, blank=True, null=True) dms_dok_datei = models.FileField(max_length=255,upload_to='DMS/') dms_dok_hochgeladen_am = models.DateField() dms_dok_indiziert = models.BooleanField(default=False) dms_dok_gehoert_zu_app = models.CharField(max_length=255, choices=app_choices, blank=False, null=False) dms_dok_typ = models.CharField(max_length=255, choices=typ_choices, blank=False, null=False, default='Sonstiges') def save(self, *args, **kwargs): preserve_ext = extension(self.dms_dok_datei.name) neuer_dateiname = self.dms_dok_gehoert_zu_app + '_' + self.dms_dok_titel + '_' + self.dms_dok_hochgeladen_am.strftime("%d.%m.%Y") self.dms_dok_datei.name = neuer_dateiname + preserve_ext super(DMS_Dokument, self).save(*args, **kwargs) def delete(self): self.indexes.all().delete() super(DMS_Dokument, self).delete() class Meta: app_label = 'DMS' At another place in my code I do something with the objects from this class and I want to update just one field (dms_dok_indiziert). So I thought I could just set this object's value (tmp_obj) to true and then do tmp_obj.save(). But for whatever reason, it always messes up my file's name in the database. The usual upload script generates something like 'DMS/nameofthefile.pdf', but after saving tmp_obj it just becomes 'nameofthefile.pdf'. I tried this: tmp_obj.dms_dok_datei.name = 'foo' #tmp_obj.dms_dok_datei.name = 'DMS/' + tmp_obj.dms_dok_datei.name print(tmp_obj.dms_dok_datei.name) tmp_obj.save() And yes, it prints 'foo'. Still, when I save the object, then in the database it is again 'nameofthefile.pdf'. I just don't get it. :(