Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The static file is not loaded in the bootstrap template. Django app
In my purchased bootstrap template, static files are not loaded (only some they display correctly). What is this error caused by? How can I solve it? I use the latest version of django and python3. Example: {% load static %} [...] <!-- SVG Background --> <div id="SVGMainHero" class="col-lg-9 col-xl-7 svg-preloader d-none d-lg-block position-absolute top-0 right-0 pr-0" style="margin-top: 105.6px;"> <figure class="ie-main-hero"> <img class="js-svg-injector" src="{% static 'assets/svg/illustrations/main-hero.svg' %}" alt="Image Description" <!-- DO NOT SEE THIS PHOTOS --> data-img-paths='[ {"targetId": "#SVGMainHeroImg1", "newPath": "{% static 'assets/img/750x750/img2.jpg' %}"} ]' data-parent="#SVGMainHero"> </figure> </div> [...] <!-- End SVG Background --> Any help will be appreciated. -
Django framework form is trying to insert a new record instead of updating
Django 1.8.3 python 3.6 I have a default Django framework form I use for both update and create records. The primary key ("id" field) is generated by Django. The rest is defined in my model (see below). The model is subclassed from AuditModel class which overloads save method. Everything works at this point, i.e. I can create new records or update existing records using standard Django forms interface. class Patient(AuditModel): internal_id = models.CharField(max_length=100, null=True, blank=True, help_text="Internal ID") external_id = models.CharField(max_length=100, null=False, blank=False, help_text="External ID", verbose_name="External ID") label = models.ForeignKey(Label, help_text="Label") class AuditModel(models.Model): created = models.DateTimeField(null=True,editable=False) updated = models.DateTimeField(null=True,editable=False) def save(self, *args, **kwargs): date = timezone.localtime() if self._state.adding : self.created = date self.updated = date super(AuditModel, self).save() My question: I would like external_id to be unique (but not a primary key), i.e. external_id = models.CharField(max_length=100, null=False, blank=False, help_text="External ID", unique=True, verbose_name="External ID") Once I added unique=True to the definition of the external_id field, the behaviour of the view changes: on attempt to update existing record I get an error message next to external_id textbox "Product with this External ID already exists." and no change happens in the DB. Somehow presence of unique=True in the definition of the external_id field make Django … -
django restframework: blank=False and default='x' creates a modelsearializer with required=False field. how to circumvent?
See example below, that will create a serializer with a not required testing field (obviously, as there is a default). I know I can add the field manually to the serializer, with required=True. But, having many fields, I would like to have DRF do the work for me. Or I could remove the default on the modelfield. Dont want this either...is there a thing, like required_fields, on the Meta, perhaps? Or another workaround? Model class MyModel(models.Model): testing = models.CharField(max_length=3, blank=False, default='x') Serializer class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel The reason why I need this: Having a vue.js CRUD like app, that is creating new instances...without specifying the initial fields on the object. -
Django 2.1/PostgreSQL - can I prevent deleting model objects?
There were some questions in the past about this but as Django grows, there are many new database functions. I'm looking for a way to prevent model to be deleted from anywhere by anyone. I have a model Product and I don't want product to be deleted from database ever. I understand that overriding delete is sometimes a good way but I would like to do it on database level so there is no chance to delete it from shell_plus or any other source. In Postgres, I think, there is a way: CREATE RULE product_del_protect AS ON DELETE TO product DO INSTEAD NOTHING; But I would like to do it throug Django so every migrated database will be affected. And better would be to raise an error. -
Celery Task discovery in Django App only partially working
I have a rather odd issue with task discovery only functioning partially in a Django app. I have an app with structure like: app\ |>celery.py >tasks\ |>__init__.py |>a.py |>b.py |>c.py celery.py: class CeleryAppConfig(AppConfig): name = 'taskapp' verbose_name = 'Celery Config' def ready(self): installed_apps = [app_config.name for app_config in apps.get_app_configs()] app.autodiscover_tasks(lambda: installed_apps, force=True) Init.py: from .a import * from .b import * from .c import * a.py b.py & c.py@ from celery import shared_task @shared_task(bind=True) def Task(self): #do stuff. The issue is that although tasks in a.py and b.py are autodiscovered, tasks in c.py aren't. Copying a function from c.py to a.py means it's recognised, and the reverse not. Ultimately I can make it work without having tasks in multiple files, but its super annoying. I'm running python 3.6 on alpine with django 2 and celery 4.2 -
Autoincrementing field on object save - Django
So far, I have this function: def my_number(): x = '0000' return 'MY{0}'.format(str(int(x) + 1).zfill(len(x))) Which I call like this: number_seq = models.CharField(_("Ref."), unique=True, db_index=True, default=my_number, null=True) It works, but when I try to save a new document, it just creates a new MY0001, and it should be incrementing, like MY0002, MY0003 and so forth. What might be the reason for that? -
ValueError: attempted relative import beyond top-level package (Django)
When i try to migrations of my django app model by writing : python manage.py makemigrations Then raises ValueError: attempted relative import beyond top-level package Here is my project screenshots : https://imgur.com/mB6UoZs https://imgur.com/3ipsrWo Here is my model.py from django.db import models from ..krisi_user.models import krisi_user #from src.krisi_user.models import krisi_user # Creating krisi_user_image Model class problem_image(models.Model): full_name = models.CharField(max_length=250) email = models.CharField(max_length=100) image = models.ImageField(upload_to='images') phone = models.CharField(max_length=50) krisi_user = models.ForeignKey(krisi_user,on_delete= models.CASCADE) def __str__(self): return self.full_name -
Why is a   in a <p> tag changing images on my website
I just developed a website template with Django using a bootstrap theme. When I wanted to add a &nbsp into the image caption it moved the image too. It created a blank space on the right border of the image. Deleting the &nbsp did not remove the blank space. The screenshot is in the comments. When I debug the page it says that the CSS code moved the image by -15px but I can not see anything like this in my CSS. I already deleted the cache of the browser and tried something with CSS. -
Calling function without import the other file function in same directory
I want to call im1.py's want_to_call() method from im2.py Test's class func1() and func1() will be called by im1's some_func() method.... Your help will be appreciated. Thanks in advance im1.py from im2 import Test def some_func(value): Test.func1() print(value) def want_to_call(): return 'called from im2' some_func("ola") im2.py from im1 import want_to_call class Test: def func1(): variable = want_to_call() print(variable) print('How do I call want_to_call method in im1') class Test1: def func(): print('Thanks in advance') -
nginx adding new site causes ERR_TOO_MANY_REDIRECTS
I'm trying to add another Django app to my server. I already have the xmlanalyzer.maciejg.pl up&running, now I'm trying to add to the existing nginx & gunicorn setup another app to be available at fencing.maciejg.pl. I've used the existing XMLAnalyzer gunicorn setup (working fine): #!/bin/bash NAME="xmlanalyzer" # Name of the application DJANGODIR=/home/django/xmlanalyzer # Django project directory SOCKFILE=/home/django/xmlanalyzer/run/gunicorn.sock # we will communicte using this unix socket USER=my-user-name # the user to run as GROUP=my-user-name # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=xmlanalyzer.settings # which settings file should Django use DJANGO_WSGI_MODULE=xmlanalyzer.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) #exec gunicorn -b 127.0.0.1:8001 xmlanalyzer.wsgi:application --pid /tmp/gunicorn.pid ; exec gunicorn -b 127.0.0.1:8001 ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ ## --bind=unix:$SOCKFILE \ --bind=127.0.0.1:8001 \ --log-level=debug \ --log-file=- Here's gunicorn setup for Fencing app (not working): #!/bin/bash NAME="fencing" # … -
Is Djangos FileField the right choice here?
I have an application which stored binary data like this in the past: class Blob(models.Model): content = models.BinaryField() name = models.CharField(max_length=10000, default='') content_type = models.CharField(max_length=1024, default='application/octet-stream') The binary data gets more and more, and I want to store it in a storage server. minio looks good. How to store the data which was in the BinaryField (in DB) before, the most pythonic/django/simple way? I see several ways to solve this now V1: FileField class Blob(models.Model): content = models.FileField() name = models.CharField(max_length=10000, default='') content_type = models.CharField(max_length=1024, default='application/octet-stream') This has the drawback, that deleting files needs to be done by me. See docs about FieldFile.delete() V2: property content I implement this myself using the minio python lib. I use the primary-key of the current blob as file-name. But here again: deleting of the data in the storage server needs to be implemented, too. V3: ... I guess there are more solutions. Please tell me if you see a feasible solution. -
Django installation in virtualenv : MySQL-python error
I'm trying to install Djando in a Python2.7 virtualenv on an OpenSuse 15.0 Installation of django works, but not of MySQL-python : Djando installation documentation pip install MySQL-python Collecting MySQL-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-python Building wheel for MySQL-python (setup.py) ... error Complete output from command /home/u372284/development/pra_manager/djando/venv/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-4TF6HJ/MySQL-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-aVaY0z --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -fmessage-length=0 -grecord-gcc-switches -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector-strong -funwind-tables -fasynchronous-unwind-tables -fstack-clash-protection -g -DNDEBUG -fmessage-length=0 -grecord-gcc-switches -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector-strong -funwind-tables -fasynchronous-unwind-tables -fstack-clash-protection -g -DOPENSSL_LOAD_CONF -fwrapv -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/mysql/mariadb -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o _mysql.c: In function ‘_mysql_ConnectionObject_ping’: _mysql.c:2005:41: error: ‘MYSQL {aka struct st_mysql}’ has no member named ‘reconnect’ if ( reconnect != -1 ) … -
Set Default value for a django ModelChoiceField
I need to set a default value for ModelChoiceField The value is being sent from my views.py. I've looked for some other similar questions but it didn't really help as it was all about ChoiceField with choices not a ModelChoiceField with queryset views.py def edit_package(request, pk): current_package = get_object_or_404(models.Package, pk=pk) edit_package_form = forms.EditPackageForm(request.POST, name=current_package.package_name, teacher=current_package.package_teacher_name, level=current_package.package_level, subject=current_package.package_subject, price=current_package.package_price) if request.method == 'POST': if edit_package_form.is_valid(): pass else: edit_package_form = forms.EditPackageForm(request.POST, name=current_package.package_name, teacher=current_package.package_teacher_name, level=current_package.package_level, subject=current_package.package_subject, price=current_package.package_price) context = { 'current_package': current_package, 'edit_package_form': edit_package_form, } return render(request, 'edit_package.html', context) forms.py class EditPackageForm(forms.Form): def __init__(self, *args, **kwargs): current_name = kwargs.pop("name") # client is the parameter passed from views.py current_teacher = kwargs.pop("teacher") # client is the parameter passed from views.py current_level = kwargs.pop("level") # client is the parameter passed from views.py current_subject = kwargs.pop("subject") # client is the parameter passed from views.py current_price = kwargs.pop("price") # client is the parameter passed from views.py super(EditPackageForm, self).__init__(*args, **kwargs) self.fields['package_name'] = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'value': current_name})) self.fields['teacher_name'] = forms.ModelChoiceField(queryset=models.Teacher.objects.all(), initial=current_teacher, widget=forms.Select(attrs={'class': 'form-control'}), required=False) self.fields['level_name'] = forms.ModelChoiceField(queryset=models.Level.objects.all(), initial=current_level, widget=forms.Select(attrs={'class': 'form-control'}), required=False) self.fields['subject_name'] = forms.ModelChoiceField(queryset=models.Subject.objects.all(), initial=current_subject, widget=forms.Select(attrs={'class': 'form-control'}), required=False) self.fields['package_price'] = forms.IntegerField( widget=forms.NumberInput(attrs={'class': 'form-control', 'value': current_price})) And that is how it looks, TextInput and NumberInput have the default value, but … -
how to render and save 2 models in 1 template in Django
I have 2 models with a ForeignKey relationship . Model1 ……… Model2 fc = models.ForeignKey(Model1) …... no proxy and abstract model... needed??? Is it any chance to render it in 1 template? ( it’s done already) and save both forms in the correspondent models simultaneously? I have written some code(bellow).. it works, but in secondary model fc_id( a key that is in charge for connection to a model1 correspondent object would be set to null, that is ,model2’s data saves, but irrelevant to model1. Model1 saves OK. Sorry for the banal question, if so THX tried Django 2 models 1 form def viewname(request): if request.method == 'POST': form1 = FORM1(request.POST, request.FILES, prefix="form1") form2 = FORM2(request.POST, request.FILES, prefix="form2") if form1.is_valid() and form2.is_valid(): form1.save() # has to do smt with COMMIT=FALSE do smt and COMMIT=TRUE then ??? form2.save() return redirect(reverse_lazy("someURL")) else: form1 = FORM1(prefix="form1") form2 = FORM2(prefix="form2") context = {"form1": form1, "form2": form2} return render(request, "some.html", context) model2 and model1 data should be saved according Foreign Key relationship, but not separatelly -
How to store and access user data in database in Django?
I'm a newbie in Django and I'm building this web app that allows three different types of users to login. A customer, operator and an accountant. When the customer logs in, he is asked to upload two jpeg documents. When he is done, these documents will be converted into editable text(I'm using Google's Tesseract engine for Optical character recognition for this) and this data is stored in three columns. The first two columns are non editable but the third is editable. In the third column, the user makes changes if the converted text has any errors(since OCR is not 100 % accurate). At this point an email has to be sent to the operator. The operator logs in and checks whether the customer has uploaded the the right documents or not. If there are any errors, he edits them and hits the save button. At this stage an email is sent to the accountant and he logs in to verify the data for the second time. If he confirms, an email is sent to the customer saying his documents have been verified. As of now, my app is taking an image and converting it into editable text and displaying it … -
Create Sub Admin in Django with Special Permission based on the Data
I am using Django 2.1 I want to create a few users with some special privileges, I call these users as "Manager". What a Manager can do is: Can able to login Admin site (Can do this by making this user as staff) Can do CRUD operation ONLY for his team. In a database I've created a table called "team", where every user is associated with the certain team. Though it is not necessary to have a manager in each team. But if there is a manager he can do above-mentioned operations. I am a bit confused about how to achieve that, as on Admin Panel I can create permissions and groups based on pages/models but not type of data (team-based). I assume that I need to create different User types, but there are so many ways out there to handle different situations I am unable to relate if any one of them is applicable to my use case. Research: By creating a seperate tables for each user: Multiple User Types In Django OR django best approach for creating multiple type users Could be done this way, where we create teams in the database, and allow manager to view the … -
Save object name into ForeignKey field on child object - Django
I have these models: class MyModel1(models.Model): field1 = models.CharField(max_length=128, blank=True, null=True) fieldrelated1 = models.OneToOneField('MyModel2', max_length=128, blank=True, null=True, related_name='mymodel2') fieldrelated2 = models.OneToOneField('MyModel3', max_length=128, blank=True, null=True, related_name='mymodel3') fieldrelated3 = models.OneToOneField('MyModel4', max_length=128, blank=True, null=True, related_name='mymodel4') class MyModel2(models.Model): field2 = models.CharField(max_length=128, blank=True, null=True) myfk = models.ForeignKey(MyModel1, max_length=128, blank=True, null=True) class MyModel3(models.Model): field3 = models.CharField(max_length=128, blank=True, null=True) test = models.CharField(max_length=128, blank=True, null=True) class MyModel4(models.Model): field4 = models.CharField(max_length=128, blank=True, null=True) test = models.CharField(max_length=128, blank=True, null=True) Then, this method: def create_child_objects(instance, created, rad, **kwargs): if not created or rad: return field1 = instance.field1 if not instance.fieldrelated1_id: fieldrelated1, _ = MyModel2.objects.get_or_create(field1=field2) instance.fieldrelated1 = fieldrelated1 if not instance.fieldrelated2_id: fieldrelated2, _ = MyModel3.objects.get_or_create(field1=field3) instance.fieldrelated2 = fieldrelated2 if not instance.fieldrelated3_id: fieldrelated3, _ = MyModel4.objects.get_or_create(field1=field4) instance.fieldrelated3 = fieldrelated3 instance.save() models.signals.post_save.connect(create_child_records, sender=MyModel1, dispatch_uid='create_child_objects') So far, this method works to save the parent and save particular fields on child creation. My problem comes when I want to, for example, instead of saving a parent's CharField into a child CharField, I want to save the actual parent instance into a child's ForeignKey field, like this: def create_child_objects(instance, created, rad, **kwargs): if not created or rad: return field1 = instance.__str__ if not instance.fieldrelated1_id: fieldrelated1, _ = MyModel2.objects.get_or_create(field1=myfk) instance.fieldrelated1 = fieldrelated1 if not instance.fieldrelated2_id: fieldrelated2, _ = … -
How to resolve pyinstaller executable import error "cannot import name _align"?
I have created a exec using pyinstaller but when i execute it i get the error: Django Version: 1.8 Exception Type: ImportError Exception Value: cannot import name _align Below is my Spec file: # -*- mode: python -*- block_cipher = None a = Analysis(['manage.py'], pathex=['.envLibsite-packagesscipyextra-dll', '/root/binaries/q_c'], binaries=[], datas=[], hiddenimports=['django.contrib.admin.apps', 'cymem.cymem', 'thinc.linalg', 'murmurhash.mrmr', 'cytoolz.utils', 'cytoolz._signatures', 'spacy.strings', 'spacy.morphology', 'spacy.lexeme', 'spacy.tokens', 'spacy.gold', 'spacy.tokens.underscore', 'spacy.parts_of_speech', 'dill', 'spacy.tokens.printers', 'spacy.tokens._retokenize', 'spacy.syntax', 'spacy.syntax.stateclass', 'spacy.syntax.transition_system', 'spacy.syntax.nonproj', 'spacy.syntax.nn_parser', 'spacy.syntax.arc_eager', 'thinc.extra.search', 'spacy.syntax._beam_utils', 'spacy.syntax.ner', 'thinc.neural._classes.difference', 'scipy._lib.messagestream', 'sklearn.neighbors.typedefs', 'spacy.lang.en', 'django.contrib.auth.apps', 'sklearn.feature_extraction', 'sklearn.svm', 'srsly.msgpack.util', 'preshed.maps', 'thinc.neural._aligned_alloc', 'blis', 'blis.py', 'django.contrib.contenttypes.apps', 'django.contrib.messages.apps'], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='q_c', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True ) Can someone help me resolve this issue? -
How to host jupyter Notebook as subdirectory along with other website
I have a linux server, where I have hosted Jupyter Notebook. I can host only 1 website (that too on https). But I have some other Flask or Django based web applications too. Can I host Jupyter notebook as a subdomain on some webserver like Apache. So that I am free to host other websites of django or flask over other subdomains of Apache etc. Based on my problem, if some alternate solution can be suggested by someone that will also do (i.e., hosting multiple sites including jupyter notebook over just one DNS) I have explored options to run multiple notebook servers on same port. People and documentation said it is not possible. This log shows the port 8888. I have restriction of only one port 443. [I 15:09:00.576 NotebookApp] The Jupyter Notebook is running at: [I 15:09:00.577 NotebookApp] http://localhost:8888/?token= Final result should look like: https://mysite/notebook --> jupyter notebook https://mysite/myweb1 --> Some other html/jquery page running on same server (Can be django or flask app too) -
How to use Django Orm Subqueries in this sql
I'm new to Django ORM and I found it difficult to use Django Subqueries in this sql statement since I didn't found a nested select from example in django orm : these are my models: class A: published_at = models.DateTimeField(_('Published at')) .... Class B: set_id=models.IntegerField(_('Set ID'), blank=True, null=True, db_index=True) prices= models.FloatField(_('Price'), blank=True, null=True, db_index=True) and this is ~SQL select DATE_FORMAT(`A`.`published_at`, '%Y-%m'), sum(b) from ( select `chapter`.`id` as c, set_id, avg(prices) as b from B group by id, set_id ) as ch INNER JOIN `A` ON (id = `A`.`id`) group by DATE_FORMAT(`A`.`published_at`, '%Y-%m'); is using `subqueries in this situation usuful? I'm using django 1.11 please help -
Select data with in treeview structure and post to empty django model. (django vue + rest)
I have an django backend using a rest api. I am planning to build a filter for my vue frontend using this package. https://github.com/riophae/vue-treeselect I need to alter my models so I can filter the data in a hierarchal manner like so. .Sport | ...Competition | ....open_date | .....Event-name | ......Market-type What do I need to do in order to alter on my models.py and and how do I call get data to flow into the tree view on update button click in the filter.vue file? Also how to I post to the empty model on add button click? models.py from django.db import models class Event(models.Model): sport = models.CharField(max_length=50, null=True) event_id = models.BigIntegerField(primary_key=True) event_name = models.CharField(max_length=200, null=True) open_date = models.CharField(null=True, max_length=50) market_type = models.CharField(null=True,max_length=50) competition = models.CharField(null=True, max_length=50) Empty model to post filtered results to. class EventMonitor(models.Model): sport = models.CharField(max_length=50, null=True) event_id = models.BigIntegerField(primary_key=True) event_name = models.CharField(max_length=200, null=True) open_date = models.CharField(null=True, max_length=50) market_type = models.CharField(null=True,max_length=50) competition = models.CharField(null=True, max_length=50) serializers.py from rest_framework import serializers from .models import Event, EventMonitor class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = '__all__' class EventMonitorSerializer(serializers.ModelSerializer): class Meta: model = EventMonitor fields = '__all__' views.py from rest_framework.viewsets import GenericViewSet, ModelViewSet from api.serializers import EventSerializer, EventMonitorSerializer … -
Is there a way to make a 5 star rating system using django restframework with the models I have created?
I am trying to make an API using django RESTframework for a 5-star rating system. The API should render the list of all products in the home URL, and on each product, the average rating must be displayed. On clicking that, all the reviews for that particular product must be enlisted. I have made my models, and views and the serializers.py file. The directory level is shown: project_rating ├── reviews │ ./apps.py │ ./tests.py │ ./views.py │ ./admin.py │ ./models.py │ ./migrations ├── manage.py ├── api │ ./apps.py │ ./tests.py │ ./urls.py │ ./views.py │ ./admin.py │ ./models.py │ ./migrations │ ./serializers.py My reviews/models.py looks like this: class product(models.Model): title = models.CharField(max_length = 100) description = models.TextField() timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) review = models.ForeignKey('feedback', on_delete=models.CASCADE, null=True, default = "NA") def __str__(self): return self.title class feedback(models.Model): SCORE_CHOICES = zip(range(6), range(6) ) user = models.CharField(max_length=50, null= True, default='anonymous user') item = models.ForeignKey(product, on_delete=models.SET_NULL, null= True) rating = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) def __str__(self): return 'Rating(Item ='+ str(self.item)+', Stars ='+ str(self.rating)+')' The api/serializers.py looks likes this: class RatingSerializer(serializers.ModelSerializer): class Meta: model = models.feedback fields=( 'id', 'user', 'rating', ) class ProductSerializer(serializers.ModelSerializer): class Meta: model = models.product fields=( 'id', 'title', 'description', 'review', ) My api/views.py is: class … -
Django doesn't save OneToOne field on self
I have a model with a OneToOne field to itself: class Préinscription(models.Model): plus_un = models.OneToOneField('self', on_delete=models.SET_NULL, null=True, default=None, related_name='+') When I try to set this field on an instance, it doesn't work. In the following code, pp and pp2 are two instances of Préinscription. if d['plus_un']: pp2.nom = d['nom2'] pp2.prénom = d['prénom2'] pp2.mél = d['mél2'] pp.plus_un = pp2 pp2.save() print(pp2) # First print p.nb_billets = 2 else: pp.plus_un = None if pp2.id: pp2.delete() p.nb_billets = 1 p.save() print(pp2) # Second print print(pp.plus_un) # Third print pp.save() print(pp.plus_un) # Final print This code gives no errors. However, here is the sequence returned by the prints: Préinscription object (325) Préinscription object (325) Préinscription object (325) None This means that even though the related object is created and all, it isn't saved. As you can see, I suspected it might be because of a conflict between the .plus_un leading to the parent or the child, and so I set related_name='+' to avoid that. It does not change anything though, exactly the same results in either case, after migrating. Note that it does however work when I do it through the CLI (./manage.py shell), with the exact same procedure. -
Problem passing value to modal popup using django
I'm trying to do a simple confirm popup to delete a row on a data table. I have a list of "boxes" and on each row a delete button. When I click the delete button a modal popup appears and if the user clicks "yes" than the record should be deleted. The problem is that I'm not being able to "pass" the box id to the modal popup and than to my method on views.py. If for example I have 3 boxes on my list (Id 1, 2 and 3) the method on views.py always receive the first Id (1) This is the code: <tbody> {% for box in boxes %} <tr> <td>{{ box.id }}</td> <td>{{ box.code }}</td> <td>{{ box.description }}</td> <td><button type="button" value="{{ box.id }}" class="btn waves-effect waves-light btn-secondary " data-toggle="modal" data-target=".bs-example-modal-lg"><i class="fas fa-trash-alt"></i></button></td> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" style="display: none;"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myLargeModalLabel">Confirmation</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> </div> <div class="modal-body"> <p>Do you really want to delete this box?</p> </div> <div class="modal-footer"> <button type="submit" name="box_id" value="{{ box.id }}" class="btn btn-primary waves-effect text-left" >Yes</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> </tr> {% endfor %} </tbody> … -
How to attach a file to pdf from Amazon S3
I have the simple code for pdf rendering in my application and I try to add pdf attachments. So I read the docs and find solution. attachments (list) – A list of additional file attachments for the generated PDF document or None. The list’s elements are Attachment objects, filenames, URLs or file-like objects. So I add attachments to write_pdf method: def render_to_pdf(self, request): context_dict = { 'application': self, } context_dict['pagesize'] = 'A4' context_dict['documents'] = dict() urls = [] documents = self.user.documents.all() for document in documents: context_dict['documents'][str(document.id)] = dict() context_dict['documents'][str(document.id)]['signed_name'] = document.signed_file_name context_dict['documents'][str(document.id)]['name'] = document.file_name attachment = Attachment(url=BotoGateway().generate_cloudfront_url(document.signed_file_name)) urls.append(attachment) html_template = get_template('application_form_pdf.html') rendered_html = html_template.render(context_dict).encode(encoding="UTF-8") pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri()).write_pdf(attachments=urls) http_response = HttpResponse(pdf_file, content_type='application/pdf') http_response['Content-Disposition'] = 'filename="report.pdf"' return http_response I try 2 variant: Add urls to attachments or add Attachment objects with urls. But nothing worked. I get correct filename but when I try to open my attachment I get 0 bytes file. I debug my code and url is correct.