Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django update order field on save
Advancing on this question: Django model list order field update I am trying to update all order fields when i update 1 record from a drag and drop list result. Current implementation using linked question: class Section(models.Model): name = models.CharField() order = models.IntegerField(default=0) def save(self, *args, **kwargs): existing_sections = ( Section.objects.filter( order__gte=self.order ) .exclude(id=self.id) .order_by("order") ) existing_sections.update(order=F("order") + 1) super(Section, self).save(*args, **kwargs) Lets say i have 5 fields, with order fields 1 to 5 incrementally. This code works fine if i add a new Section at the start or end of sequence. It will make first 1 and add 1 to all existing. But if i want to move from index 3 to index 5, then i will end up with the following as final result. Note the order = 3 is missing and added 6 to the end. order = 1 order = 2 order = 4 order = 5 order = 6 -
django framework: get value from django.db.models.fields.IntegerField
How can I get value from class django.db.models.fields.IntegerField? I want get 1 from admin field. This is python code: model class and function view from django.db import models from django.db import connection import pymysql # Create your models here. class Users(models.Model): def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.firstname=models.CharField(max_length=100) self.lastname=models.CharField(max_length=100) self.username=models.CharField(max_length=50) self.password=models.CharField(max_length=255) self.admin=models.IntegerField() self.createdAt=models.DateTimeField(db_column="created_at") def getAdmin(self): return self.admin class Meta: db_table = 'users' A view function when I run user = Users.objects.get(id=userId) def home(request): #controllo se sei loggato if request.session.has_key('loggedin'): if request.session['loggedin'] != True: return redirect("login") else: return redirect("login") #l'utente è loggato recupero le informazioni userId = int(request.session['id']) user = Users.objects.get(id=userId) print(type(user)) print(type(user.getAdmin())) tmplVar = {} tmplVar["admin"] = user.admin return render(request, 'pygiustizia/home.html',{'tmplVar': tmplVar}) -
ArgumentError with Django rtree module on Apache
I have a VPS running Django on Apache. I am using Django as a backend and I am calling it from JavaScript in the frontend. In the views.py file I handle the upload of a .zip file and I elaborate it using GeoPandas and Shapely. Since GeoPandas module needs Rtree, I installed both Rtree module and his dipendency libspatialindex. The problem is that when JavaScript upload the file using FormData, the server sometimes returns the correct output (and status code 200) and sometimes returns error 500 with this message: ArgumentError argument 5: <class 'TypeError'>: expected LP_LP_c_long instance instead of pointer to LP_c_long ... Exception Location: /opt/bitnami/python/lib/python3.8/site-packages/rtree/index.py, line 688, in intersection Python Executable: /opt/bitnami/python/bin/python3 Python Version: 3.8.12 Python Path: ['/opt/bitnami/projects/GeoidDjangoAPI', '/opt/bitnami/python/lib/python38.zip', '/opt/bitnami/python/lib/python3.8', '/opt/bitnami/python/lib/python3.8/lib-dynload', '/opt/bitnami/python/lib/python3.8/site-packages', '/opt/bitnami/python/lib/python3.8/site-packages/setuptools-46.4.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/pip-21.3.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/six-1.16.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/platformdirs-2.4.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/filelock-3.4.2-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/distlib-0.3.4-py3.8.egg'] How can I solve? I tried to reinstall the required packages both using venv and without. -
Django : can't interrupt update function with redirect. Is it possible?
I use a function for updating a Model. def update_mapping(request, pk): flow = Flow.objects.get(pk=pk) mappings = MappingField.objects.filter(fl_id=pk) headers_samples = GetCsvHeadersAndSamples(request, pk) [...] In this function, I call another one (GetCsvHeadersAndSamples) for getting datas from a CSV. Later, I use those datas with JS in the template. def GetCsvHeadersAndSamples(request, flow_id): get_file_and_attribs = get_csv(request, flow_id) file = get_file_and_attribs[0] separator = get_file_and_attribs[1] encoding = get_file_and_attribs[2] with open(file, encoding=encoding) as f: reader = csv.reader(f, delimiter=separator) headers = next(reader) samples = next(itertools.islice(csv.reader(f), 1, None)) headersAndSamples = {'headers': headers, 'samples': samples} return headersAndSamples For accessing CSV datas, I use another function for checking if the CSV still exists, in which case, I retrieve datas in it. def get_csv(request, flow_id): flow = Flow.objects.get(pk=flow_id) file = flow.fl_file_name separator = flow.fl_separator media_folder = settings.MEDIA_ROOT file = os.path.join(media_folder, str(file)) if os.path.isfile(file): file_2_test = urllib.request.urlopen('file://' + file).read() encoding = (chardet.detect(file_2_test))['encoding'] return (file, separator, encoding) else: # print('No file') messages.error(request, "File not found or corrupted.") return HttpResponseRedirect(reverse('mappings-list', args=(flow_id,))) I hoped that the return would "break" my original function and would redirect to the 'mappings-list' page with the message.error. But it continues and returns to GetCsvHeadersAndSamples function that generates an error because CSV datas were not found. Nota: the commented print however shows … -
Displaying Mutiline string in django through ajax
When I use the following code to return a multiline string data to my html page, it turns out to become a single line string. Is there a way to display the multiline string? <div class="multiline" id="result"> </div> $(document).on('submit','#post-form', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/create', data:{ other:$('#other').val(), code:$('#code').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(data){ $('#result').html(data); } }); }); I try to use the following code: $.each(data.split(/[\n\r]+/), function(index, line) { $('<li>').text(line).appendTo('#result'); }); but the displayed string is increasing each time when i submit another data and i want the new string to overwrite old string -
Can I prevent Django from deleting an object depending on an attribute in a referencing type?
Imagine PetOwner and a Pet models: class PetOwner(models.Model): name = models.CharField() class Pet(models.Model): owner = models.ForeignKey('PetOwner', on_delete=models.CASCADE) alive = models.BooleanField(default=True) I would like it to be possible to delete PetOwners, but only if all theiry associated Pets are not alive anymore. If that is the case, the PetOwner can be deleted and all his associated pets are also deleted (cascade semantics). Is that possible? -
whats the best way to encode/hash url ids in django 1.11
I'm trying to migrate our project that uses incremental ids for our APIs to use encoded or hashed ids. The problem is we're using Django 1.11 that doesn't support url converters which will be very helpful for implementing this feature. But.. Upgrading Django is not an option for us (too risky!) the only viable option I'm considering is to use Django middleware and write our own middleware that will do the transformation for us (but this seems a very ugly solution because modifying original request info is just meh) What is the best implementation and solution for this? thanks! -
Double aggregation of queryset in django
I have data that looks like this: [{ 'ticker': 'ACVA-US', 'source': 'INTERNAL', 'event_id': 300, 'value_usd': 3000.0, 'shares': 300.0, 'days_to_trade': 3.0, 'num_trades': 1 }, { 'ticker': 'ACVA-US', 'source': 'INTERNAL', 'event_id': 200, 'value_usd': 2000.0, 'shares': 200.0, 'days_to_trade': 2.0, 'num_trades': 1 }, { 'ticker': 'ACVA-US', 'source': 'EXTERNAL', 'event_id': 200, 'value_usd': 1000.0, 'shares': 100.0, 'days_to_trade': 1.0, 'num_trades': 1 }] I need to perform what is essentially a double-aggregation. First, I need to take the average of items with the same ticker+event, which would look like: [{ 'ticker': 'ACVA-US', 'event_id': 300, 'value_usd': 3000.0, 'shares': 300.0, 'days_to_trade': 3.0, 'num_trades': 1 }, { 'ticker': 'ACVA-US', 'event_id': 200, 'value_usd': 1500.0, 'shares': 150.0, 'days_to_trade': 1.5, 'num_trades': 2 }] Next, I need to sum up items across tickers, which would look like: [{ 'ticker': 'ACVA-US', 'value_usd': 4500.0, 'shares': 450.0, 'days_to_trade': 4.5, 'num_trades': 3 }] I can't figure out how to do this using Django. I've tried: query1 = queryset.values('ticker', 'event_id').annotate(value_usd=Avg('value_usd'), shares=Avg('shares'), days_to_trade=Avg('days_to_trade'), num_trades=Count('ticker')) query2 = query1.values('ticker').annotate(value_usd=Sum('value_usd'), shares=Sum('shares'), days_to_trade=Sum('days_to_trade'), num_trades=Count('security')) but I receive an error django.core.exceptions.FieldError: Cannot compute Sum('value_usd'): 'value_usd' is an aggregate. I was hoping to do this without having to create a db view that performs the first aggregation, but so far I can't figure it out. I need … -
Check if django queryset have the same value in specific field
Is there any easier way to check if the query set have same value in specific field class Subject(models.Model): name = models.CharField(max_length=15, blank=False) summary = models.CharField(max_length=200, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) is_finish = models.BooleanField(default=False) y = Subject.objects.all() how to know if y objects, each of them have is_finish == True without using for loop? I just want to know that the queryset is giving me the same value for is_finish field. -
HTML page not refreshing after rendering in views in Django
I am currently working on a django project. Below is a function which handle "charts/" request def charts(request): if request.method == 'POST': form = SecuritiesForm(request.POST) if form.is_valid(): data = generateCharts(list(form.cleaned_data.get("securities_field"))) return render(request, 'charts.html', { "tickerList": data["tickerList"], "current": data[data["tickerList"][1]]}) if request.method == 'GET': ticker = request.GET.get('ticker', '') print(ticker) data = getData() print(data.keys()) return render(request, 'charts.html', { "tickerList": data["tickerList"], "current": data[ticker]}) return render(request, 'home.html', {'form': SecuritiesForm()}) as you can see when it is a GET request I update the dictionary and try to render the same HTML file. However my HTML page does not refresh and continues to show the same content, Can anyone help with this? It does not seem to refresh with the new data. On HTML side I do this {% if current %} {{ current |safe }} {% else %} <p>NO Graph</p> {% endif %} -
how can i use filter to check if specific user's social media link is correct?
def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() room_messages = user.message_set.all() topics = Topic.objects.all() link_fb = User.objects.filter(Q(link_fb__icontains='facebook')) link_ig = User.objects.filter(Q(link_ig__icontains='instagram')) link_lin = User.objects.filter(Q(link_lin__icontains='linkedin')) context = {'user': user, 'rooms': rooms, 'room_messages': room_messages, 'topics': topics, 'link_fb': link_fb, 'link_ig': link_ig, 'link_lin': link_lin} return render(request, 'base/profile.html', context) I've got something like this. I want to check if url is correct. Problem is i can not get specific user and then use filter. Is there any other way to do that? -
Django AllAuth with Twitter Error: "No access to private resources at api.twitter.com"
I'm trying to setup the Django AllAuth Twitter login. When the user authenticates with Twitter and is redirected to my website, Django AllAuth raises the Error "No access to private resources at api.twitter.com" and I'm pretty lost here. I have the following settings in my settings.py: SOCIALACCOUNT_PROVIDERS = { "twitter": { # From https://developer.twitter.com "APP": { "client_id": os.environ["TWITTER_API_KEY"], "secret": os.environ["TWITTER_API_SECRET"], } }, } My app has the following privilege rights in the developer portal: OAuth1 Endpoints OAuth2 Endpoints User Email Read Tweets and Profiles Any ideas why this could be happening? Thanks in advance! -
Celery beat service showing inactive (dead) in python3
here i am using celery version 5.1.2 on Ubuntu 16.04 with python version 3.7 and Django version 3.0 here i am unable to schedule tasks and i couldn't understand why its showing inactive(dead) here are the commands what i am using and the result what i am getting sudo systemctl daemon-reload sudo systemctl reset-failed celeryd.service sudo systemctl restart celeryd sudo systemctl status celeryd ● celeryd.service - Celery Beat Service Loaded: loaded (/etc/systemd/system/celeryd.service; enabled; vendor preset: enabled) Active: inactive (dead) since Fri 2022-04-01 13:08:11 BST; 2min 20s ago Process: 4520 ExecStart=/home/ravi/.virtualenvs/lightdegree/bin/celery multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_F Main PID: 4520 (code=exited, status=0/SUCCESS) Apr 01 13:08:10 ip-xxx systemd[1]: Started Celery Beat Service. Apr 01 13:08:11 ip-xxx celery[4520]: celery multi v5.1.2 (sun-harmonics) Apr 01 13:08:11 ip-xxx celery[4520]: > Starting nodes... Apr 01 13:08:11 ip-xxx celery[4520]: > worker1@ip-xxx: OK here i am sharing my celery log file result also Apr 1 13:20:08 ip-xxx systemd[1]: Reloading. Apr 1 13:20:08 ip-xxx systemd[1]: Started ACPI event daemon. Apr 1 13:20:17 ip-xxx systemd[1]: Stopped Celery Beat Service. Apr 1 13:20:17 ip-xxx systemd[1]: Started Celery Beat Service. Apr 1 13:20:18 ip-xxx celery[4868]: #033[1;36mcelery multi v5.1.2 (sun-harmonics)#033[0m Apr 1 13:20:18 ip-xxx celery[4868]: > Starting nodes... Apr 1 13:20:18 ip-xxx celery[4868]: … -
What is the proper way to upload files using FileField in Models and Serializers in Django Rest Framework?
I am making a simple DRF Login App which will let the user to upload a CSV file and its description upon registration. It is working fine but when I upload the file, it gives the error The submitted data was not a file. Check the encoding type on the form.. I have searched around stackoverflow but there are questions related to only ImageField (that is image) not FileField. SO I was unable to solve the issue. My Models.py is: class Detail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) file = models.FileField(verbose_name="CSV File", upload_to='csv_files') file_desc = models.TextField("CSV File Description") def __str__(self): return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name)) My Serializers.py is: class MainRegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') class RegisterSerializer(serializers.ModelSerializer): register = MainRegisterSerializer() class Meta: model = Detail fields = ['register', 'file', 'file_desc'] optional_fields = ['file', 'file_desc'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['register']['username'], validated_data['register']['email'], validated_data['register']['password']) user.first_name = validated_data['register']['first_name'] user.last_name = validated_data['register']['last_name'] user.save() detail = Detail(user=user, file=validated_data['file'], file_desc=validated_data['file_desc']) detail.save() return user My Views.py is: class RegisterAPI(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'accounts/register.html' def get(self, request): serializer = RegisterSerializer() return Response({'serializer': serializer}) def post(self, request): serializer = RegisterSerializer(data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer}) … -
Python - FastAPI vs Django [closed]
Based on benchmarks, FastAPI has better performance than Django. FastAPI is also an ASGI app, as opposed to Django being WSGI. Django projects are also much heavier and you have to do a lot using python3 manage.py. I personally find that FastAPI is nicer to use in terms of API and documentation. Is there any benefit of Django that I am missing, or is it just personal preference? -
Get id of FactoryBoy factory with LazyAttribute when using DjangoModelFactory
I have the following factory and want to access the id of an instance that will be created from it: class PlatformFactory(factory.django.DjangoModelFactory): type = factory.fuzzy.FuzzyChoice(Platform.Type) name = factory.fuzzy.FuzzyText(length=30) user = factory.SubFactory(UserFactory) ext = factory.LazyAttribute(lambda self: f"{self.user.key}|{self.id}") class Meta: model = Platform exclude = ["user", ] Unfortunately it gives me the error AttributeError: The parameter 'id' is unknown. Evaluated attributes are {'type': <Type.OTHER: 2>, 'name': ... But since it is a django model there is an id present. Why is this not recognized by factory boy and how can I solve this? Thanks and regards Matt -
Python Django Class based views - accessing data
I've created a ListView # views.py from django.views.generic import ListView class ReportListView(ListView): model = ReportList context_object_name = 'reportitems' template_name = "reports.html" # urls.py path('reports/', login_required(views.ReportListView.as_view()), However, when I try to check length of reportitems I get this error `Could not parse the remainder: '(reportitems)' from 'len(reportitems)' # my html file {{ len(reportitems) }} or {{ len(object_list) }} I get the same error with object_list too. What am I doing wrong? Just to confirm. ReportList model doesn't have any data in it. Is that the reason it's failing? If yes, how could I check that if there is any data or not yet? I tried to look at Django docs and Google search. However, it seems like I should have access to object_list variable or unless when I change it's name. -
Static files don't load in django framework
Settings SITE_ID = 1 STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Template home-page.html {% load static %} piece of code <!-- JQuery --> <script type="text/javascript" src="{% static 'app1/js/jquery-3.4.1.min.js' %}"></script> <!-- Bootstrap tooltips --> <script type="text/javascript" src="{% static 'app1/js/popper.min.js' %}"></script> <!-- Bootstrap core JavaScript --> <script type="text/javascript" src="{% static 'app1/js/bootstrap.min.js' %}"></script> <!-- MDB core JavaScript --> <script type="text/javascript" src="{% static '../js/mdb.min.js' %}"></script> <!-- Initializations --> <script type="text/javascript"> // Animations initialization new WOW().init(); urls from commercemag import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls', namespace='item-list')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) idk what i should do, please help me -
How to annotate an object with the sum of multilplication of two fields from a related object to a realated object in Django
Given these three classes class User(BaseModel): name = models.CharField(..) class Order(BaseModel): user = models.ForeignKey(User,...,related_name='orders') class OrderItem(BaseModel): order = models.ForeignKey(Order,...,related_name='items' quatity = models.IntegerField(default=1) price = models.FloatField() and this is the base class (it is enough to note that it has the created_at field) class BaseModel(models.Model): createt_at = models.DateTimeField(auto_now_add=True) Now each User will have multiple Orders and each Order has multiple OrdeItems I want to annotate the User objects with the total price of the last order. Take this data for example: The User objects should be annotated with the sum of the last order that is for user john with id=1 we should return the sum of order_items (with ids= 3 & 4) since they are related to the order id=2 since it is the latest order. I hope I have made my self clear. I am new to Django and tried to go over the docs and tried many different things but I keep getting stuck at getting the last order items -
How to ignore html tags/code stored in JavaScript variables?
Hi I am currently working on a django project wherein I send multiple plotly charts as html code to the client side and try to store this html code in a dictionary I first make the chart and convert to HTML code prediction_graph = prediction_graph.to_html(full_html=False) then I send multiple such charts to client side. Here please note that charts itself is a dictionary. return render(request, 'charts.html', { "tickerList": charts["tickerList"], "charts": json.dumps(charts)}) On client side I try to store it in a javascript variable charts = {{ charts|safe }}; However the html tags/code present in this variable causes error. Is there any way to solve this? like make it ignore the html tags/code -
Can't open localhost in the browser on port given in docker-compose
I am trying to build and run django application with docker and docker-compose. docker-compose build example_app and docker-compose run example_app run without errors, but when I go to http://127.0.0.1:8000/ page doesn't open, I'm just getting "page is unavailable" error in the browser. Here is my Dockeffile, docker-compose.yml and project structure Dockerfile FROM python:3.9-buster RUN mkdir app WORKDIR /app COPY ./requirements.txt /app/requirements.txt COPY ./requirements_dev.txt /app/requirements_dev.txt RUN pip install --upgrade pip RUN pip install -r /app/requirements.txt docker-compose.yml version: '3' services: example_app: image: example_app build: context: ../ dockerfile: ./docker/Dockerfile command: bash -c "cd app_examples/drf_example && python manage.py runserver" volumes: - ..:/app ports: - 8000:8000 project structure: ──app ──app_examples/drf_example/ ────manage.py ────api ────drf_example ──requirements.txt ──requirements_dev.txt ──docker/ ────docker-compose.yml ────Dockerfile -
Django- iterate a through a for loop
I have the following for loop in my django template displaying the items in my 'question' list.I want to print the value according to the index position of the list.However when I am trying to print it , nothing is showing in my browser. I have use a range function in my context and initialize it with a value of 2 in a key name 'n'. This is my context context = {'range' : range(2), 'question': input_question, 'most_sim_Q': result[6], 'question_scores': question_scores} return render(request, 'predict/result.html', context) this is the template {% extends 'predict/base.html'%} {% block content %} {% for text in range %} <!--parsing the input question--> <h2>Input Question: </h2><br> {{question.text}} <!--Parsing the most similar question--> <h2>most similar question's are: </h2><br> {{most_sim_Q.n.most_sim_Q}} <!--parsing the top 10 most smilialr question--> <h2> Top 10 most similar questions found are : </h2><br> {%for ques_key, values in question_scores.items%} {% for que, score in question_score.i.items %} <h3> {{ que }} ==> {{score}} </h3> {% endfor %} {% endfor %} <h3>--------------------------------------------------</h3> {% endfor %} {% endblock content %} I am printing question.text where question is the list containing two values but {{question.text}}.This is my output Input Question: most similar question's are: Top 10 most similar questions found … -
Django infinite loading after multiple requests on apache using mod_wsgi
I recently added a second Django application to my functional set of websites, 1 Django 1 PHP on apache (3.3.0) using mod_wsgi. All the Django applications work fine, however, when I added a second Django application to my apache config file as a virtual host, it stopped responding after I refreshed the page a couple of times (give or take). I have played around with my WSGI files, deleted .htaccess files and changed virtual host configurations, alas it still does the same thing. Here is the necessary information (I hope) for anyone to take a look and help, any help is appreciated My vhost file LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/taber/AppData/Local/Programs/Python/Python310" WSGIApplicationGroup %{GLOBAL} ################################################################################################## # MAIL.NEOSTORM.US.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName mail.neostorm.us.to SSLEngine on SSLCertificateFile "conf/ssl.crt/neostorm.us.to-chain.pem" SSLCertificateKeyFile "conf/ssl.key/neostorm.us.to-key.pem" DocumentRoot "C:/xampp/htdocs/webmail" <Directory "C:/xampp/htdocs/webmail"> Require all granted </Directory> </VirtualHost> ################################################################################################## # ASTINARTS.UK.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName astinarts.uk.to SSLEngine on SSLCertificateFile "conf/astinarts/astinarts.uk.to-chain.pem" SSLCertificateKeyFile "conf/astinarts/astinarts.uk.to-key.pem" Alias /static "C:/xampp/htdocs/astinarts/static" <Directory "C:/xampp/htdocs/astinarts/static"> Require all granted </Directory> Alias /media "C:/xampp/htdocs/astinarts/media" <Directory "C:/xampp/htdocs/astinarts/media"> Require all granted </Directory> Alias /.well-known "C:/xampp/htdocs/astinarts/.well-known" <Directory "C:\xampp\htdocs\astinarts\.well-known"> Require all granted </Directory> Alias /sitemap.xml "C:/xampp/htdocs/astinarts/sitemap.xml" Alias /robots.txt "C:/xampp/htdocs/astinarts/robots.txt" <Directory "C:/xampp/htdocs/astinarts/astinarts"> Require all granted </Directory> WSGIScriptAlias / "C:/xampp/htdocs/astinarts/astinarts/wsgi.py" application-group=astinarts <Directory "C:/xampp/htdocs/astinarts/astinarts"> … -
Selection box answer and value
I have a Questionnaire model that has a selection dropdown boxes, the available choices to select from a formed from another model Choices The choices model has a choice_text field and a choice_value. When a user selects a choice_text it is posted to the database, but i also need to choice_value to be added to but this value is not visible. So basically the question would be "what is the marketing like" and choice would be good, bad or average. But the value would be 1 2 3 Im not sure of the best way to post both the choice and value. def get_questionnaire(request, project_id, questionnaire_id): # Get or Create the Response object for the parameters next = request.POST.get('next', '/') response, created = ProjectQuestionnaireResponse.objects.get_or_create( project_name_id=project_id, questionnaire_id=questionnaire_id ) AnswerFormSet = modelformset_factory(ProjectQuestionnaireAnswer, form=AnswerForm, fields=('answer','notes',), extra=0) answer_queryset = ProjectQuestionnaireAnswer.objects.filter(response=response ).order_by('question__sequence' ).select_related('question') if request.method == 'POST': formset = AnswerFormSet(request.POST, form_kwargs={'question_id': questionnaire_id}) instances = formset.save() return HttpResponseRedirect(next) else: pass # Get the list of questions for which no Answer exists new_answers = ProjectQuestionnaireQuestion.objects.filter( questionnaire__projectquestionnaireresponse=response ).exclude( projectquestionnaireanswer__response=response ) # This is safe to execute every time. If all answers exist, nothing happens for new_answer in new_answers: ProjectQuestionnaireAnswer(question=new_answer, response=response).save() ### getting all questions related to a given … -
How check empty variable in template? Exception Value: Could not parse the remainder
{% extends 'pygiustizia/base.html' %} {% block body %} <div class="wrapper"> <h2>Login</h2> <p>Prego, inserisci le tue credenziali di login.</p> <div class={% if len(tmplVar.loginErr) > 0 %} "alert alert-danger" {% endifequal %}> {% if tmplVar.loginErr is not None %} {{tmplVar.loginErr}} {% endif %}</div> <form action="{% url 'login' %}" method="post"> <div class="form-group"> <label>Username</label> <input type="text" name="username" class="form-control {% if tmplVar.usernameErr is not None %} is-invalid {% endif %}" value="{{tmplVar.username}}"> <span class="invalid-feedback">{% if tmplVar.usernameErr is not None %} {{tmplVar.usernameErr}} {% endif %}</span> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" class="form-control {% if tmplVar.passwordErr is not None %} is-invalid {% endif %}" value="{{tmplVar.password}}"> <span class="invalid-feedback">{% if tmplVar.passwordErr is not None %} {{tmplVar.passwordErr}} {% endif %}</span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Login"> </div> </form> </div> {% endblock %} Exception Value: Could not parse the remainder: '(tmplVar.loginErr)' from 'len(tmplVar.loginErr)' What I miss? How can I check if variable is empty or lenght 0?