Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail - how to preopulate fields in admin form?
I would like to pre-populate fields in wagtail page admin. Particularly I would like to take username of currently logged admin/editor user and fill it in the form as a string. A simplified version of my page looks like this: class ItemPage(Page): author = models.CharField(max_length=255, default="") content_panels = Page.content_panels + [ FieldPanel('author'), ] I do not want to set a default value in the author field in the model - it should be user specific. I do not want to use the save method or signal after the model is saved/altered. The user should see what is there and should have the ability to change it. Also, the pages will be generated automatically without the admin interface. I think that I need something like https://stackoverflow.com/a/14322706/3960850 but not in Django, but with the Wagtail ModelAdmin. How to achieve this in Wagtail? -
How to Replace Contents of HTML Input With Ajax
I have a dependent drop-down list which populates when an option is selected in the first drop-down list. However, my Ajax request is returning the entire HTML template instead of only the JSON response with the desired data. The data I want is included, but only within the template I have designed. How can I specify that I only want the JSON response? Opportunities.html <div class="field"> <label class="label">Client Information:</label> <div class="select"> <select name="selectcompanies" id="selectcompanies"> <option value="">Company</option> {% for company in companies %} <option value="" name="selected_company" id="selected_company">{{ company.name }}</option>} {% endfor %} </select> </div> <div class="select"> <select name="selectlocations" id="selectlocations"> <option>Location</option> {% for location in locations %} <option value="">{{ location }}</option> {% endfor %} </select> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#selectcompanies").change(function () { var url = $("#opportunityForm").attr("data-url"); // get the url of the `load_cities` view var optionSelected = $(this).find("option:selected"); // get the selected country ID from the HTML input var company = optionSelected.text(); $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'selected_company': company // add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function console.log(data) $("#selectlocations").html(data); // replace the … -
Django compressor does not uglify javascript
I wish to use Django Compressor to both minify and uglify my css and javascript. I have got it working such that I do an offline compression and all required javascript is compressed correctly. The problem is that it does not uglify the code. My settings: STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "compressor.finders.CompressorFinder", ) COMPRESS_ENABLED = True COMPRESS_OFFLINE = True COMPRESS_YUGLIFY_BINARY = "yuglify" COMPRESS_YUGLIFY_JS_ARGUMENTS = "--mangle" yuglify is on my path. I tried running it manually on a file to test, ie:yuglify file.js --mangle. It turns out that yuglify (which is a wrapper around uglify-js) does not support es6 and above. I found another uglifier called terser which works perfectly from the terminal with es6 code. I therefore tried to replace the above settings with terser, ie: COMPRESS_YUGLIFY_BINARY = "terser" COMPRESS_YUGLIFY_JS_ARGUMENTS = "--mangle" This also does not work in django-compressor. The result is that the files get minified but not uglified. I would appreciate any suggestions on getting this working either with django-compressor or with an alternative package. -
Django migration not applying changes despite announcing otherwise
I'm trying to remove a column from a table in Django. I removed the field from the models.py file as well as any reference to it elsewhere. I ran docker-compose exec api python manage.py migrate and docker-compose exec api python manage.py makemigrations my_db where I was informed that: Running migrations: Applying my_classes.0002_remove_myclass_column_to_remove... OK But when I manually explore the database my_db, the column is still present. The contents of the latest migration file: # Generated by Django 2.1.7 on 2019-06-06 12:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('myclass', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='myclass', name='column_to_remove', ), ] Why hasn't my migration taken effect properly? -
Paginator Class based views not working in DJANGO
I am not sure why the paginator is not working. It does show at the bottom of the page but it does not apply to the list objects from "Entity" table. Is there something i am doing wrong in my html or views? models.py class Entity(models.Model): entity_name = models.CharField(max_length=250, blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users') slug = models.SlugField(max_length=250, unique=True, null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Entities" def __str__(self): return self.entity_name def get_absolute_url(self): return reverse('snippets:password', kwargs={'pk': self.pk}) views.py class EntityListView(LoginRequiredMixin, ListView): template_name = 'snippets/list.html' def get(self, request): queryset = Entity.objects.filter(owner=request.user) paging = queryset paginator = Paginator(paging, 3) page = request.GET.get('page') page_obj = paginator.get_page(page) return render(request, self.template_name, context={ 'entities':queryset, 'page_obj':page_obj }) html.py {% for entity in entities %} <a href='{% url "snippets:password" entity.pk %}'>{{ entity.entity_name }}</br></br></br></a> {% endfor %} <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> Any help would be much appreciated. -
How to iterate through a dictionary in a dictionary in django template using jinja variable?
My dictionary looks like this: a = { "1": { "league_id": "1", "name": "2018 Russia World Cup", "country": "World", "country_code": "", "season": "2018", "season_start": "2018-06-14", "season_end": "2018-07-15", "standings": False, }, "2": { "league_id": "2", "name": "Premier League", "country": "England", "country_code": "GB", "season": "2018", "season_start": "2018-08-10", "season_end": "2019-05-12", "standings": True }, } I want to loop through the dict and display all values for "name" and "country". my code in my .html template looks like: {% for c in a %} <thead>{{ a[c]['country'] }}</thead> {% endfor %} {% for n in a %} <tr> <td>{{ a[n]['name'] }}</td> </tr> {% endfor %} This gave an error: Could not parse the remainder: '[c]['country']' from 'leagues[c]['country']' I also tried {% for c in leagues %} <thead>{{ leagues.c.country }}</thead> {% endfor %} {% for n in leagues %} <tr> <td>{{ a.n.name }}</td> </tr> {% endfor %} It gave a blank page. How do I target the values name and country? -
Response has no attribute 'username'
I try to return a custom Response for my generics API view but it does not work since I get 'Response' object has no attribute 'username' error when the API is called Here's what I've done so far: I handle the DoesNotExist exception error then return a Response (from django rest framework). class UniqueEmailAPI(generics.RetrieveAPIView): permission_classes = [ permissions.AllowAny, ] serializer_class = UserSerializer def get_object(self): email = self.request.data['email'] try: return User.objects.get(email= email) except ObjectDoesNotExist: return Response(status=status.HTTP_204_NO_CONTENT) -
raise AppRegistryNotReady("Apps aren't loaded yet.")
I try to spawn a process which starts crawling some website in my views.crawl which is an ajax response. But some question happen: "raise AppRegistryNotReady("Apps aren't loaded yet.")". I don't know how to solve it this is my views: from django.shortcuts import render from .models import WebPath,FilePath from django.http import JsonResponse ... def main(url): weburl=WebPath(url,None) weburl.save() while(WebPath.objects.filter(path=None)): starturl() downloadfile() # Create your views here. def start(request): return render(request,'start.html') @csrf_exempt def crawl(request): global process if request.POST['status']=='ok': process=multiprocessing.Process(target=main,args=[request.POST['url']]) process.start() print(process.pid) return JsonResponse(['ok'],safe=False) else: process.terminate() return JsonResponse(['ok'],safe=False) the Exception is: Traceback (most recent call last): File "<string>", line 1, in <module> File "F:\Anaconda\Anaconda\lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "F:\Anaconda\Anaconda\lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) File "E:\python\django\crawltsinghua\crawl\views.py", line 2, in <module> from .models import WebPath,FilePath File "E:\python\django\crawltsinghua\crawl\models.py", line 4, in <module> class WebPath(models.Model): File "F:\Anaconda\Anaconda\lib\site-packages\django\db\models\base.py", line 87, in __new__ app_config = apps.get_containing_app_config(module) File "F:\Anaconda\Anaconda\lib\site-packages\django\apps\registry.py", line 249, in get_containing_app_config self.check_apps_ready() File "F:\Anaconda\Anaconda\lib\site-packages\django\apps\registry.py", line 132, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Django simple history history_change_reason - how to set instance from class
I wired up an object to use simple history and I see the historical table being correctly populated. I would like to also use history_change_reason field for more metadata. The difference from instructions is that on our system we use objects.create_or_update inside a classmethod. It works if I set changeHistory on the class parameter. However, I would like to set it on the instance of the class. What is a good way to do it? class SimpleHistoryTest(models.Model): .... history = HistoricalRecords() ... @classmethod def update_or_create_override (cls, feature): ... cls.changeReason = feature # this works. However, this is changed on all instances of class SimpleHistoryTest.objects.update_or_create( prop1='value1', ) -
['ManagementForm data is missing or has been tampered with']
Getting this error ['ManagementForm data is missing or has been tampered with'] even though i have followed all the steps in developing the code and tried to keep it as simple as possible Model.py: from django.db import models class Startup (models.Model): startup_name = models.CharField(max_length = 100) class Team (models.Model): startup = models.ForeignKey(Startup, on_delete = models.CASCADE) name = models.CharField(max_length = 100) position = models.CharField(max_length = 100) Forms.Py: from django.forms import inlineformset_factory from .models import * from django import forms class StartupForm (forms.ModelForm): class Meta: model = Startup fields = ['__all__'] class TeamForm (forms.ModelForm): class Meta: model = Team fields = ['name','position',] TeamFormSet = inlineformset_factory ( Startup , Team , fields = ('name' , 'position' ,) , extra = 1) Views.py: class teamcreate(CreateView) : model = Team template_name = 'application/str_team.html' form_class = TeamForm success_url = 'str_dashboard' def get_context_data(self , **kwargs) : data = super ( teamcreate , self ).get_context_data ( **kwargs ) if self.request.POST : data['formset'] = TeamFormSet ( self.request.POST or None) else : data['formset'] = TeamFormSet ( ) return data def form_valid(self , form) : context = self.get_context_data ( ) formset = context['formset'] with transaction.atomic ( ) : form.instance.created_by = self.request.user self.object = form.save ( ) if formset.is_valid ( ) : … -
Django migration not writing to DB, but complain about lack of relation when further changes is made
I've recently made a new class called 'Search' to store users search history. To reflect this on the database, I ran python manage.py makemigrations which creates the file 0001_initial.py in the migrations directory, so far so good. However when I run python manage.py showmigratiions and it shows that the new class has already been migrated. searches [X] 0001_initial If I run python manage.py migrate, no surprise it thinks no further migration is needed. Operations to perform: Apply all migrations: searches Running migrations: No migrations to apply. Throughout the process, 0001_initial.py never show up in the table django_migrations. The weird thing is if I change the class slightly, I can run makemigrations followed by migrate, and the migration of the edit will show up on django_migrations table in the database. Sadly, it still won't create a table for 'Search'. Here is my model.py from django.db import models from bookapp.users.models import User from bookapp.models import TimestampedModel class Search(TimestampedModel): user = models.ForeignKey('users.User', related_name='searched_by_user', blank=True, null=True, on_delete=models.SET_NULL) datetime = models.DateTimeField(auto_now_add=True) search_input = models.CharField(max_length=1024, null=True, blank=True) def __str__(self): return self.search_input and I have included Search in INSTALLED_APP in settings.py -
How the admin adds Categoies in drop down menu in Django?
I want to add different Categories in a drop down menu. I have created views for that but the options do not appear in drop down. How to display categories in a dropdown menu by retrieving the options from database in django?. I have shared the code on the given link but didn't get any satisfactory response.Please if any one can help? -
resubmission form on refresh page
hi I have problem when i refresh my page, my form resubmit . I want to send context with my render if request.method == 'POST' and 'search_form' in request.POST: rol = request.POST['rol'] group = request.POST['group'] national_number = request.POST['national_number'] phone_number = request.POST['phone_number'] users = MyUser.objects.filter(Q(group__name=group)|Q(role__name=rol)|Q(national_number=national_number)|Q(phone_number=phone_number)) return render(request,'deletuser.html',locals()) -
How to make chromium headless wait till the reactjs is loaded with the data from the fetch call
I have a Django project and recently I am trying to convert the front end to react one view at a time. I am using Django-hardcopy(https://github.com/loftylabs/django-hardcopy) to create a pdf report for me which was working for Django templates. But now that I am using react, the chrome headless does not wait till the fetch call is completed and just prints out the empty page in the pdf as react first renders the DOM element (so the data is still not fetched). I did go through some StackOverflow answers like using --virtual-time-budget=10000 But did not work. I tried to delay the reportview with import time time.sleep(5) I really cannot use react to render pdf at this moment because of some other restrictions. Is there any way to do this? If you guys need any more info let me know. Just an overview of the code I have: views.py class ReportView(LoginRequiredMixin, PDFViewMixin): def get_context_data(self, pk, **kwargs): .... mytemplate.html <div class="react-baseline-div"> <div id="baseline-energy-root"></div> </div> {% compress js %} <script src="{% static 'react/build_files/_reactify.js' %}"></script> <script src="/static/react/build_files/baseline_energy.chunk.js"></script> <script src="/static/react/build_files/main.baseline_energy.chunk.js"></script> {% endcompress %} This has the react build files and the <div> that connects to react app(react app renders perfectly) Just not in the pdf. -
Django-funky-sheets {% include hot_template %} causes permission denied error
I am trying to implement the django-funky-sheets (https://pypi.org/project/django-funky-sheets/) package, but I keep getting a Permission denied error as soon as I add the {% include hot_template %} tag. I did the following during installation and setup: pip install django-funky-sheets settings.py INSTALLED_APPS = [ ... 'funky_sheets', ... ] urls.py path('adres/funky/create/', CreateFunkyView.as_view(), name='funky-create'), path('adres/funky/update/', UpdateFunkyView.as_view(), name='funky-update'), views.py class CreateFunkyView(HotView): model = Adres template_name = 'bierviltje/vilt_detail.html' prefix = 'table' succes_url = reverse_lazy('funky-update') fields = ( 'id', 'adres_title', 'm2', ) hot_settings = { 'contextMenu': 'true', 'autoWrapRow': 'true', 'rowHeaders': 'true', 'contextMenu': 'true', 'search': 'true', 'licenseKey': 'non-commercial-and-evaluation', } def get_context_data(self, **kwargs): context = super(CreateFunkyView, self).get_context_data(**kwargs) context['vilt'] = self.model.vilt class UpdateFunkyView(CreateFunkyView): template_name = 'bierviltje/vilt_detail.html' action = 'update' button_text = 'Update' vilt_detail.html ... <div class="row"> {% include hot_template %} </div> ... The error message I keep getting is: [Errno 13] Permission denied: 'C:\Users\[username]\[project]\bierviltje\templates' -
Only main page loads on AWS/Ubuntu/django
I've developed an app locally and everything worked fine. I've promoted this to AWS using an ubuntu image. followed this example https://www.youtube.com/watch?v=u0oEIqQV_-E and was able to get the site to load. at least the main page. I added this to my urls.py (gunicorn + mezzanine : static files are not found) from django.contrib.staticfiles.urls import staticfiles_urlpatterns ... the rest of your URLconf goes here ... urlpatterns += staticfiles_urlpatterns() this enabled my css to work. Now the navigation to other views (pages) isn't working. I can't find anything online like this. any help would be great! -
How to fix: Django forms: {{ form }} is not working in a dynamic html page
I've created a dorm in Django: #forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField() number = forms.FloatField() eail_user = forms.EmailField() and imported in in views.py #views.py from django.shortcuts import render from .models import Cards from cards.forms import ContactForm def index(request): cards = Cards.objects.all() return render(request,'card.html', {'cards':cards}) def contact(request): form = ContactForm() return render(request,'name.html', {'form': form}) I have created three html files, name.html, base.html and card.html. The form is showing up in name.html properly, however, in cards.html, it just shows a single button and it omits {{ form }} tag. Any idea how to solve the issue? Thanks. #name.html from django.shortcuts import render from .models import Cards from cards.forms import ContactForm def index(request): cards = Cards.objects.all() return render(request,'card.html', {'cards':cards}) def contact(request): form = ContactForm() return render(request,'name.html', {'form': form}) This is base.html #base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link href="{% static 'css/stylesheet.css' %}" rel="stylesheet" type="text/css"> <!------ Include the above in your HEAD tag ----------> <meta charset="UTF-8"> <title>Title</title> </head> <body> <section id="team" class="pb-5"> <div class="container"> <h5 class="section-title h1">OUR TEAM</h5> <div class="row"> {% block content %} {% endblock %} </div> </div> </section> </body> </html> And this is card.html which extends … -
How to get the name of attached file to a mail in Django test case
I want to get the name of an attached file in Django test case. What's the way to achieve it. I went through the google search but all I found was how to check for an attachment. from django.core import mail attachment = mail.outbox[0].attachments[0][1] I'm getting the attachment. But what I know the attachment name is sent in the request header. How can I access that attachment name. Does Django provide a way to do that? If I'm wrong please correct me -
Django development server stops unexpectedly in Windows
I have Django application template based, which I am developing using Pycharm community. I am using Django built in development server to test my functionality in local Windows machine. The Django server stops at random when I am browsing the UI of the application. The same server is running fine in Ubuntu. The console doesn't give any error message at the time its stopping. The same happens but lesser when using --noreload flag while running. I tried in different machines also and the issue is same and if I should switch to some standard server then I need recommendation. Thank you in advance. The stacks that I am using are: Django - 1.8 Windows - 10 Python - 2.7 with virtualenv Ubuntu - 18.04 Postgres - aws-rds postgres-11 Browsers - Chrome, Firefox, Edge -
How do I exclude a post method and add a description in drf_yasg
I am using drf_yasg with swagger ui to document our Django app, trying to exclude post method is not working, nor operation description @method_decorator(name='create', decorator=swagger_auto_schema(auto_schema=None)) @method_decorator(name='list', decorator=swagger_auto_schema(operation_description="GET /dashboards")) class DashboardAPIView(ListCreateAPIView): """ View class that extends the Django rest framework generic view ListCreateAPIView to perform GET and POST operations for Dashboards """ queryset = Dashboards.objects.all().order_by('dash_name') serializer_class = DashboardSerializer def perform_create(self, serializer): sequence_no = get_next_sequence_number_test_dashboard() serializer.save(sequence_no=sequence_no) expecting post to be excluded and decription to show, but no dashboards GET /dashboards dashboards_list POST /dashboards dashboards_create -
I am having a problem in select box, where it can select multiple options, the selected option has a few objects in a sub select box
Firstly, I have a select box where i have to select multiple options. On selecting them, the code just considers the first option selected, and ignores the rest of the other options. Making me not able to save the other options. Views.py def post(self, request): user_site = UserSite.objects.get(user_id = request.POST["user_id"]) user_site.site_id = request.POST['site'] user_site.save() user_site.user.profile.roles = request.POST['role'] user_site.user.profile.company_id = request.POST['company'] user_site.user.profile.save() Only the option of 'Tamrind Valley' is selected, and 'Green Wood High'' is just ignored html <select class="form-control select2 edit-company-select" multiple="multiple" name="company" style="width: 100%;" required > <option></option> {% for company in companies %} <option value="{{ company.id }}"{{company.name}}</option> {% endfor %} </select> -
Django 2.2.2: "Manager isn't accessible via (Model) instances" on Admin
Hello SO, I just created two models: models.py from django.db import models from django.contrib.auth.models import User import uuid from uuid_upload_path import upload_to from django.core.exceptions import ValidationError from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ class StorageObject(models.Model): name = models.CharField(max_length=200) text = models.TextField(blank=True) slug = models.UUIDField(default=uuid.uuid4) display = models.BooleanField(default=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) # types file = models.FileField(upload_to=upload_to, blank=True, null=True) image = models.ImageField(upload_to=upload_to, blank=True, null=True) link = models.URLField(blank=True) @cached_property def file_type(self): if self.file: return 1 elif self.image: return 2 elif self.link: return 3 def clean(self): if self.file and (self.image or self.link): raise ValidationError(_('Storage Objects can only contain one storage type each')) elif self.image and (self.link or self.file): raise ValidationError(_('Storage Objects can only contain one storage type each')) elif self.link and (self.file or self.image): raise ValidationError(_('Storage Objects can only contain one storage type each')) if not (self.link or self.image or self.file): raise ValidationError(_('Storage Objects must contain exactly one storage type')) def __str__(self): return '%s (by %s)' % (self.name, self.owner) class Collection(models.Model): name = models.CharField(max_length=200) active = models.BooleanField(default=True) objects = models.ManyToManyField(StorageObject) owner = models.ForeignKey(User, on_delete=models.CASCADE) As the title says I´m getting an AttributeError whenever I am trying to create a Collection via admin-interface. However creating the StorageObject works perfectly fine and … -
How to check if the url is not in the i18n_pattern?
I need to check if the request path is outside the i18n_pattern, i.e. it should not have 'lang' prefix. For example, I have the following urls.py: urlpatterns = [ path('api/', include('api.urls'), name='api'), ] urlpatterns += i18n_patterns( path('', include('core.urls'), name='index'), prefix_default_language=False ) The reverse for 'api' shows that it will not be prefixed whatever language is used. Are there any other ways to figure out that the path of the current request is not included in i18n_patterns? Thanks! -
How can I do to convert a valuesqueryset to a JSON with datetime?
Hello I am trying to convert a list to JSON, here is my code : `json.dumps(myList)` But the problem is that in my valuesqueryset I have some datetime ... Do you have any ideas to solve this problem ? Thank you ! -
once i set SECURE_SSL_REDIRECT = True in django my website won't be able to visit
I am buiding my website,try to convert all http to https, so i followed https://docs.djangoproject.com/en/2.1/topics/security/#security-recommendation-ssl set SECURE_SSL_REDIRECT = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_HSTS_SECONDS = 2 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True then managed by supervisor that shows no error, but i can't visit this website by http/https. i check supervisor's stdout.log no error and also no visited records, error.log of nginx also no problem. once i set SECURE_SSL_REDIRECT = False https can be visited, but http still not my settings of nginx about 80 and 443 ports: server { listen 80; server_name www.frozendurian.com; rewrite ^(.*) https://$server_name$1 permanent; } server{ listen 443 ssl; server_name default; client_body_in_single_buffer on; client_max_body_size 2m; client_body_buffer_size 50m; proxy_buffering off; ssl_certificate /home/mark/1_frozendurian.club_bundle.crt; ssl_certificate_key /home/mark/2_frozendurian.club.key; ...... }