Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dynamically exclude a field from Django Model Form
I have a django Form class which is used to post data by a user in a forum. The class is shown below. class PostForm(forms.ModelForm): body = forms.CharField(label=_('Body'), widget=TinyMCE( attrs={'cols': 40, 'rows': 30, 'placeholder': _("Your answer...")}, mce_attrs=TINYMCE_DEFAULT_CONFIG)) class Meta(): model = Post exclude = ('creator', 'updated', 'created', 'topic', 'user_ip', 'telegram_id') The form only includes the body field as of now. I want to be able to dynamically exclude this body field when instantiating a form of this class. I need this because I am trying to use another django app called django-flag-app which is used to flag inappropriate posts by the user. This app adds a field to model of this form. So when a user flags it, it's showing an additional tinymce widget which should not be displayed. I want to prevent this by adding body to excludes dynamically. How can I achieve that ? -
Creating a function to check some combination of checks for auth
I am trying to create a boolean auth function that takes in some combination of *args and **kwargs to enable auth checks. This particular function checks the user's group membership and admin status along with the usual permissions. Note that if a user is admin, they are allowed to bypass the permissions. def auth_check(request, org_group, *perms): if request.user not in User.objects.filter(groups__name__in=[org_group]): return False if request.user.groups.filter(name='admins').exists(): return True for perm in perms: if request.user.has_perm(perm) == False: return False return True My question is how do I make it so it is possible to pass in some or condition for the *perms. For example something like 'model.change_object' | 'model.remove_object' like they do with complex lookups in Django. -
How to provide unique id to the button in a forloop to the single button in django templates?
I am trying to give a unique id to the button by adding post id in the button id, I don't understand how can i call this button id in ajax function. The way i am trying to do is wrong,So when i click on button that returns nothing. postlist template: {% csrf_token %} {% for post in object_list.all %} <div class="cardbox"> <div class="cardbox-heading"> <!-- START dropdown--> <div class="dropdown pull-right"> <button class="btn btn-secondary btn-flat btn-flat-icon" type="button" data-toggle="dropdown" aria-expanded="false"> <em class="fa fa-ellipsis-h"></em> </button> <div class="dropdown-menu dropdown-scale dropdown-menu-right" role="menu" style="position: absolute; transform: translate3d(-136px, 28px, 0px); top: 0px; left: 0px; will-change: transform;"> <a class="dropdown-item" href="#">Hide post</a> <a class="dropdown-item" href="#">Stop following</a> <a class="dropdown-item" href="#">Report</a> </div> </div><!--/ dropdown --> <!-- END dropdown--> <div class="media m-0"> <div class="d-flex mr-3"> <a href="#"><img class="img-responsive img-circle" src="{{post.username.avatar.url}}" alt="User"></a> </div> <div class="media-body"> <p class="m-0">{{post.username}}</p> <small><span>{{post.create_date|timesince}}</span></small> </div> </div><!--/ media --> </div><!--/ cardbox-heading --> <div class="cardbox-item"> <a href="{% url 'posts:post_detail_final' pk=post.pk slug=post.slug %}" data-toggle="modal"> <img class="img-responsive" src="{{post.image_data.url}}" alt="MaterialImg"> </a> </div><!--/ cardbox-item --> <div class="cardbox-base"> <ul> {% for likes in post.likes.all %} <li ><a href="{% url 'profiles:detail' username=likes.username %}"><img src="{{likes.userprofile.avatar.url}}" class="img-responsive img-circle" alt="User"></a></li> {% endfor %} </ul> </div><!--/ cardbox-base --> <div class="cardbox-like"> <ul> <li> <span class="" id="like_count">{{post.likes.count}}</span> <button class="btn btn-link text-dark p-0 border-0 … -
Django rendering a page with a small selection. Should this be faster?
All the code in this example is just a simplified representation. The actual code is more complex, but I believe that for this question this should be sufficient. I am unfortionaly stuck with a very old version of Django, which I can not change: 1.7.1 I render a .html page using django. The html page contains instances of artist. class Artist(EmptyModelBase): name = models.CharField(max_length=127) etc. etc. When a request comes, it goes to views.py where we do this: def some_function(req): # do some stuff filter = # filter actually comes from the request items = Artist.objects.filter(**filter) items = items[0:20] # return max 20 instances, even if we have more context = {'artists':items} return render(req, 'artist.html' , context) The .html itself is relatively simple. It contains more then this, but this is the essence: {% for item in artists %} <p class="artist"> {{ item.name | safe}} </p> {% endfor %} Everything above works as expected. Based on the request, and the filter in the request, there will be anywhere between 1 and 250k instances of Artist returned by the query. I take a slice of max 20 instances, and then render the page. My issue: if the request returns very few … -
Add custom model method in Django admin
I have a model Ad which has a custom add_ownership_including_ancestors method. Like below: models.py class Ad(models.Model): name = models.CharField(max_length=100) creator = models.ForeignKey('User', on_delete=models.CASCADE) def add_ownership_including_ancestors(self, current_user_id): #function to add permissions to current_user and creator and their ancestors views.py class AdViewSet(viewsets.ModelViewSet): def create(): #here the method is called adInstance.add_ownership_including_ancestors(request.user.id) Now this functionality works fine in normal webpage. I want the same method to be implemented in django admin pages whenever I create or update ad object from django admin pages. How can I do that? -
Django Randomly Select List Item to Display In Template
I have a list of strings in a .py file located in the same dir as my working app. I want to display a randomly selected item from the list and have it display in the template of my app. On each refresh of the page i want the random selection to change. I can't work out how this is possible at the moment. I'm thinking two things: run a random selection within the .py that has my list; or bring the entire list into the template and then use JS(?) to randomly select an item. Any advice? -
invalid input syntax for type integer: "1.0"
Having trouble reading csv file in python data frame got error Skipping line 4565: unexpected end of data invalid input syntax for type integer: "1.0" Any suggestions? -
Dictionary as string in django template
I have a dictionary in this format: dict = [{ "key1": "value1" "key2": "value2" "key3": "{"name": "", "age": "", "sex": ""}" }, ] NOTE: key3 is a string holding a dictionary On the template I can actually pull key1, key2, key3 since they are straight forward. But, key3 is one more dictionary stored in string. I'm able to do this: {% for eachObj in dict%} { eachObj.key1 } { eachObj.key3 } <!-- This prints whole dictionary--> { eachObj.key3.name } <!-- This line doesn't work since it is a string --> {%endfor%} Is there some way where I can try doing like: JSON.parse(eachObj.key3) inside that for loop? -
Name is not editing after click on edit button . ( No errorr )
#Forms.py ( I have added the form for edit the user profile ) class CreateForm(forms.ModelForm): Full_name = forms.CharField(required=True) class Meta: model = Profile fields = ('Full_name') #Views.py ( edit_post is the view for edit user profile ) def edit_post(request): args = {} if request.method == 'POST': form = CreateForm(request.POST or None, instance=request.user) form.actual_user = request.user if form.is_valid(): Full_name = request.POST['Full_name'] form.save() return HttpResponseRedirect(reverse('mains:profiles')) else: form = CreateForm() context = {'form':form} return render(request, 'mains/edit_post.html' , context) #Urls.py ( edit_post url is the url of edit user profile ) path('edit_post/', views.edit_post, name='edit_post'), #Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='') Full_name = models.CharField(max_length=40,default='') email = models.EmailField(max_length=60,default='') #Edit_post.html {% extends "mains/base.html" %} {% block content %} <p><a herf="{% url 'mains:profiles' %}">Edit Profile</a> <form action="{% url 'mains:edit_post' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Edit Post"/> </form> {% endblock content %} -
HTML is there a way to limit the year to 4 digits in date input
I am developing a django app. I have date input in my form: <input type="date" name="date_of_birth" class="dateinput form-control" required id="id_date_of_birth"> It allows to enter the date with the year having 6 digits, but I wish it was only possible to enter 4. I tried max, max-length attribute with pattern. I also tried to write a simple script: $(function() { $('#id_date_of_birth').change(function() { var date = $(this).val(); console.log(date, 'change') }); }); but it only starts when I change the year. I would like the numbers to loop on 4 digits instead of 6. Can someone give me a hint how to limit the year to only 4 digits? -
Dynamic sitemap with paginated external content (API) of 1 million data
This question is not specific to my setup but I have a Nextjs app for frontend and Django app for backend. I want to create sitemap but when I fetch data from API it comes in the paginated form as usual. I can adjust the number of items in these API responses but I have ~1 million pages. So what's the approach to generate sitemap for this kind of large sites? -
How to pass selected value from dropdown in Django?
I have a combobox onchange of selection in need to load the field with list of items. I tried various method to pass the selected dropdown value to a method. I tried to call a javascript method in from datalist onChange event but it didn't work. how can we achieve this? I am tried for full day but unfortunately no luck. Model. CATEGORY_CHOICES = Choices( ('KtCoffee', 'Karnataka Coffee'), ('Atea', 'Assam tea'), ('WBRice', 'West Bengal Rice'), ('GujCotton', 'Gujarat Cotton'), ('KerCocoa', 'Kerala Cocoa'), ) class maincategory(models.Model): category = models.CharField(choices=CATEGORY_CHOICES,max_length=25) def __str__(self): return self.category VIEW def update(request): if request.method == "GET": context = { 'choices': maincategory._meta.get_field('category').choices } return render(request, 'update.html', context) HTML <div> <input list="category-input"> <datalist id="category-input" style="width:100px"> {% for des,text in choices %} <option value={{text}}>text</option> {% endfor %} </datalist> </div> -
how to merge my dataframe to models in django?
I am trying to put my dataframe into mysql database in my django project for two days but not able to do this. this is my views.py file from django.shortcuts import render, redirect from .models import App from .forms import AppForm from django.core.files.storage import FileSystemStorage import MySQLdb from pandas.io import sql con = MySQLdb.connect("localhost", "root", "1234", "djstudent" ) def list_app(request): app = App.objects.all() import pandas as pd data = [['tom', 10.0, 5], ['nick', 15.0, 3], ['juli', 14.0, 1]] df = pd.DataFrame(data, columns=['description', 'price', 'quantity']) df.to_sql(App, con=con, if_exists='replace') return render(request, 'app.html', {'app': app}) def create_app(request): form = AppForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('list_app') return render(request, 'app-form.html', {'form': form}) def update_app(request, id): app = App.objects.get(id=id) form = AppForm(request.POST or None, instance=app) if form.is_valid(): form.save() return redirect('list_app') return render(request, 'app-form.html', {'form': form, 'app': app}) def delete_app(request, id): app = App.objects.get(id=id) if request.method == 'POST': app.delete() return redirect('list_app') return render(request, 'app-delete-confirm.html', {'app': app}) this is my model.py file from django.db import models # Create your models here. class App(models.Model): description = models.CharField(max_length=100) price = models.DecimalField(max_digits=9,decimal_places=2) quantity = models.IntegerField() #media = models.FileField(upload_to='media', default="") def __str__(self): return self.description settingspy Django settings for crud1 project. Generated by 'django-admin startproject' using Django 2.2.2. … -
Why Django is encapsulating all the content inside the Body Tag
I have a problem that I am reproducing with a simple example. No matter what I do I do always have a page with my content inside a body (js, footer, etc) like the image attached. Can anyone help me to figure this out? Thank you. If I remove the body tag from base.html, django include a body tag itself that encapsulates the remaining content. base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> {% block content %} {% endblock content %} </body> <footer> <h3>This is the footer</h3> </footer> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="{% static 'bootstrap-4.4.1/js/bootstrap.min.js' %}" ></script> </html> home.html: {% extends 'base.html' %} {% block content %} <div> <h1>This is the home body</h1> </div> {% endblock content %} The render result: -
Use django filter in FullCalendar.io
I am making a fullcalendar in my Django project, and I want to use django filters to filter the calendar. I have successfully created the calendar and the filters, but I can't get it to work together. This is my latest error when using the filter in combination with the calendar. Does anyone have experience with including django filters (or another filtering approach) in a fullcalendar, or have a link to documentation that explains filtering in fullcalendar? -
Trying to deploy a second app on my linode server
I have an app running on my linode server, but since my app is not being used much and I have enough memory, I decided to host another app on same server but I have been unable to do so, I have tried so many tutorials online but I have not been successful with it. Please assist. Thanks in advance. -
Pagination and queryset
I have a queryset : items = Items.objects.all() category_query = request.POST.get('category) items = items.filter(category = category_query) I have a paginator : from django.core.paginator import Paginator paginator = Paginator(items, 18) page_query = request.GET.get('page') items = paginator.get_page(page_query) when I click on Next in the pagination it remove the active filter on my items. How can I avoid that ? -
how to change errors in Django rest framework like PK to ID
{ "status": 400, "errors": [ "designation Invalid pk "2" - object does not exist.", "provincedetails Invalid pk "10" - object does not exist." ] } I know why this errors is throwing because relation object is not exist so.. But I want to customize this error like to remove PK and add ID, is that possible to do? -
Show and hide elements in different tabs with JQuery
There are a few similar questions but not one that quite answers mine. I have a page with several different tabs, and a Django form with different filters as fields which is used in the template. The form fields 'west_region' and 'east_region' have different choices. I want to show a different filter depending on which tab is open. Can I use JQuery and the hash value to do this? This is my music.html template: {% block page-content %} <div class="card mb-4"> <div class="card-block"> <form class="ui-filter"> <div class="ui-filter--fields"> <!-- West region filter --> <div class="ui-filter--field" id="west-region"> <label for="supplier_elec">Region:</label> <div class="form-full-width">{{ form.west_region }}</div> </div> <!-- East region filter --> <div class="ui-filter--field" id="east-region"> <label for="supplier_gas">Region:</label> <div class="form-full-width">{{ form.east_region }}</div> </div> </div> <div class="ui-filter--submit"> <button class="btn btn-primary btn-block" type="submit">Apply Filters</button> </div> </form> </div> </div> <div class="row"> <div class="col"> <div class="tab-content content py-4"> <div class="tab-pane active container-fluid" id="jazz" role="tabpanel"> <div class="row align-items-center"> <div class="col-sm-8 col-xl-10 col-12"> <h1>Jazz</h1> </div> </div> <h2>Songs</h2> {% include 'jazz.html' %} </div> <div class="tab-pane container-fluid" id="rock" role="tabpanel"> <div class="row align-items-center"> <div class="col-sm-8 col-xl-10 col-12"> <h1>Rock</h1> </div> </div> <h2>Songs</h2> {% include 'rock.html' %} </div> </div> </div> </div> {% endblock %} {% block extrascripts %} <script> $('#music-genre a').click(function(e) { e.preventDefault(); $(this).tab('show'); }); $("ul.nav-tabs > … -
Python: CalledProcessError, command returned non-zero exit status 1
I am getting this error Command '['settings.PDF_TO_TEXT', '-layout', 'absolute_file_path', '-']' returned non-zero exit status 1. here is what I want to achieve. def get_queries(filename, num_queries=3): scored_chunks = [] absolute_file_path = os.path.join(settings.MEDIA_ROOT, filename) # pdf_to_text_output = subprocess.check_output([settings.PDF_TO_TEXT, "-layout", absolute_file_path, "-"], shell=true) pdf_to_text_output = subprocess.check_output(['settings.PDF_TO_TEXT', "-layout", 'absolute_file_path', "-"], shell=True) try: text = pdf_to_text_output.decode('utf-8') except UnicodeDecodeError: text = pdf_to_text_output.decode('ISO-8859-1') ....... I am new to Django and python, I have tried many solutions but nothing is working for me. because I don't know how it works. here is the full traceback. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/index/ Django Version: 3.1.2 Python Version: 3.7.4 Traceback (most recent call last): File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Farhana Noureen\plagtrap\main\views.py", line 302, in post results = process_homepage_trial(request) File "C:\Users\Farhana Noureen\plagtrap\main\services.py", line 435, in process_homepage_trial queries = pdf.get_queries(filename) File "C:\Users\Farhana Noureen\plagtrap\util\getqueriespertype\pdf.py", line 18, in get_queries pdf_to_text_output = subprocess.check_output(['settings.PDF_TO_TEXT', "-layout", 'absolute_file_path', "-"], shell=True) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 395, in check_output **kwargs).stdout File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 487, … -
Render React Static files with django
Hope you all are doing well I am trying to connect my react frontend to my django REST-API, which doesn't seem to go well at the moment, in the react development server the application is working quite well but as in terms while exporting its static files to django things seem to crash at the point. The following process was followed to achieve the goal run npm run build command to get the build directory within the react app. Copied and pasted the build/static directory to my BASE_DIR Changed my settings.py for the django project to the following STATIC_URL = '/static/' STATICFILE_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT= os.path.join(BASE_DIR,'static-root') and then finally running the command python manage.py collectstatic which copied over 160 files into my static-root directory. This is what my project structure looks like the collectstatic command doesn't seem to copy my react static files in spite the fact that I have mentioned that static directory which contains the react files. Which is the reason that I cannot access my react static files, any help on how to render the react files django or mistakes in my strategy while development would be highly appreciated. -
Download Uploaded Files in Django Admin Action
I am trying to create an admin action in django to download the selected files uploaded by the users. I can view the uploaded file one by one and use the save link as for saving the file/images. But I want to download more than one by selecting and save them to a zip folder for download in one go. I use this download users' pdf in django as reference and created the below code. I was able to download a zip file but when i opened it,it says the zip file is not valid. I believe there is something wrong with querying the file url/writing it to the zip folder. Please assist. import tempfile import zipfile def downloadPic(self, request, queryset): with tempfile.SpooledTemporaryFile() as tmp: with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive: for index, item in enumerate(queryset): projectUrl = str(item.file.url) + '' fileNameInZip = '%s.zip' % index archive.writestr(fileNameInZip, projectUrl) tmp.seek(0) response = HttpResponse(tmp.read(), content_type='application/x-zip-compressed') response['Content-Disposition'] = 'attachment; filename="pictures.zip"' return response -
Bootstrap4 HTML page is too big on mobile
I'm a relative noob with bootstrap and css. I've rebuilt this site from the ground up a couple times in the last couple of weeks to try and sort the spacing etc and currently I have the problem that the main section is slightly too big for a mobile screen in the x dimension and can be scrolled, which is obviously unwanted behaviour. I've tried so many configurations and am so confused as to where this apparent right margin is coming from. (The content fills the screen until you scroll leaving a significant sliver of background body colour. I've tried debugging by setting the background colour of different elements and the margin shows black with the body background, but white with main, i.e is between the body and the main. I have tried doing this in my css: html { overflow-y: scroll; overflow-x: hidden; // this solves the problem on a small browser window but not on mobile device. margin: 0; padding: 0; } body { margin: 0; padding: 0; } main { margin: 0; padding: 0; background-color: #000; // this is what i was referring to that leaves a white margin after scrolling if this color is in the … -
If date not in queryset add default value
Im integrating django with chartjs. I use classbasedview like below. class SingleTagChartJSONView(BaseLineOptionsChartView): def get_context_data(self, **kwargs): context = super(BaseLineChartView, self).get_context_data(**kwargs) date_year = int(str(context["year"])) date_month = int(str(context["month"])) specific_date = datetime(date_year, date_month, 1) obj_tags = mitop_tags.objects.filter( tag_publish_date__year=specific_date.year, tag_publish_date__month=specific_date.month, post_tag_single=str(context['tag'])).extra( {'day' : "date(tag_publish_date)"} ).values('day').annotate( tag_occur=Count('post_tag_single')) I get obj_tags output like this: {'day': datetime.date(2020, 10, 16), 'tag_occur': 3} {'day': datetime.date(2020, 10, 17), 'tag_occur': 3} {'day': datetime.date(2020, 10, 18), 'tag_occur': 1} {'day': datetime.date(2020, 10, 19), 'tag_occur': 2} {'day': datetime.date(2020, 10, 20), 'tag_occur': 1} {'day': datetime.date(2020, 10, 22), 'tag_occur': 6} {'day': datetime.date(2020, 10, 23), 'tag_occur': 8} {'day': datetime.date(2020, 10, 24), 'tag_occur': 8} {'day': datetime.date(2020, 10, 26), 'tag_occur': 8} {'day': datetime.date(2020, 10, 27), 'tag_occur': 6} {'day': datetime.date(2020, 10, 28), 'tag_occur': 6} {'day': datetime.date(2020, 10, 30), 'tag_occur': 3} {'day': datetime.date(2020, 10, 31), 'tag_occur': 7} I want to add default value for not existing date (record) in queryset. {'day': datetime.date(2020, 10, 1), 'tag_occur': 0} In that case from 1-15 then missing 25 and 29. Desired output {'day': datetime.date(2020, 10, 1), 'tag_occur': 0} {'day': datetime.date(2020, 10, 2), 'tag_occur': 0} {'day': datetime.date(2020, 10, 3), 'tag_occur': 0} {'day': datetime.date(2020, 10, 4), 'tag_occur': 0} {'day': datetime.date(2020, 10, 5), 'tag_occur': 0} {'day': datetime.date(2020, 10, 6), 'tag_occur': 0} {'day': datetime.date(2020, 10, 7), 'tag_occur': 0} {'day': datetime.date(2020, … -
For some migrations, why `sqlmigrate` shows empty, or the same SQL both directions?
I'm working on upgrading a legacy project, currently still on Python 2.7.18 as the highest Python-2 before upgrade to 3. After upgrading Django from 1.8.13 to 1.11.29, the project requires some database changes (unapplied migrations), and I'm using command python manage.py sqlmigrate to review the SQL statements. I have some questions, and any inputs will be highly appreciated: Some migrations, e.g. 0002_logentry_remove_auto_add below, SQL only contains comment, I'm wondering why. (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate admin 0002_logentry_remove_auto_add BEGIN; -- -- Alter field action_time on logentry -- COMMIT; For migration 0002_auto_20160226_1747, SQL is the same for both forward and backward (--backwards) directions, and I'm also wondering 1) why, and 2) whether this should be a concern. Just want to be cautious with the production database, and thank you for your pointers. (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate authtoken 0002_auto_20160226_1747 BEGIN; -- -- Change Meta options on token -- -- -- Alter field created on token -- -- -- Alter field key on token -- -- -- Alter field user on token -- ALTER TABLE `authtoken_token` DROP FOREIGN KEY `authtoken_token_user_id_535fb363_fk_auth_user_id`; ALTER TABLE `authtoken_token` ADD CONSTRAINT `authtoken_token_user_id_35299eff_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); COMMIT; (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate --backwards authtoken …