Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multi-table inheritance and graphene
I am trying to serve a graphql endpoint through django-graphene. I have the following models: class BaseModel(models.Model): fk = models.ForeignKey(MainModel, related_name='bases') base_info = models.CharField(...) class ChildModel(BaseModel): name = models.CharField(...) MainModel being my central data model. There are several variants of ChildModel, which explains the multi-table inheritance used here. I have been able to get things to work with this schema declaration: class BaseModelType(DjangoObjectType): class Meta: model = BaseModel class ChildModelType(DjangoObjectType): class Meta: model = ChildModel class MainModelType(DjangoObjectType): class Meta: model = MainModel which allows the following graphQL query: { mainModel(id: 123) { id bases { id baseInfo childmodel { id name } } } } However, I'd like to flatten this the way Django understands the inheritance, so that I can query the data like this: { mainModel(id: 123) { id bases { id baseInfo name <--- this field from the child is now on the base level } } } I suspect the answer is in how I declare ChildModelType, but I haven't been able to figure it out. Any hints appreciated! -
Jinja & Django Invalid block tag : 'set', expected 'endblock'
I need to increment the variable count but I'm getting this error, I have already searched, they say I should install jinja, however the code worked perfectly before adding {% set count = 1 %} , which means that it's not a matter of installation. here is my Template code : {% set count = 1 %} {% for form in formset %} <tr style="border:1px solid black;" id="{{ form.prefix }}-row" class="dynamic-form" > <td><div class="col-xs-1"><b><p name="np1">{{ count }}</p></b></div></td> <td > {% render_field form.dateOperation class="form-control" %}{{form.dateOperation1.errors}} </td> <td>{% render_field form.designation class="form-control" %}{{form.errors}} </td> <td> {% render_field form.typeTiers class="form-control" %}{{form.typeTiers.errors}} </td> <td> {% render_field form.tiers class="form-control" %}{{form.tiers.errors}} </td> <td>{% render_field form.numfacture class="form-control" %}{{form.numfacture.errors}} </td> <td>{% render_field form.montant class="form-control" %}{{form.montantdebit.errors}} </td> {% for radio in form.typeMontant %} <td> {{ radio.tag }} </td> {% endfor %} <td>{% render_field form.montant class="form-control" %} {{form.montantdebit.errors}} </td> </tr> {% set count = count + 1 %} {% endfor %} and this is the raised error: Invalid block tag on line 51: 'set', expected 'endblock'. Did you forget to register or load this tag? Any help please , Thank you in advance. -
inspectdb command for json in django2 generates django.contrib.postgresql.fields.JSONField instead of django.contrib.postgres.fields.JSONField?
I switched to django 2 because it supports detecting json fields with inspectdb, but when I run the inspectdb it generates django.contrib.postgresql.fields.JSONField which I don't know where to import it from. As specified in django documentation here django_inpectdb_doc I understand that can fix it by adding import django.contrib.postgres.fields.JSONField bu the problem is that it was automatically generated django.contrib.postgresql.fields.JSONField (notice the bold text). class AsyncResultsStore(models.Model): task_id = models.CharField(max_length=255) created = models.DateTimeField(blank=True, null=True) status = models.CharField(max_length=255) result = django.contrib.postgresql.fields.JSONField(blank=True, null=True) info = models.CharField(max_length=255) arguments = django.contrib.postgresql.fields.JSONField(blank=True, null=True) chip_meas_result = models.ForeignKey(Chipmeasurementresult, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'async_results_store' I want to do: django.contrib.postgres.fields but that is not possible because the generated line is: django.contrib.postgresql.fields postgressql instead of postgres In the link of documentation above it is specified that I should put in settings.py installed apps: 'django.contrib.postgres' which I did. should I import from somewhere else or is this a buggy behavior in django2? -
Can I add fields to my model without code?
Let me explain this. I have an app with different forms to answer.I need my moderator to create these form without code. The moderator creates a form and adds questions. It is also preferable that he has the opportunity to group questions and make different type of anwers- text or checkbox. Is it possible to using Django? -
How to separate docker and docker-compose from Django source folder
I am trying to achieve this project layout structure: project root: - docker: - docker-compose.yml - Dockerfile-app - Dockerfile-mysql - src: - djangoproj - core - requirements.txt docker-compose.yml version: '3' services: app: build: context: . dockerfile: Dockerfile-app command: /bin/bash -c "cd /var/www/app/src/djangoprj && pip install -r requirements-develop.tx && python manage.py runserver 0.0.0.0:8000 || sleep 100000" container_name: website_app depends_on: - mysql links: - mysql ports: - '8000:8000' volumes: - ../:/var/www/app working_dir: /var/www/app/src/djangoproj mysql: build: context: . dockerfile: Dockerfile-mysql container_name: website_mysql environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: local MYSQL_USER: yoo MYSQL_PASSWORD: password ports: - '3306:3306' This basically works, the only issue I have, it is that the requirements are built every single time. What I would like is that in the Dockerfile-app to copy the requirements.txt file and then run the pip install which I expect to run only when the requirements.txt was changed. Inside Dockerfile-app: ADD src/djangoproj/requirements.txt / RUN pip install -r requirements.txt From what I know in docker I can't access the parent folder. I was also trying to do app: build: context: .. But doesn't output anything... so I don't know what it is going on... When is the volume added to the docker container? Any help will be so much … -
Passing parameter to view to populate form
It works fine when I specify exactly what the data has to be by doing this form = forms.MakeSale(instance=Laptop.objects.get(Name="NameOfTheLaptop")) But as soon as I try and pass the value to view and query the model, I get the following error: Reverse for 'sale' with no arguments not found. 1 pattern(s) tried: ['sale\\/(?P<laptopname>[^/]+)$'] views.py def laptop_sale(request, laptopname): form = forms.MakeSale(instance=Laptop.objects.get(Name=laptopname)) if request.method == 'POST': form = forms.MakeSale(request.POST, request.FILES) if form.is_valid(): readyinstance = form.save(commit=False) readyinstance.added_by = request.user readyinstance.save() else: return render(request, 'laptops/laptop_sale.html', {'form': form}) return render(request, 'laptops/laptop_sale.html', {'form': form}) urls.py path('sale/<str:laptopname>', views.laptop_sale, name = "sale") details.html {%for detail in details%} ... <a class="btn btn-success" href="{%url 'laptops:sale' laptopname=detail.Name%}" > This laptop has been sold »</a> {%endfor%} -
Django Date time automatic by timezone
I need to determine Django get the timezone from computer/web automatically and each time use data or time use it in suitable format. For example in USA MM/DD and not DD/MM .. I detrmine: USE_L10N = True USE_TZ = True Another help how can I check it from my computer? -
How to implement Singleton in Django
I have an object that need to be instantiated ONLY ONCE. Using redis for caching the instance failed with error TypeError: can't pickle _thread.lock objects while I can comfortably cache others instances as need. Thus I am looking for a way to create a Singleton object, class SingletonModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): # self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) # if self.can_cache: # self.set_cache() def delete(self, *args, **kwargs): pass class Singleton(SingletonModel): singles = [] @classmethod def setSingles(cls, singles): cls.singles = singles @classmethod def loadSingles(cls): sins = cls.singles log.warning("*****Found: {} singles".format(len(sins))) if len(sins) == 0: sins = cls.doSomeLongOperation() cls.setSingles(sins) return sins In the view.py I call on Singleton.loadSingles() but I notice that I get Found: 0 singles after 2-3 requests. Please what is the best way to create Singleton on Djnago without using third party library that might try serialising and persisting the object (which is NOT possible in my case) -
Datepicker doesn't take the value
I have a problem with a django form: I have some input, select and 2 date field implemented with a datepicker. When I submit my form the form doesn't return the value inserted in the date field. It seems is a problem with the html name of the field. Can someone help me? Thanks. This is my code: forms.py class Dispositivi(forms.Form): tipo_dispositivo = forms.ChoiceField(choices=dev_choices(), label="Tipo dispositivo", required=False) codice_identificativo=forms.CharField(label="Codice Identificativo", required=False, max_length=30) data_rilascio_da=forms.DateField(widget=forms.DateInput(attrs= { 'id': 'data_rilascio_da', 'class':'datepicker' }), label="data_rilascio_da", required=False) data_rilascio_a=forms.DateField(widget=forms.DateInput(attrs= { 'class':'datepicker', 'id': 'id_date_a', 'label': 'Data rilascio a', 'name': 'data_rilascio_a' }), required=False) scratch=forms.CharField(label="Scratch Card", required=False, max_length=10) this is my views.py: def dispositivi(request): if request.method == 'POST': form = Dispositivi(request.POST) print('form: ', form) datilist = {} if form.is_valid(): cleaned_data = form.cleaned_data tipo_dispositivo = cleaned_data.get('tipo_dispositivo') data_rilascio_da = cleaned_data.get('data_rilascio_da') print('data presa nella fun: ', data_rilascio_da) data_rilascio_a = cleaned_data.get('data_rilascio_a') scratch = cleaned_data.get('scratch_card') dati_input=dict( tipo_dispositivo = tipo_dispositivo, codice_identificativo = codice_identificativo, data_rilascio_da = data_rilascio_da, data_rilascio_a = data_rilascio_a, scratch_card = scratch_card ) and this the base.html + render form: <link rel="shortcut icon" type="image/png" href="{{STATIC_URL}}/images/favicon.ico"/> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script> {% block extrascript %} <script type="text/javascript" > $(function () { $('#id_date_da').datepicker({ dateFormat: 'yy-mm-dd' }); $('#id_date_da').datepicker(); $('#id_date_a').datepicker({ dateFormat: 'yy-mm-dd' }); $('#id_date_a').datepicker(); }); </script> {% endblock %} <style> … -
django form field validation using parameter from URL
I have a visit-create class based on a CreateView. It accesses the organization from the URL, so it's passed in as a keyword arg. class VisitCreate(LoginRequiredMixin, UserOrgRequiredMixin, CreateView): model = models.Visit form_class = VisitCreateForm # template_name is "visit_form.html" from CreateView def form_valid(self, form): # get the patient for this visit patient = models.Patient.get_by_pk(self.kwargs['patientId']) if not patient or patient.organization.name != self.kwargs['orgStr']: raise SuspiciousOperation('Patient does not exist') I want to write a form field validator that checks something about the visit, but it needs the orgStr. Here is the current form field validator, but it can't get the orgStr: class VisitCreateForm(ModelForm): class Meta: model = models.Visit ... # Allow only one visit per day def clean_visit_date(self): visit_date = self.cleaned_data['visit_date'] if models.Visit.get_visits(visit_date, visit_date, self.kwargs['orgStr']): raise ValidationError('There is already a visit on this date') How do I mark a field error on visit_date? Either I have to pass orgStr to the form somehow, or mark the field error in VisitCreate.form_valid. Please don't suggest adding the orgStr as a hidden field in the form. That seems crazy. -
Django serializer validate not firing
I have a choices field on a Django model as such: VALID = 0 INVALID = 1 FLANGGED = 2 NOT_REVIEWED = 3 STATUS_CHOICES = ( (VALID, 'Valid'), (INVALID, 'Invalid'), (FLANGGED, 'Flagged'), (NOT_REVIEWED, 'Not Reviewed'), ) review_status = models.PositiveSmallIntegerField( choices=STATUS_CHOICES, default=NOT_REVIEWED) When I surface this to the front-end I use obj.get_review_status_display() to get the String value. When I'm editing this model (via DRF), and I pass the integer value, I can see my validate() method on my serializer is getting called. However, when I pass the string value to patch the model, the validate() never gets called: def validate(self, data): valid_status_key = False if 'review_status' in data: for k, v in Application.STATUS_CHOICES: if v == data['review_status']: valid_status_key = k if not valid_status_key: raise serializers.ValidationError('Invalid review status') else: data['review_status'] = valid_status_key # only called when data['review_statuse'] is an Int, not String assert False, [data, valid_status_key] return data So... How can I pass the String value to the backend, and hit the validate() method to validate it against my Choices field? -
Django get dictionary of siblings without using prefetch related?
I have three models like the following and have a list of Boys. How can I get a list of each of their sisters? Unfortunately I can not use prefetch related as I am stuck using a very old version of django. class Parent(model.Model): name = models.CharField(max_length=50) class Boys(model.Model): parent = models.ForeignKey(Parent) name = models.CharField(max_length=50) class Girls(model.Model): parent = models.ForeignKey(Parent) name = models.CharField(max_length=50) Desired output would be something like this: { boy1: [ sister1, sister2 ], boy2: [ .. ] } Thanks in advance for any help! -
django - how to return one to many
this is my model class plans(models.Model): plan_name = models.CharField(max_length=50) plan_price = models.IntegerField(default=0) plan_is_active = models.BooleanField(max_length=1, default='1') def __str__(self): return self.plan_name class plan_cat(models.Model): cat_name = models.CharField(max_length=50) plan = models.ForeignKey(plans, on_delete=models.CASCADE) cat_is_active = models.BooleanField(max_length=1, default='1') def __str__(self): return self.cat_name my serializer is class PlanSerializer(serializers.ModelSerializer): class Meta: model = plans fields = ('plan_name','plan_price') class CatSerializer(serializers.ModelSerializer): plan = PlanSerializer() class Meta: model = plan_cat fields = ('cat_name','plan') this is my view class plan_details(APIView): def get(self, requests): queryset = plan_cat.objects.filter(cat_is_active='1') serializer = CatSerializer(queryset, many=True) return Response(serializer.data) when i call this view http://localhost:8000/plans/details/ getting this output [ { "cat_name": "category 1", "plan": { "plan_name": "free", "plan_price": 0 } }, { "cat_name": "category 2", "plan": { "plan_name": "paid", "plan_price": 10 } }, { "cat_name": "category 3", "plan": { "plan_name": "free", "plan_price": 0 } } ] instead i want a output like this [ { "plan_name": "free", "plan_price": 0"": " "cat_name": { "category 1", "category 3", } }, { "plan_name": "paid", "plan_price": 0"": " "cat_name": { "category 2", } }, ] the problem is the foreign key is with the second model, so i cant serialize to get the grouped content output as mentioned above. do i have to rewrite the model or serializer class ? -
ForeignKey to OneToOne: ProgrammingError: relation already exists (but doesn't really)
I have a db with the following Django Migrations: 0001_initial.py: migrations.AddField( model_name='extrashirtprice', name='sibs_weekend', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='registration.SibsWeekend'), ), So I want to make it a OneToOneField instead. So there's a new migration: 0012_auto.py: operations = [ migrations.AlterField( model_name='extrashirtprice', name='sibs_weekend', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='registration.SibsWeekend'), ), ] I checked and ensured that the operation done in 0012 wasn't done anywhere else. When I run migrate, I get: django.db.utils.ProgrammingError: relation "registration_extrashirtprice_sibs_weekend_id_6626038b_uniq" already exists I looked at Django - Change a ForeignKey relation to OneToOne but they were talking about using --fake which I feel is a little too hacky. Plus we deploy with an automated script so I want to avoid adding commands if possible. This post also had no actual accepted answers and it was in the context of south migrations so I'd rather see how it can be done using Django migrations in a better way. I could just use ForeignKey with a unique constraint (I assume) but I want to use the more official OneToOneField for this if possible. NOTE: I am running these migrations on a database with data. It's not empty so if the issue has anything to do with the fact that there's data, please show me how to fix that … -
Upload multiple files using Files Field in Django Admin
Here i have class models: models.py class Parameter(models.Model): files = models.FileField( upload_to='uploaded', blank=True, null=True, ) and i have this in my admin.py class ParameterAdmin(admin.ModelAdmin): form = Parameter and i add it in my forms.py so it can select more then one file class ParameterForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ParameterForm, self).__init__(*args, **kwargs) self.fields['files '] = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}), ) But, after i try to choose and select multiple files via django admin.. Not all files are uploaded and it only upload one latest selected file.. How can i upload multiple files via django admin..? I don't need views.py and html from.. i just need django admin can upload multiple files.. Simple -
Firebase Cloud Messaging + Django: How to securely store the service account's private key?
I just started implementing FCM into my Django backend. The problem I encountered is the following. In the docs you are told to generate a private key JSON file and securely store it. Usually I store my keys in an os.env variable. But this is not possible, since this is a whole file and not just a value. Also on the same page, the doc tells you how to get a request token: def _get_access_token(): """Retrieve a valid access token that can be used to authorize requests. :return: Access token. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( 'service-account.json', SCOPES) access_token_info = credentials.get_access_token() return access_token_info.access_token As you can see here, the library needs direct access to the file. So my question is? How do I securely store this? I'm currently hosting on heroku, so I need this in my version control system. -
Adjusted local models, getting columns do not exist in production environment
I have a django blog project via PythonAnywhere using PostGres, and have recently tried to push my changes (mainly implementing Django-MPTT) to my models to my production server via git. I have ran migrations etc, but when I load the site, I got a server error 500. The error logs look a bit like this : "/home/DMells123/.virtualenvs/nomadpadvenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute#012 return self.cursor.execute(sql, params)#012django.db.utils.ProgrammingError: column posts_category.lft does not exist#012LINE 1: ...gory"."parent_id", "posts_category"."parentSlug", "posts_cat...#012 The original error said category.name doesn't exist, which is a new field I added to my Category database (well, actually I renamed it). I added this column to the database in my production environment via psql : (ALTER TABLE ADD COLUMN name varchar(200) and then I got another column does not exist, namely the one above. This comes from making use of Django-MPTT recently, and I've realised I'm out of my depth with creating these columns which are not visible in my models. My question is, have I done this wrong? I understand that I am trying to impose a changed MVT structure onto my existing blog posts data, but is there an easier way to get this fixed? This error will keep re-appearing but I don't … -
django.db.utils.IntegrityError: UNIQUE constraint failed: products_product.slug
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: products_product.slug utlis.py import random import string from django.utils.text import slugify def random_string_generator(size=10,chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug=None): """ This is for a Django project and it assumes your instance has a model with a slug field and a title character (char) field. """ if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) return slug models.py from django.db import models import random import os from .utils import unique_slug_generator from django.db.models.signals import pre_save,post_save def get_filename_ext(filepath): base_name=os.path.basename(filepath) name,ext=os.path.splitext(base_name) return name,ext def upload_image_path(instance,filename): #print(filename) new_filename=random.randint(1,3010209312) name, ext=get_filename_ext(filename) final_filename='{new_filename}{ext}' return "products/{new_filename}/{final_filename}" class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) def featured(self): return self.filter(featured=True,active=True) class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model,using=self._db) def all(self): return self.get_queryset().active() def featured(self): return self.get_queryset().featured() def get_by_id(self, id): qs = self.get_queryset().filter(id=id) # Product.objects == self.get_queryset() if qs.count() == 1: return qs.first() return None class Product(models.Model): title=models.CharField(max_length=120) slug = models.SlugField(unique=True) description=models.TextField() price=models.DecimalField(decimal_places=2,max_digits=20,default=38.25) image=models.ImageField(upload_to=upload_image_path,null=True,blank=True) featured=models.BooleanField(default=False) active=models.BooleanField(default=True) objects=ProductManager() def __str__(self): return self.title def product_pre_save_receiver(sender,instance,*args,**kwargs): if not instance.slug: instance.slug=unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver,sender=Product) … -
Django - how to use a template tag within a url
I have a template tag named 'string_after' that I want to use within a URL. however I cant find anywhere what the syntax would be to use the tag within a URL? I would use the tag as such {% string_after type.site_type 'd' %} which I tried to put inside the url but it is just seen as another url variable instead of the function <li><a href="{% url 'sites:site_list' 'all' string_after type.site_type 'd' %}"> %}">{{ type.site_type }}</a></li> Does anybody know the correct syntax? Thanks -
How to get around "missing 1 required positional argument" error when doing an AJAX call
I get a TypeError: options() missing 1 required positional argument: 'context' on the following code: def post_ad(request): filename = request.POST.get('temp_s3_url') boost_form = AdvertisePostForm(request.POST or None, request.FILES or None) if boost_form.is_valid(): instance = boost_form.save(commit=False) if Post.objects.filter(hash=instance.hash).exists(): instance.hash = random_string() instance.ad = True instance.save() context = { 'hash': instance.hash, } return options(request, context) context = { 'boost_form': boost_form } return render(request, 'advertising/post_ad.html', context) def options(request, context): ad = get_object_or_404(AdvertisePost, hash=context['hash']) if request.is_ajax(): total_price = request.POST.get('total_price') print('Total price:', total_price) context = { 'ad': ad } return render(request, 'advertising/options.html', context) js ... var total_price = Math.round(amount); $.ajax({ type: 'POST', url: "/advertise/options/", data: { csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), total_price: total_price, }, success: function (data) { console.log('Success!'); console.log(amount); } }); } when I remove context as a positional argument, or change def options(request, context): to def options(request, context="something"): - it works (there's no error and the ajax call successfully prints in my view. However I have to keep the context as it has important data. How can I get around this problem? -
Override django form field
I've been research a lot about this, but don't get any answer accurate. Here's the deal: I want to override where forms.Field is used from my own, that is, where all classes that inherit from forms.Field, inherit from my own. Why? I like to add some properties that i'll use in every single field. Anyone? -
Configuring static files in Django in production
I'm having difficulty configuring static files in Django 2.0.3 The production server deployed on Heroku works properly when DEBUG = True, but as soon as I switch it to DEBUG = False, I get an Application error, spawning 9 identical ERROR (EXTERNAL IP): Internal Server Error emails. Further confounding me, is that the local dev server is set to DEBUG = True, yet the paths to my static files using href="{% static "images/apple-icon-57x57.png" %}" show the full path to Amazon S3 href="https://r2cp-assets.s3.amazonaws.com/static/images/apple-icon-57x57.png". I thought that DEBUG = True would serve static files from my local server? Setting DEBUG = False on the local dev server does not cause any problems. I'm using storages.backends.s3boto3 for both static and media storage. Running Collectstatic doesn't return any errors. Is there something that's causing a problem with the creation of a manifest entry? I've tried with and without setting STATIC_ROOT. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Here's the text of the error message from the prod server when DEBUG = False. Internal Server Error: / ValueError at / Missing staticfiles manifest entry for 'images/apple-icon-57x57.png' Request Method: GET Request URL: https://obscure-lake-48617.herokuapp.com/ Django Version: 2.0.3 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.4 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', … -
Django & js : My formset forms are dependent on each other
I have the following js that adds forms to my template whenever I click on the button "" function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function addForm(btn, prefix) { var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); var row = $('.dynamic-form:first').clone(true).get(0); $(row).removeAttr('id').insertAfter($('.dynamic-form:last')).children('.hidden').removeClass('hidden'); $(row).children().not(':last').children().each(function() { updateElementIndex(this, prefix, formCount); $(this).val(''); }); $('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1); return false; } I call this script in my header : $(function () { $('#add-row').click(function() { return addForm(this, 'form'); //$('.add-row').hide(); }); }) and this is my template : <form action="/caisse" method="POST" enctype="multipart/form-data" id="personForm" data-tiers-url="{% url 'ajax_load_tiers' %}" >{% csrf_token %}{{ form.non_field_errors }} <table align="center"> <!-- <div class="row" style="padding-left: 24%; padding-top: 3%"></div> --> <tr> <td width="10%"></td> <td><input id="uploadFile" placeholder="Choose File" class="form-control" /></td> <td><div class="btn btn-primary" id="divInput"><span>importer</span> {% render_field form1.myfile id="uploadBtn" style=" position: absolute;top: 0;right: 0;margin: 0; padding: 0;font-size: 20px;cursor: pointer;opacity: 0;filter: alpha(opacity=0);" %} </div></td> </tr> </table> <table style ="border-collapse: separate;border-spacing: 15px;" id="id_forms_table"> {% for form in formset %} <tr style="border:1px solid black;" id="{{ form.prefix }}-row" class="dynamic-form" > <td><div class="col-xs-1"><b><p name="np1">1</p></b></div></td> <td > … -
Using Django's Q to get search result from CBV's
I am trying to implement a simple search feature in my CBV's ListView below is how my ListView looks like class Postlist(SelectRelatedMixin, ListView): model = Post select_related = ('user', 'group') I would like to achieve something like this def post_list(request): posts = Post.objects.all() query = request.GET.get('q') if query: posts = Post.objects.filter( Q(title__icontains=query)| Q(user__username=query)| Q(body__icontains=query) ) context = { 'posts': posts, } return render(request, 'blog/post_list.html', context) but I guess I can't account for the SelectRelatedMixin. I am fine with using either. FBV or CBV as long as I can get the search working -
attempt to write a readonly database in apache server with django
I tried to deploy mi site using this tutorial: https://www.unixmen.com/configure-django-with-apache-centos-7/ in redhat 7 but when I need to write something in the database always have this exception: attempt to write a readonly database My Directory have apache as owner, it has 755 as permissions also the db.sqlite3, but this doesn't work