Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: POST request is string, while instance is int
When I type custom_form.tickets.value and there is already some information in my database saved (ManytoMany) I receive e.g. `[19, 22, 20]`` The database entries are saved correctly and also on page load, all saved fields are filled. However, as it is form, errors in input can happen. I expect my form then to show/save the previously selected checkboxes before clicking on submit. However, then all fields are not checked. Only if I change it to {% if ticket_id|stringformat:"s" in custom_form.tickets.value %}checked{% endif %}> and therefore adding |stringformat:"s" it works for the post method. Unfortunately, I then have the problem that the instance/database records are not shown. Do you know how I can make both cases work? When loading the page and inserting instance data or when submitting the form if an error occurs. <div class="form-group"> <label for="{{ custom_form.tickets.id_for_label }}"> {{ custom_form.tickets.label }} <span class="badge badge-light">{% trans "Optional" %}</span> </label> <small class="form-text text-muted mt--2">{{ custom_form.tickets.help_text }}</small> {% for ticket_id, ticket_label in custom_form.tickets.field.choices %} <div class="custom-control custom-checkbox"> <input type="checkbox" name="{{ custom_form.tickets.html_name }}" value={{ ticket_id }} class="custom-control-input" id="id_{{ custom_form.tickets.html_name }}_{{ forloop.counter }}" {% if ticket_id in custom_form.tickets.value %}checked{% endif %}> <label class="custom-control-label" for="id_{{ custom_form.tickets.html_name }}_{{ forloop.counter }}">{{ ticket_label }}</label> </div> {% endfor %} … -
django-bootstrap-datepicker-plus change Backgroundcolor
it seems that django-bootstrap-datepicker-plus changes also my design.(changing my background color) Is there a way to change the bootstrap css? I have installed django-bootstrap-datepicker-plus with "pip install django-bootstrap-datepicker-plus" in my venv. -
How to get sphinx to document Django Model fields using help_text
I am documenting Django code using sphinx. How do I get it to document the fields in a Django model using the help_text value of the field? I have tried some hacks, including the SO answer here [Sphinx - Documenting Django models This does not work - and anyway is a kludge. At the moment sphinx generates the following for any Django field: A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed. Where I would like it to display the value of help_text for the field. Thanks. -
Individual search filters for fields in django-rest-framework
Django-rest-framework will has a SearchFilter backend that will allow a single query against the searchable fields: class OrganizationViewSet(viewsets.ModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer pagination_class = CustomPagination filter_backends = (filters.SearchFilter, DjangoFilterBackend) filter_fields = ('sector', 'industry', 'marketplace') search_fields = ('symbol',) this way, when I query ...?search=AMZ it will only return records with a non-sensitive match in the symbol field. If I add another element into the search_fields tuple, it will look for this same search string in both. Is there a way to define these search fields individually that will allow me to do something like: ?search_symbol=AMZ&search_name=Good so that it looks for objects that have AMZ in symbol field and good in name field? -
403 Forbidden during update the post. Django 2.1.5
I'm get 403 forbidden error, when i'm try update post with following code. models.py class Post(models.Model): ... def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) urls.py url(r'^post/(?P<pk>\d+)/update/$', views.PostUpdateView.as_view(), name='post_update'), views.py class PostUpdateView(PermissionRequiredMixin, UpdateView): model = Post permission_required = 'post.can_mark_returned' def get_form_class(self): fields = ['title', 'body', 'logo'] if self.request.user.is_staff: fields.append('moderation') return modelform_factory(self.model, fields=fields) post_form.html {% extends "base_generic.html" %} {% block content %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit" /> </form> {% endblock %} post_detail.html ... <a href="{% url 'post_update' post.pk %}">Изменить</a> ... -
How to avoid circular import within django's tests dir?
I'm trying to fix a circular import issue I'm having with Django tests. My dir structure is: app/tests: test_user_level01.py test_user_level02.py Within each file I have classes to test get 200s and get 403s (among other classes). Users in level 2 should have all the get 200s that level 1 users have and users in level 1 should have all the get 403s that the level 2 users have. Thus I have a circular import. Normally I would solve this with an absolute import but I can't figure out what that would be. I've tried: """test_user_level01""" from . import test_user_level02 """test_user_level02""" from . import test_user_level01 But this seems to give a circular import error (missing classes). Thank you ahead of time for your help. PS. The following doesn't work: import app.tests.test_user_level01 -
How to enforce database constraints between two foreign keys on a join table?
I am trying to enforce a constraint between two foreign keys on a join table, and I don't know whether I can do it using the database, or whether I should do it through my app, or my ORM. Here are my tables: Dataset Tag - Dataset: FK - name: string (eg: "park", "church", etc) Place - Dataset: FK - latitude - longitude PlaceTag (my join table) - Tag: FK - Place: FK - note: string (eg: "this place is my favorite park") I want to enforce the constraint that each PlaceTag has a Tag and a Place that belong to the same Dataset. Should I do this using the database, or my app? Or should I re-structure my models to enforce this constraint more easily? FWIW, this is an open-source project, and my PR for creating these tables is up here: https://github.com/mapseed/api/pull/161/files The project is using Django, if that helps. -
Could not parse the remainder: '{{' from '{{' when comparing dates in Django
I have a field in my model as below, which defines a date: usedate = models.DateField(default=date.today) I now want to be able to compare that date to todays date, to see if it's late. I've added the below to my html & it prints the correct date for today: {% now "Y-m-d" as todays_date %} {{ todays_date }} I'm now trying to compare todays date with the date in my model, using the below. But I get the error "Could not parse the remainder: '{{' from '{{'" Can anyone help? {% if todays_date > {{ todo.usedate }} %} <b>You're Late!</b> {% endif %} -
Django + Nginx configuration (getting "Welcome to nginx!")
I have Django + Nginx + Gunicorn on Ubuntu. Certificates generated with Letsencrypt. In /etc/nginx/sites-available/myproject I have: server { server_name myproject.com www.myproject.com; listen 80; return 301 https://myproject.com$request_uri; } server { server_name myproject.com www.myproject.com; listen 443; ssl on; ssl_certificate /etc/letsencrypt/live/myproject.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/myproject.com/privkey.pem; client_max_body_size 1G; root /home/myname/myproject; location / { include proxy_params; proxy_pass https://unix:/home/myname/myproject/myproject.sock; } } In /etc/nginx/sites-available/default, except commented lines, I have: server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { try_files $uri $uri/ =404; } } In /etc/nginx/sites-enabled I have default and myproject. When I go to https://myproject.com, I see "Welcome to nginx!". What am I doing wrong that it redirects to "Welcome to nginx!"? -
How to check custom Django model instance equality in tests?
I have a script which imports millions of records from a legacy database into a Django database using raw SQL for efficiency. The legacy database does not have ID primary keys, so these are created from a sequence when inserting rows. I'm testing that this import process is working properly by creating rows in the legacy database, running the import and verifying that I get the proper Django objects back out. The last part of a test typically looks a bit like this: actual = MyModel.objects.get(code=legacy_object_code) expected = MyModel( id=actual.id, code=legacy_object_code, other_property=other_value, … ) I have to pull the ID in from the actual object because otherwise there's no way the two objects could be tested for equality. But the problem is that self.assertEqual(expected, actual) always succeeds! This is because Django object equality is defined as having the same type and ID/PK. My workaround to actually check the properties of the model instances is this: def assert_model_instance_field_equality(self, expected, actual): expected_dict = expected.__dict__ expected_dict.pop('_state') actual_dict = actual.__dict__ actual_dict.pop('_state') self.assertDictEqual(expected_dict, actual_dict) I couldn't find this sort of assertion method, but maybe I'm missing something. Is there such a method, am I missing something, or is this really the best way to check … -
python manage.py runserver long response time
When I run 'python manage.py runserver' it takes at least 20 minutes before performing any system checks, it then takes a further 10 minutes to do the system checks. If there is an error with the code or database then it still takes this long before saying anything. I have the latest version of pip, Python and Django. I've looked on the task manage and the command prompt is using 0.1% of the CPU during this time. It also takes this long for me to run 'python manage.py migrate'. I seem to be the only one working on the project that has this problem. -
Django PDFTemplateView (easy_pdf) tidying up a report with page breaks
I saw where I can Have a page break in a easy pdf html template saying <p class="pb"></p> That is great, but I am trying to run a report where it page breaks and puts a table header every so many lines, with special consideration for the first page. Is there anyway to do this? This is the view I am calling my html from: class InvoiceReportPDF(PDFTemplateView): template_name = 'ipaswdb/invoice/invoice_report.html' download_filename = 'invoice_report.pdf' def get_context_data(self, **kwargs): context = super(GroupRosterPDF, self).get_context_data(pagesize='LetterSize',title='Group Roster',**kwargs) #context['groups'] = build_group_printout_models('pdf') return context So I can print this invoice but the line items just run from one page to the next with no nice header at the top of the next page (for when same invoice)... I can't use variables in the html page to count using the template and I thought Id get slick and when I build the items I send to the webpage to put in a field for a page break. So when I build my object I send to the view context I have like: invoiceItem['pagebreak'] = None if lineCount > xmany: invoiceItem['pagebreak'] = 'YES' Then in the html: {% if invoice.items %} {% for item in invoice.items %} <tr> <td> {{ … -
Assign default choice to a choiceField
I'm in with my final project and I'm a little bit new in django. I'm trying to assign a default value to the fields of my form, but i can't reach this This is my forms.py file This is the value of notas_csv. I'd like to assign the first value to 'nota_pad_verde' form field, and the same with the rest of the fields -
Django CharField add to choices from front-end
Problem Description Suppose I have a model with a CharField that has choices as follows: class MyModelWithChoice(models.Model): FIELD1_CHOICES = (('1', 'One'),) field1 = models.CharField(max_lenth=32, choices=FIELD1_CHOICES) Is there a way to add to these choices from the front end? Preventing the problem I know that the problem can be prevented by creating another model and using a ForeignKey for field1, which works just fine. Reason I'm trying to find another way The reason I'm trying to avoid creating a new model is because it doesn't really carry any more information. If it contained further information about the choice, I wouldn't have a problem, but it seems like too much overhead to create a table in the db just for the choices -
ImportError from python standard library
I get an ImportError when trying to import from python standard library. This only happens when I use a custom django management command and not when I use the normal runserver. This is the error I get: Traceback (most recent call last): File "D:/stack/sendall/website/sendall/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\stack\sendall\website\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "D:\stack\sendall\website\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "D:\stack\sendall\website\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\stack\sendall\website\venv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "D:\stack\sendall\website\venv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Joseph\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "D:\stack\sendall\website\sendall\accounts\models.py", line 1, in <module> from typing import AsyncContextManager ImportError: cannot import name 'AsyncContextManager' I am using python 3.7 Hope someone can help me solve this issue -
How to solve 'can only concatenate str (not "ManyRelatedManager") to str' in django
What needs to be done to solve this error in django , as i am new in django please help me to solve this. I tried searching on the web for this solution but got nothing. As much i know the problem is in self.product_name , i want a way to display a manyrealatedmanager. class cart(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) product_name = models.ManyToManyField(Album) qty = models.IntegerField(validators=[MaxValueValidator(15)]) price = models.IntegerField() total_price = models.IntegerField(editable=False) def save(self, *args, **kwargs): self.total_price = self.price * self.qty super(cart, self).save(*args, **kwargs) def __str__(self): return str(self.user)+' | '+self.product_name+' | '+str(self.qty)+' | '+str(self.price)+' | '+str(self.total_price) I am expecting the data in cart.product_name in form of str. -
Why I get error 400 bad request when sending variables in the URL django
I'm using django 3.9 this is my urlpatterns: from referrals import views as referrals_views urlpatterns = [ path('referrals_details/<int:patient_id>', referrals_views.referrals_details, name='referrals_details'),] I use a varible to indicate the id of the user I want to get. I´ve noticed that when sending a request, in my console I get: code 400, message Bad request syntax ('----------------------------563121910873865134633264') This issue is only when I use variables in the URL, I get my responses right though. Doing a quick search the main reason to this problem is requesting as Https, something that I'm not doing, I'm using Postman to send the requests. Any light on how to solve my problem will be appreciate it, thanks. -
django modelformset factory 'tuple' object has no attribute 'author
i am trying to make form that update modelformset if data is change but it is given error that 'tuple' object has no attribute 'author in change_object def formformset_update(request,invoice_id): # Sale_Transiction_formset = modelformset_factory(SaleTransiction, form=Sale_Invoice_Main_Page_ModelForm,extra=1) if request.method == 'POST': forms = Sale_Invoice_Main_Page_ModelForm(request.POST,instance=SaleInvoice.objects.get(invoice_no=invoice_id)) formset = Sale_Transction_formset_Extra(request.POST, request.FILES,queryset=SaleTransiction.objects.filter(invoice_no=invoice_id)) if formset.is_valid() and forms.is_valid(): forms.save() transiction = formset.save(commit=False) inv_no = forms.cleaned_data['invoice_no'] customer = forms.cleaned_data['customer'] trans_date = forms.cleaned_data['invoice_date'] forms.author = request.user # for ins in transiction: # ins.invoice_no = inv_no # ins.customer_transiction_name = 'class' # ins.transiction_date = trans_date # ins.transiction_type = 'sale' # ins.author = str(request.user) # ins.save() for obj in formset.deleted_objects: obj.delete() for objs in formset.changed_objects: # objs.author = request.user objs.customer_transiction_name = customer objs.transiction_date = trans_date objs.save() for ins in formset.new_objects: ins.invoice_no = inv_no ins.customer_transiction_name = customer ins.transiction_date = trans_date ins.transiction_type = 'sale' ins.author = request.user ins.save() return HttpResponseRedirect(reverse_lazy('saleinvoice:sale invoice home page')) else: # sale_invoice = Invoice_max.objects.get(invoice_name='sale') forms = Sale_Invoice_Main_Page_ModelForm(instance=SaleInvoice.objects.get(invoice_no=invoice_id)) formset = Sale_Transction_formset_Extra(queryset=SaleTransiction.objects.filter(invoice_no=invoice_id)) return render(request, 'saleinvoice/sale test/sale formformmodel update.html' ,{ "saleform" : forms, "saletransiction" : formset }) model class SaleInvoice(models.Model): customer = models.ForeignKey(Customer_data , on_delete=models.CASCADE) invoice_date = models.DateField(null=True,blank=True) invoice_no = models.PositiveIntegerField(unique=True) due_date = models.DateField(blank=True,null=True) address = models.TextField() total_amount = models.PositiveIntegerField(null=True,blank=True) description = models.TextField(null=True,blank=True) transiction_type = models.CharField(max_length=50,blank=True) author = models.CharField(max_length=30,null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) … -
filter_fields in django rest framework viewset are ignored
I am trying to get some basic equality filtering for my view and if I understand the documentation, I only need the filter_fields() field defined. Well, they seem to be ignored (/api/organizations?ticker=AMZN lists everything instead of filtering down to a single record): class OrganizationViewSet(viewsets.ModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer pagination_class = CustomPagination filter_fields = ('sector', 'industry', 'marketplace') @staticmethod def pack_persons_to_url(request, data): data["persons"] = request.build_absolute_uri("/api/persons/%s/" % data["symbol"]) def list(self, request, *args, **kwargs): response = super(OrganizationViewSet, self).list(request, *args, **kwargs) for element in response.data["results"]: self.pack_persons_to_url(request, element) return response def retrieve(self, request, *args, **kwargs): response = super(OrganizationViewSet, self).retrieve(request, *args, **kwargs) self.pack_persons_to_url(request, response.data) return response The first three fields are FKs and the ticker is a CharField. What do I need to fix to make it all work right? -
User has permission but after calling view response is 403 Frobidden
I have added permission to my model can_modify_match (below the code). After that I give this permission for one of the users. In template I used tags: {% if perms.matches.can_modify_match %} to precise which element are visible for users who has or not permission and this work perfectly. After that I specified permission for my class-based view MatchCreateView. When I try to call the view I have reposne 403 Forbidden. Why is that? Have I done something wrong? class Match(models.Model): ... class Meta: permissions = ( ('can_modify_match', 'Can modify match'), ) class MatchCreateView(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView): ... permission_required = 'matches:can_modify_match' -
Django unit testing: Separating unit tests without querying the database multiple times
I have a pair of tests like this: Make sure a task's deletion status initializes as None def test_initial_task_deletion_status_is_none(self): unfinished_task = Task.objects.get(tasked_with="Unfinished Test") self.assertIsNone(unfinished_task.delete_status) # Make sure a task's deletion status changes appropriately def test_unfinished_task_deletion_status_updates_appropriately(self): unfinished_task = Task.objects.get(tasked_with="Unfinished Test") unfinished_task.timed_delete(delta=.1) self.assertIs(unfinished_task.delete_status, "Marked for Deletion") This will go on, but I'll have unfinished_task = Task.objects.get(tasked_with="Unfinished Test") at the beginning of every one. Is there a way to split these types of things into separate tests, but use the same query result? -
How to fix ''module' object is not iterable' error, in Python with Django project
I am trying to create an webpage using Python and Django. I have just created a simple template and tried to run the sever but I get errors and I'm not able to understand.. I check all the spelling in my projects and searched the similar issues, however I am not able to solve it. settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'learning_logs', ] urls.py from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls')), ] views.py from django.shortcuts import render # Create your views here. def index(request): """The home page for Learning Log""" return render(request, 'learning_logs/index.html') urls.py // This is second URL """Defines url patterns for learning_logs.""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ # Home page. path('', views.index, name='index'), ] Error on command prompt when I tried to run server: "C:\Users\User\Desktop\python_work\project_3\learning_log\11_env\lib\site-packages\django\urls\resolvers.py", line 535, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: ..... "C:\Users\User\Desktop\python_work\project_3\learning_log\11_env\lib\site-packages\django\urls\resolvers.py", line 542, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see … -
Django all-auth custom signup form with custom user model
So I have a project that uses a custom UserModel, the default UserModel is extended to use a Profile model with a OneToOne relation to the Usermodel. I would like to use django allauth to verify emailaddresses and add social login. I have some issues with the custom signup, I've read the following How to customize user profile when using django-allauth, but it's not entirely clear how to implement this, I get an error; 'GuestSignUpForm' object has no attribute 'save' I've searched the forum and there seems to be no "official" documentation on how to do this, some people use ModelForms, others inherit from SignUpView, some def signup and others use def save... I tried customizing the default UserModel with UserCreationForm and had no issues, I just need some clarification on the inner workings of the allauth package models.py # Custom Usermodel class User(AbstractUser): pass # Custom Profile model to store additional info class Profile(models.Model): prefix = models.CharField(_('prefix'), max_length=8, blank=True, default="") user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') # Other fields left out for readability def __str__(self): if self.prefix: return '%s %s, %s' % (self.user.last_name, self.prefix, self.user.first_name) else: return '%s %s' % (self.user.last_name, self.user.first_name) # Create a profile record on save @receiver(post_save, … -
django-webpack-loader not rendering react app using react-app-rewired
I'm working on tying my react and Django apps together. Right now I'm just working to get the dev server working and will focus on production later. I've been following a handful of guides on this process, but they're all a little different and I haven't been able to find the right combination to get this working. I'm using react-app-rewired because I'd like to not have to eject. My understanding is that its more desirable to not eject and manually configure all of the Webpack configs. This may especially be true as I'm still learning react/webpack. Its my understanding that once this is configured I just need to run the Django server and it should display my app. I'm not running collectstatic or any npm start or build commands. Here's what I have configured: base.py ... STATICFILES_DIRS = [ # os.path.join(os.path.join(BASE_DIR, 'frontend'), 'build', 'static') os.path.join(BASE_DIR, "frontend", "build", "static"), ] ... local.py ... WEBPACK_LOADER = { "DEFAULT": { "CACHE": not DEBUG, "BUNDLE_DIR_NAME": "frontend/build/static/", # must end with slash "STATS_FILE": os.path.join(BASE_DIR, "frontend", "build", "webpack-stats.json"), } } ... config-overrides.js var BundleTracker = require('webpack-bundle-tracker'); module.exports = { webpack: (config, env) => { config.plugins.push( new BundleTracker({ path: __dirname, filename: './build/webpack-stats.json' }), ); return config; }, … -
How to display the website three inside page? Even an instance
I can't show the website tree on every pages as a menu…? I’m quite confuse with wagtails querySet… and how to move inside the three… I got always the same error Manager isn't accessible via BlogPage instances I able to display ancestors of a page but not able to show sibling of my current page. class BlogIndexPage(Page): ... class BlogPage(Page): ... def event_index(self): homepage = self.get_ancestors().type(BlogIndexPage).last() return homepage def siblings_index(self): siblings = self.objects.sibling_of(BlogIndexPage) return siblings I got : Manager isn't accessible via BlogPage instances I'm trying to do it only with wagtails basic query. (without wagtailmenu add-on)