Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django post save signal calling two times with each request
I'm using Django 2.x I have a model TransactionLog which logs the amount given and updated. Each time amount is given, a new record is created in AmountGiven model and thus will create a log with action as given and if the earlier given amount is updated, it will log with action as updated. @receiver(post_save, sender=AmountGiven) def amount_given_post_save_receiver(sender, instance, created, **kwargs): if created: action = 'given' else: action = 'updated' TransactionLog.objects.create( user=instance.contact.user, contact=instance.contact, amount_given=instance, amount=instance.amount, action=action ) But even when a new record is created, post save receiver is being called two or more than two times. Then, one record is saved as action=given in TransactionLog and others are creating action=updated record in the TransactionLog model. How can I make it unique to each call? -
gunicorn WORKER TIMEOUT django
This is the error that i got when i execute: heroku logs --tails when my coworker send data, cause' any other else he does in the web run flawless 2018-10-30T02:00:06.120286+00:00 heroku[router]: at=info method=GET path="/admin/jsi18n/" host=**** request_id=74398afb- 64fa-47ce-bd60-84e1f97d2568 fwd="186.149.99.66" dyno=web.1 connect=0ms service=233ms status=500 bytes=71354 protocol=https 2018-10-30T02:00:06.117070+00:00 app[web.1]: 10.35.152.177 - - [30/Oct/2018:02:00:06 +0000] "GET /admin/jsi18n/ HTTP/1.1" 500 71144 "***" "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 OPR/56.0.3051.52" 2018-10-30T02:06:17.830010+00:00 app[web.1]: [2018-10-30 02:06:17 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:54) 2018-10-30T02:06:17.833403+00:00 app[web.1]: [2018-10-30 02:06:17 +0000] [54] [INFO] Worker exiting (pid: 54) 2018-10-30T02:06:18.063326+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="****" host=**** request_id=36d7700f-690f-408a-bc50-697571dae1b5 fwd="****" dyno=web.1 connect=0ms service=30542ms status=503 bytes=0 protocol=https 2018-10-30T02:06:18.224034+00:00 app[web.1]: [2018-10-30 02:06:18 +0000] [60] [INFO] Booting worker with pid: 60 this is what herokus says about h13 code error, and i guess maybe is my gunicorn configuration, but this error just happen to one of my coworkers, when he tries to send data, i don't know at all why this is happening, and i'm getting mad about it cause' my app web will come out soon, and i want to offer the best performance experience. Well this error never happen to me even when i open my heroku web app … -
Django project show processed data instantly
I have one django project. It has one function in view.py to process the data from the inputs to give the output for other function. However the processing time for the function is kind of long. I want to fulfill the instant demonstration of the processed output. How could I achieved that? The following processing() function is for the processing purpose. And the output 'user_entries' is for the demonstration in results() as followed. def processing(request): import sys n = [] for topic in Topic.objects.filter(owner=request.user).order_by("date_added"): entries = topic.entries.all() m = [] for p in entries: q = p.text m.append(q) n.append(m) list = [] start(list, n) request.session['user_entries'] = list return request.session['user_entries'] def results(request): data = processing(request) return render(request, "project/results.html", {"datas": data}) In the start() function of the processing() function. There is one part list.append() to add new output into list. But it seems that the new appended list cannot be transferred and show the instant results in project/results.html? -
how to get list of cities from a country knowing a city in that country in Django
I have 3 models for country, province ('state'), and city. Suppose i have 3 countries USA, Canada, and England. In addition, assume the user has selected the city of Orlando ( I got this city through a form). Now, how can I get all cities in USA (assume there are limited amount of cities from USA in data base) in a dropdown menu. here are the models: # country model class Country(models.Model): name = models.CharField(max_length=64, unique=True) def __str__(self): return "%s" % (self.name) # province model class Province(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=64) def __str__(self): return "%s" % (self.name) # city model class City(models.Model): province = models.ForeignKey(Province, on_delete=models.CASCADE) name = models.CharField(max_length=64) def __str__(self): return "%s" % (self.name) I have tried the following code in view function: def search(request): template = 'path/to/template.html' #get the name of the city query_c = request.GET.get('qc') # get the country of this city p_c = Country.objects.filter(province__city__name__iexact=query_c) print(p_c) get a list of cities belong to this country cities_in_post_city = City.objects.filter(province__country___name=p_c) context={ 'all_p_cities': cities_in_post_city, } return render(request, template, context ) I need a list of all cities belong to the same country knowing only a city name. I do not care which city belong to which state. … -
Django 'DIRS': [] in settings.py TEMPLATES causes "TemplateDoesNotExist" Error
I'm using django version 2.1.2 with python 3.6. I created two django projects (test01 & test02) by CMD. Both of the projects are under the same folder. Test01 executes normally, while test02 raises TemplateDoesNotExist error. I've found a solution for the latter that is hard coding the address of templates in settings.py: 'DIRS': [r'C:\django\test02\accounts\templates'] However, another project can run normally even leaving this list as blank []. The structures of both projects are the same: Can anyone give a suggestion that can fix the problem in test02 without hard coding the address of templates in test02? -
django view 'GET' does not work, 'POST' does work
I have no Idea why, but if I try to 'GET' this view I get this error: django.urls.exceptions.NoReverseMatch: Reverse for 'profile-update-name' with arguments '('',)' not found. 1 pattern(s) tried: ['ce_profiles/profile\\-update\\-name/(?P<pk>[0-9]+)/$'] But if submit a 'POST' request, everything is fine. ??? urls.py app_name='ce_profiles' urlpatterns = [ path('profile-update-name/<int:pk>/', views.profile_update_name, name='profile-update-name' ), ] view def profile_update_name(request, pk): name = get_object_or_404(CEName, id=pk) if request.POST: name_form = NameForm(data=request.POST, instance=name) if name_form.has_changed() == False: name_form.add_error(None, _('No changes made.')) if name_form.is_valid(): name_form.save() updated_name = get_object_or_404(CEName, id=name.id) profile_name_json = render_to_string( 'ce_profiles/profile_name.html', {'profile_name': updated_name,} ) return JsonResponse({'profile_name': profile_name_json}) else: return JsonResponse({'error': name_form.errors}) else: name_form = NameForm(instance=name) get_NameForm_json = render_to_string( 'ce_profiles/update_NameForm.html', {'NameForm': name_form} ) return JsonResponse({'NameForm': get_NameForm_json}) -
Update data in HTML table without reloading the whole page Django
I have an HTML table which shows data corresponding to the choice selected in the dropdown and when the user presses submit button, the page refreshes and the data for that choice is shown in the table. What I want to achieve is do this without reloading the whole page. HTML code : <div class="form-inline"> <div class="col-md-10"> <div class="form-group"> <select class="form-control input-sm" name="type" id="type"> <option value="%">All types</option> {% for type_name in type %} <option value="{{ type_name.name }}">{{ type_name.name }}</option> {% endfor %} </select> </div> </div> </div> <div class="clearfix" style="margin-bottom: 10px;"></div> <div class="form-inline"> <div class="col-md-2"> <div class="form-group"> <input type="submit" class="btn btn-info btn-sm" value="Submit"> </div> </div> </div> <table class="table table-striped table-bordered"> <thead> <tr> <th>Date</th> <th>Type Name</th> <th>Type Name 2</th> <th>Count</th> </tr> </thead> <tbody> {% for row in generic_table_rows %} <tr> <td>{{ row.date }}</td> <td>{{ row.type_name }}</td> <td>{{ row.type_name_ }}</td> <td>{{ row.count }}</td> </tr> {% endfor %} </tbody> </table> Django code for providing data for table (the data is captured from postgres database) : def get(self, request) : params = self.__get_params(request) render_dict = {} render_dict['year'] = params['year'] render_dict['month'] = params['month'] render_dict['type'] = [{'name' : 'tenant-wise'}, {'name' : 'division-wise'}, {'name' : 'both-wise'}] render_dict['tenant_list'] = get_tenant_list() render_dict['division_list'] = ['ac', 'bt', 'hr', 'scm', 'collabo', 'dicing-search'] if … -
ValueError: Cannot assign object user must be a "User" instance
This is very strange to me. I am setting a breakpoint inside of a Django signal receiver create_customer_settings to debug this. The app is throwing a ValueError even though the new CustomerSettings object is successfully created. When I try to create it for a second time, I get a UNIQUE constraint error, but that is because it was already added successfully. Why the ValueError when isinstance(this_user, User) == True? Is this an error I can safely catch and ignore? Is it a problem because the CustomerSettings id is different than the User id? create_customer_settings @receiver(post_save, sender=User) def create_customer_settings(sender, instance, created, **kwargs): if created: this_user = User.objects.get(id=instance.id) pdb.set_trace() CustomerSettings.objects.create( user=this_user, email=this_user.email, date_of_birth="1998-01-04", in_private_mode=False ) pdb.set_trace() output 1: System check identified no issues (0 silenced). October 29, 2018 - 23:42:57 Django version 2.1.1, using settings 'myapp.settings' Starting development server at http://127.0.0.1:7000/ Quit the server with CONTROL-C. > /src/myapp/myapp/models.py(36)create_customer_settings() -> pdb.set_trace() (Pdb) this_user <User: new_user_8080> (Pdb) isinstance(this_user, User) True (Pdb) CustomerSettings.objects.create( user=this_user, email=this_user.email, date_of_birth="1998-01-04", in_private_mode=False ) *** ValueError: Cannot assign "<CustomerSettings: CustomerSettings object (6)>": "CustomerSettings.user" must be a "User" instance. pdb.set_trace() output 2: (Pdb) this_user.is_anonymous False (Pdb) this_user <User: new_user_8080> (Pdb) CustomerSettings.objects.create( user=this_user, email=this_user.email, date_of_birth="1998-01-04", in_private_mode=False ) *** django.db.utils.IntegrityError: UNIQUE constraint failed: myapp_customersettings.user_id … -
ModelForm in Django with One-to-One relationship: unable to update
I'm using Django's ModelForm functionality to create a form. However, my particular Model is extended with another model using a one-to-one relationship. I therefore create two separate forms and they are filled out by the user and then submitted. This all works 100% when creating a record (both the place and restaurant record are created), but not when updating a record. When I try to update a form, it does not pass the is_valid check for the restaurant form. I am new to Django and must also say that there seems to be quite some repetition in this code. Is there a better way to update/insert records with less repetition? My models: class Place(models.Model): name = models.CharField(max_length=255) class PlaceForm(ModelForm): class Meta: model = Place fields = ['name'] class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, related_name='restaurant', primary_key=True, ) location = models.CharField(max_length=255, null=True, blank=True) class RestaurantForm(ModelForm): class Meta: model = Restaurant exclude = ['place'] And here is my view: def create_or_edit(request, id=False): restaurantform = False if id: info = get_object_or_404(Place, pk=id) form = PlaceForm(instance=info) if hasattr(info, 'restaurant'): restaurantform = RestaurantForm(instance=info.restaurant) else: info = False form = PlaceForm() if type == 'restaurant': restaurantform = RestaurantForm() if request.method == 'POST': if not id: form … -
How to manually build a django `HttpRequest`
I have the following in requests: url = "http://hello.net" res = requests.post(url, {'email':'hello@gmail.com'}) How would I convert this same request into a django HttpRequest? So far I have: >>> from django.http import HttpRequest >>> request = HttpRequest() >>> request.method = 'POST' >>> request.POST = {'email': 'hello@gmail.com'} How would I then 'post to the url'? Additionally, is there any advantage of using a HttpRequest object over using the requests method? -
Display Total amount in the admin interface
I Have searched, didn't find any answer I want to get the total of inline salesitem in the admin template. as a user is adding the item and the price, I want the quantity * price of the item to be done in the admin inline table. Example: class Stock(models.Model): price = models.DecimalField() quantity = models.PositiveIntegerField() class Sales(models.Model): name = models.CharField() #Other fields class SalesItem(models.Model): item = models.ForeignKey(Stock) quantity = models.PositiveIntegerField() Here is my admin admin class SalesItemInline(admin.TabularInline): model = SalesItem class SalesAdmin(admin.ModelAdmin, ExportCsvMixin): exclude = ['admin', 'branch'] inlines = [SalesItemInline] It is a mini inventory system that I already deployed. I need help. -
Restrict choices using two foreignkey relationships in django
I have three models, a household model, a household-member model, and an occupations models as described below. I would like the occupations model to only show members that belong to a particular household (which is related to field sno). How does one do something like this? Would be grateful for any help. class Household(models.Model): village = models.CharField(max_length=150, null=True, blank=True) household_number = models.IntegerField(blank=True, null=True) form_number = models.IntegerField(null=True,blank=True) head_of_household = models.CharField(max_length=150, null=True, blank=True) class member(models.Model): sno = models.ForeignKey(Household, on_delete=models.CASCADE) person_number = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=150, null=True, blank=True) sex_choices2 = ( ('M','Male'), ('F','Female'), ) sex = models.CharField(max_length=3,choices=sex_choices2,blank=True, null=True) age = models.CharField(max_length=30,blank=True, null=True) class Meta: unique_together = (("sno", "person_number"),) def __unicode__(self): return self.name def __str__(self): return self.name class occupations(models.Model): sno = models.ForeignKey(Household,on_delete=models.CASCADE) person_number = models.IntegerField(blank=True, null=True) name = models.ForeignKey(member, blank=True, on_delete=models.SET_NULL, null=True) occupation = models.CharField(max_length=100, null=True, blank=True) class Meta: unique_together = (("sno", "person_number","occupation"),) -
Changing the data type of the field value dynamically in django models
I have the follwing use case in my application: there is a form field which is added dynamically from the backend. each variable can either be: integer, float, text, .. etc. my question is what is the best way to implemment this concept using django models or database as general. here is my current approach: class FieldValue(models.Model): text_value = models.CharField(max_length=255, null=True) long_text_value = models.TextField(null=True) date_value = models.DateField(null=True) datetime_value = models.DateField(null=True) number_int_value = models.IntegerField(null=True) number_float_value = models.FloatField(null=True) image_value = models.ImageField(null=True) boolean_value = models.BooleanField(default=False) class FormField(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=30, choices=FIELD_TYPE_OPTIONS) api = models.CharField(max_length=255, null=True) value = models.ForeignKey(FieldValue) I used form-field and field-values, however, the problem here is for any form field object I store a lot of variables although I am just using only one of them (at maximum). Another approach can be by storing them all as strings and then do the type check and validation rules on the application layer but I don't think this would be efficient. -
RabbitMQ and RPC in python
I am using AMQP RPC (more or less as it is describes in the RabbitMQ docs) to authenticate my services against a central authentication service The authentication code for the Django/DRF app I have I have goes something like class AMQPAuthentication(authentication.BaseAuthentication): channel = None connection = None def __init__(self): if not AMQPAuthentication.connection or not AMQPAuthentication.connection.is_open: if self.connection is not None: logger.error('AMQP connection closed. Reconnecting.') self._reconnect() self.connection = AMQPAuthentication.connection self.channel = AMQPAuthentication.channel try: self.queue = self.channel.queue_declare(exclusive=True, auto_delete=True, durable=False) self.callback = self.queue.method.queue self.channel.basic_consume(self._on_response, no_ack=True, queue=self.callback) except pika.exceptions.ConnectionClosed: self._reconnect() self.connection = AMQPAuthentication.connection self.channel = AMQPAuthentication.channel self.queue = self.channel.queue_declare(exclusive=True, auto_delete=True, durable=False) self.callback = self.queue.method.queue self.channel.basic_consume(self._on_response, no_ack=True, queue=self.callback) def _reconnect(self): creds = pika.credentials.PlainCredentials(username=settings.AMQP_USER, password=settings.AMQP_PASS) AMQPAuthentication.connection = pika.BlockingConnection(pika.ConnectionParameters(host=settings.AMQP_HOST, credentials=creds)) AMQPAuthentication.channel = AMQPAuthentication.connection.channel() logger.info('connected to AMQP broker') def _on_response(self, ch, method, props, body): if self.msg_id == props.correlation_id: self.response = body def authenticate(self, request): if request.META.get('HTTP_AUTHORIZATION'): header = request.META.get('HTTP_AUTHORIZATION') self.response = None self.msg_id = str(uuid.uuid4()) props = pika.BasicProperties(reply_to=self.callback, correlation_id=self.msg_id) self.channel.basic_publish(exchange='', routing_key=settings.AUTH_QUEUE_NAME, properties=props, body=str(header)) def authentication_timeout(): raise exceptions.AuthenticationFailed("Authentication timed out.") # add timeout for response from the auth service hard-code 15 second timeout for now tid = self.connection.add_timeout(15, authentication_timeout) while self.response is None: self.connection.process_data_events() # once we have a response, cancel the timeout self.connection.remove_timeout(tid) try: data = json.loads(self.response) if … -
serialize verbose fields of related foreign key object in django REST?
for an app with three objects - User, Event, and Action where users take actions on events creating an object like: class Action(models.Model): event = models.ForeignKey('CauseActivity', on_delete=models.CASCADE, related_name='actions') user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='actions') type = models.CharField(max_length=100, choices=ACTION_TYPES) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) I would like our RESTful API to be able to return the actions for one specific user, either within the user request (which requires no extra API calls) or with one additional request (get actions by user) a simple User serializer with 'actions' as a field will return only the obj ids (response to GET ex: "actions":[108,109]) from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( ..., 'actions', ) I am aware of nesting to serialize custom fields like username = serializers.ReadOnlyField(source='user.name') but is there a way to use serializers.ListSerializer or .ModelSerializer to serialize the full set of Action objects' fields within my UserSerializer? I read through https://www.django-rest-framework.org/api-guide/serializers/ and best approach isn't really clear to me. thanks -
I can't display an error message in my password change form with Django
I use the built in PasswordChangeForm class but I rewrite the html of the template because I don't like the default placement of error messages (strangely located between the "new password" field and the "new password confirmation" field). My form works when I correctly fill in old and new passwords. Otherwise, the page reloads without indication. When it works I am redirected to a "PasswordChangeDoneView" page. Ideally, I would prefer not to be redirected but it's less important. url.py : path('password_change/', auth_views.PasswordChangeView.as_view(), name = 'password_change'), path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(), name = 'password_change_done'), views.py : @login_required def password_change(request): if request.method == 'POST': password_form = PasswordChangeForm(instance = request.user, data = request.POST) if password_form.is_valid(): password_form.save() update_session_auth_hash(request, password_form.user) # <-- keep the user loged after password change messages.success(request, 'Your password was successfully updated!', extra_tags='safe') else: messages.error(request, 'Something went wrong', extra_tags='safe') else: password_form = PasswordChangeForm(instance = request.user) return render(request, 'registration/password_change_form.html', {'password_form': password_form}) password_change_form.html : <form action='.' method='post' enctype='multipart/form-data'> <p> <label for='id_old_password'>Old password:</label> <input type='password' name='old_password' autofocus='' required='' id='id_old_password'> </p> {% if messages %} {% for message in messages %} <p class='border-alert {{ message.tags }}'>{{ message|safe }}</p> {% endfor %} {% endif %} <p> <label for='id_new_password1'>New password:</label> <input type='password' name='new_password1' required='' id='id_new_password1'> <span class='helptext'></span> </p> <p> <label for='id_new_password2'>New … -
Model with ForeignKey "missing 1 required positional argument"
I literally started with pythond and django a week ago. Watched a good bunch of tutorials and looked around here. This is my model. Two tables, one with Customers and one with Applications. The applications are mapped to Customers. class Customer(models.Model): customer = models.CharField(max_length=255) description = models.TextField(null=True) def __str__(self): return self.customer class Application(models.Model): application = models.CharField(max_length=255) description = models.TextField(null=True) customer_id = models.ForeignKey('Customer',on_delete=models.PROTECT,blank=True, null=True) def __str__(self): return self.application This is my view function to create a new customer def new_customer_view(request, customer_id): form = CustomerForm(request.POST or None) if form.is_valid(): form.save() form = CustomerForm() context = { 'customer': Customer.objects.get() } return render(request, 'forcast/new_customer.html', context ) When I try to access the form I get: TypeError: new_customer_view() missing 1 required positional argument: 'customer_id' -
Do Django model ids start at 0 or 1?
I have tried looking at both the documentation for AutoField and automatic primary key fields, neither of which have the answer. If they start with 0, does this mean that an AutoField will never have the value of 0 unless I manually override it? -
Editable local apps with Pipenv and Django
TL;DR How can I propagate changes made in a locally developed Django application to a locally developed Django project, dependent on that application (w/o having to uninstall and reinstall the application)? Full Story I'm using pipenv to manage my dependencies on a Django 'project'. The project comprises several Django 'apps', each of which was built in-house as a standalone solution and each of which exists locally on my machine (but not in any online public repository). The applications were packaged using setup.py and installed into the main project. In order for changes made in one of the standalone applications to take effect in the main Django project, I (seemingly) have to uninstall and reinstall the application. Using pipenv install -e . from my main project directory does not seem to solve the problem. (Admittedly, I am naive about the in-and-outs of Python packaging, setup tools, etc.). What, if anything, am I doing wrong? Alternatively, is there any workaround for this? -
Need Someone To Help Me To Apply to job in upwork (Approved Account)
My Account On Upwork Is Approved I Need Someone who has experience in Upwork to help me accept any project knowing that I have passed the Upwork Readiness Test enter image description here -
Django 2.1 UpdateView rises Integrity error
I have this UpdateView Class that shows an integrity error saying that the Primary Key cannot be null: Request Method: POST Request URL: http://127.0.0.1:8000/smce/employees/update-emergency-contact/855/ Django Version: 2.1.2 Exception Type: IntegrityError Exception Value: (1048, "Column 'id_employee_id' cannot be null") I have checked everything and it seems to be correct. Even when I update the data directly in the DataBase I see reflected the value when pulling the initial data into the form. urls.py: path('employees/update-emergency-contact/<int:pk>/', EC_required(1,2)(views.EmployeesUpdateEContact.as_view()), name='employees-update-eContact'), models.py: class EmergencyContact(models.Model): id_employee = models.OneToOneField(Employees, on_delete=models.CASCADE, primary_key=True) # contactName = models.CharField(max_length=255, null=True) id_parentesco = models.ForeignKey(Parentescos, on_delete=models.PROTECT, null=True) # contactPhone = models.CharField(max_length=14, null=True) forms.py: class createEmergencyContactForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(createEmergencyContactForm, self).__init__(*args, **kwargs) self.fields['contactName'].required = False self.fields['id_parentesco'].required = False self.fields['contactPhone'].required = False class Meta: model = EmergencyContact fields = [ 'contactName', 'id_parentesco', 'contactPhone' ] widgets = { 'contactName': forms.TextInput(attrs={'class': 'form-control text-capitalize', 'name': 'contactName'}), 'id_parentesco': forms.Select(attrs={'class': 'form-control', 'name': 'parentescto'}), 'contactPhone': forms.TextInput(attrs={'class': 'form-control', 'name': 'contactPhone', 'id': 'contactPhone'}) } views.py: class EmployeesUpdateEContact(UpdateView): form_class = form_EC model = EmergencyContact template_name = 'employeesControll/employee/update_form.html' def get_success_url(self, **kwargs): return reverse('employeesControll:employee-details', kwargs={'pk': self.kwargs['pk']}) def get_context_data(self, **kwargs): kwargs['employees'] = Employees.objects.get(pk=self.kwargs['pk']) kwargs['filter'] = self.request.GET.get('filter', 'list') return super(EmployeesUpdateEContact, self).get_context_data(**kwargs) def post(self, request, *args, **kwargs): self.objects = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return … -
Dynamically render matrix like form in Django
I am using a Django model to represent day-hour combinations. The goal is to render a matrix-like form with the days on the x-axis and the hours on the y-axis. The user can check each combination to define when a vehicle is available during a week. The model looks as follows: class TimeMatrix(models.Model): MO00 = models.BooleanField(default=False) MO01 = models.BooleanField(default=False) MO02 = models.BooleanField(default=False) MO03 = models.BooleanField(default=False) .... SO22 = models.BooleanField(default=False) SO23 = models.BooleanField(default=False) I like to render the corresponding form coming from the CreateView as the mentioned matrix. The html to do this requires a list of days = ['MON', 'TUE', ..., 'SUN'] and hours = ['00', '01', ..., '23'] in order to render the form dynamically. The following html shows this without using the form the Django CreateView provides: <form action="#"> <div class="table-responsive"> <table class="table"> <thead class="thead-light"> <tr> <th scope="col">Day</th> {% for h in hours %} <th scope="col">{{h}}</th> {% endfor %} </tr> </thead> <tbody> {% for d in days %} <tr> <th scope="row" class="wt-col">{{d}}</th> {% for h in hours %} <td><input type="checkbox" name="{{d}}{{h}}" value="{{d}}{{h}}" id="id_{{d}}{{h}}"></td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> </form> Since I like to use the security measures build into Django forms I like … -
Can Django accept and validate multiple values in one field?
First off, I am very familiar with using ForiegnKeys in my data models. I don't need or want that complex of a relationship in this particular scenario. (I'm capturing name-servers and NTP-servers for a DHCP service. A table to capture such servers to use as a FK would be overkill.) What I do need is to capture multiple (say zero to 4) IP addresses and store them into a single CharField as a comma-separated list. I know I can do this via a simple CharField and clean() that splits on the commas and checks each IP or uses a regex that expects multiple values. But, is there a better way (with Django 2.0)? I've looked at ComboField and MultiValueField but the examples are few and my impression is those are rigid for how many values are expected. Like if GenericIPAddressField didn't exist, you might possibly use MultiValueField to verify each of the 4 octets. This will be used in the Admin site, if that matters. -
django-map-widgets inline not rendering new inline maps
I am using django-map-widgets in my Django Admin for storing series of coordinates/positions more easily. The first mandatory point appears automatically while loading the form and its map is loading fine. However, when I click the "Add" button for getting more inlines maps, the form loads but the map is not generated. I have notices that django-map-widgets loads a template dynamically and that template only contains a <script type="application/javascript"> ... </script>, so it looks like it is not running the script when the template loads with the "Add" button. I find it weird since in the docs, the inlines apparently work just fine. So I do not know what is wrong. I am using the latest version of both Django and django-map-widgets. I am using Django Suit, but it does not look like it is the problem, since I tried removing it and had the same behavior. -
Django 2.1.2 - AttributeError: 'UserProfile' object has no attribute 'object'
I am having problems with a class named SearchView(ListView) which I am using to display a search query. This class "SearchView" is being inherited from a UserProfile View, so that users can use the search bar in the profile view to search any post. When I try to load the route /users/// it raise the Following error: 'UserProfile' object has no attribute 'object. I guess it is because I am overriding the get_context_data() method. This is the code of the SearchView class: class SearchView(ListView): model = Post def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) try: context['list_result'] = self.result except: messages.error(self.request, 'test') finally: return context def get(self, request, *args, **kwargs): if request.GET.get('search'): search_query = request.GET.get('search', None) self.result = Post.objects.filter(title__icontains=search_query).order_by() if not self.result: messages.error(request, f'No results found for {search_query}') return super().get(request, *args, **kwargs) This is the code of the UserProfile View: @method_decorator(login_required, name='dispatch') class UserProfile(SearchView, DetailView): model = User context_object_name = 'user_object' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) try: relevant_post = Post.objects.filter(author_id=self.kwargs.get('pk')).order_by('-rating')[0] data['relevant_post'] = relevant_post except IndexError: pass finally: return data This is the search template: {% extends 'blog/base.html' %} {% load static %} {% block content %} <form class="align-middle w-50" type="GET" style="margin: 0"> <span class="fa fa-search form-control-feedback"></span> <input type="text" class="form-control" name="search" …