Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dropdowns
Hello guys I created a model workorder and I added some dropdowns. I have integer fields and i would like them to remain as integer fields but just to add some definitions for each number. The issue is that i don't know how to display them on my create/workorder template also i cannot add a new model in the admin page eventhough the dropdowns are visualized. This is my code: models.py from __future__ import unicode_literals from django.db import models from django.contrib.gis.db import models from multiselectfield import MultiSelectField TYPE_CHOICES = ( ('1','(-)'), ('2', 'Ankesë: Bllokim i Kanalzimit'), ('3', 'Ankesë: Ndërprerje e furnizimit të ujit/rënia e presionit'), ('4', 'Ankesë: Cilësia e Ujit'), ('5', 'Ankesë: Të tjera'), ('6', 'Kërkesë : Aplikacion për lidhje të re - pëlqim'), ('7', 'Kërkesë : Ndërrim i ujëmatësit'), ('8', 'Kërkesë : Rrjedhje e ujit'), ('9', 'Kërkesë: Të tjera'), ('10', 'Kërkesë : Interne - Intervenim ne ujesjelles'), ('11', 'Kërkesë : Interne - Intervenim ne kanalizim'), ('12', 'Kërkesë : Interne - Nderrim i ujematesit'), ('13', 'Kërkesë : Interne - Bllombim'), ('14', 'Kërkesë : Interne - Kyçje/Shkyçje'), ('15', 'Orari i caktuar-ujë'), ('16', 'Orari i caktuar-kanalizim'), ('16', 'Orari i caktuar-kanalizim'), ('17', 'Orari per ndërrimin e ujëmatësave') ) class Workorder(models.Model): WO_ID = models.BigIntegerField(primary_key=True) … -
How to return an HttpResponse(writing and downloading a csv) and redirect to an Html page
I am new to Django and i am trying to return, from a view, an HttpResponse that instantly downloads a csv on the browser (I've done that already!) and redirects the user to a new Html page. I've already seen the HttpResponseRedirect however i've not been able to do both (download and redirect) This is part of my views.py file Views.py response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment;filename="filename.csv"' writer = csv.writer(response) k=0 for t in text: if k==0: writer.writerow(['#','text']) k+=1 writer.writerow([k, +str(t[0])]) return response Is there a way that allows me to do both? Thank you in advance! -
Django admin forms add fields dynamic
I want to add fields dynamic. I am using Django 1.11.2 I did: class AdminOfferForm(forms.ModelForm): product1 = forms.ModelChoiceField(queryset=ManagerProduct.get_products_qs(), required=True) quantity1 = forms.IntegerField(min_value=0, required=True) price1 = forms.DecimalField(max_digits=10, decimal_places=c.DECIMALS, min_value=0.01, required=True) class Meta: model = Offer exclude = ['date_added', 'date_updated'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for x in range(100): x += 2 self.fields['product' + str(x)] = forms.ModelChoiceField(queryset=ManagerProduct.get_products_qs(), required=False) self.fields['quantity' + str(x)] = forms.IntegerField(min_value=0, required=True) self.fields['price' + str(x)] = forms.DecimalField(max_digits=10, decimal_places=c.DECIMALS, min_value=0.01, required=True) self.Meta.fields.append('product' + str(x)) self.Meta.fields.append('quantity' + str(x)) self.Meta.fields.append('price' + str(x)) Everything seems to be ok inside the instance,I see the fields, but in html they doesn't appear. I didn't declared any fieldsets and if I declare it I receive and error that the fields create in init are not recognize -
How to customize django signup form's helper texts with widget_tweaks?
I am trying to create a signup page and using django's default signup form while trying it. I have a problem with Password field's helper text because I cannot fix it. Here is my signup.html's body; <body class="text-center"> <form class="form-signin" method="POST"> {% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Sign up</h1> {% for field in form %} <label for="{{ field.id_for_label_tag }}">{{ field.label_tag }}</label> {{ field | add_class:'form-control' }} {% for text in field %} <small style="color: grey">{{ field.help_text }}</small></br></br> {% endfor %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} {% endfor %} <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button> <p class="mt-5 mb-3 text-muted">&copy; 2017-2018</p> </form> </body> Here is the page's screen shot; As I show on the screen shot with red arrow, there is a problem with ul and li tags. They aren't affected with the style. How can I fix it? -
Django ProgressBar for creaded files
Can You help me ? How i can display progress bar in my application ? I get values from database and create list of all values combination, next i save file name to database and save xml file to disk. This operation takes a long time. I want display progress bar how many files already created. Progress bar must be kept up to date. def save_auto_xml_tests(request, pk): serial_port_speed = list(SerialPortSpeed.objects.values_list('value', flat=True)) serial_port_data_bits = list(SerialPortDataBits.objects.values_list('value', flat=True)) serial_port_parity = list(SerialPortParity.objects.values_list('value', flat=True)) serial_port_stop_bits = list(SerialPortStopBits.objects.values_list('value', flat=True)) serial_port_handshake = list(SerialPortHandshake.objects.values_list('value', flat=True)) created = list(itertools.product(serial_port_speed, serial_port_data_bits, serial_port_parity, serial_port_stop_bits, serial_port_handshake)) for item in created seeker = Seeker.objects.get(name=modelseeker) xml_file_name = time.strftime("%Y%m%d-%H%M%S") + '.xml' record = XmlSeeker(xml_file=xml_file_name) record.save() xml_body = "..." xml_seeker_test = 'XmlGenerated\\{}\\{}'.format(pk, xml_file_name) pathlib.Path('./media/XmlGenerated/{}/'.format(pk)).mkdir(parents=True, exist_ok=True) f = open(os.path.join(settings.MEDIA_ROOT, xml_seeker_test), 'w') xml_save = ET.ElementTree(ET.fromstring(xml_body)) xml_save.write(os.path.join(settings.MEDIA_ROOT, xml_seeker_test), encoding="UTF-8", xml_declaration=True) f.close() return redirect('details', pk=pk) -
Cannot link my form information with the User
I have a edit page which you can edit your personal information that you register, such as username, first_name, last_name, email. But inside the page i have some extra field such as description, city, website field that you can add into your profile too. the problem is i cant save the extra field to the user that login, but the personal information edit work fine, just the extra field cannot be save to the person. i want the user able to edit their personal profile and also add/edit the extra field if they want to. the extra field didnt include when the user register, user just register with username, firstname, lastname and email.But when they edit their personal profile, i want to add some field so they can have more information in their profile. there is a picture link at the below too.Thank you. views.py file def UserProfileEdit(request): if request.method == 'POST': form_edit = EditForm(request.POST, instance= request.user) form_extra = UserExtra(request.POST,instance=request.user) if form_edit.is_valid() and form_extra.is_valid(): edit = form_edit.save() extra = form_extra.save() extra.user = edit return redirect('/userprofile/user') else: form_edit = EditForm(instance = request.user) form_extra = UserExtra(instance = request.user) user_edit = {'form_edit':form_edit,'form_extra':form_extra} return render(request,'user_profile/user_edit.html',context=user_edit) forms.py class EditForm(UserChangeForm): class Meta(): model = User fields … -
Python : range between dates when range field has time
I want to make a range between 2 dates and my range field has the time damage_list = Damage.objects.filter(entry_date__range=(fdate, tdate)) fdate and tdate are dates ('YYYY-mm-dd') and entry_date has time. How can I range all the records of the tdate ? Thanks in advance Kostas -
Why server does not support SSL, but SSL was required?
Tried this link, but no luck: psql: server does not support SSL, but SSL was required If I run that command I still get the same error. This all started when I installed Django-environ and started switching my sensitive settings into environment variables. This is my settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'CONN_MAX_AGE': 500, 'USER': 'yaelbwade', } } # Parse database connection url strings like psql://user:pass@127.0.0.1:8458/db DATABASES = { # read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found 'default': env.db(), } This is in my pg_hba.conf: # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all md5 # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres md5 #host replication postgres 127.0.0.1/32 md5 #host replication postgres ::1/128 md5 and this is my postgresql.conf: # - Security and Authentication - #authentication_timeout = 1min # 1s-600s #ssl = on # (change requires restart) #ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers # (change requires restart) #ssl_prefer_server_ciphers = on # (change requires restart) #ssl_ecdh_curve = 'prime256v1' # (change … -
How to integrate Mixpanel analytics to a Django backend?
I need to track all notifications in my Django backend using mixpanel analytics. Does anyone have any ideas or resources of how I can integrate it to my project? PS: I am using celery to handle the notifications asynchronously. Thanks -
cannot save serialized data, django
I have a serializer of class class fooSerializer(ModelSerializer): An instance is created with above serializer and verified if it is valid foo_serial = fooSerializer(data=foo_data) if foo_serial.is_valid(): print "before saving foo_serial" foo_serial.save() print "after saving foo_serial" ... ... else: print "there are errors in serial" return foo_serial.errors The code is not returning any errors i.e. the serial is valid and code runs upto print "before saving foo_serial" This indicates that the execution is failing at foo_serial.save() which is difficult to figure out as we do not have any errors messages. How to debug the issue further ? -
Heroku - how to deploy django react app which has different structuring?
I have a django-rest-framework backend and a reactjs frontend and they are integrated using this (please take a look at this). So, my app is structured in this way: -frontend -package.json -app -settings.py -webapp -views -serializers -templates -index.html -requirements.txt -Procfile -runtime.txt Now I want to deploy this kind of project to heroku so I have googled this but all those examples don't follow this structuring. So, I am unsure on how to deploy this project (having both django and react) to heroku. -
What is the right method to add text areas to Django?
I have written python code that analyses two text sources and compares them. I'd like to implement this dynamically via two text boxes that a user could either type into or manually upload. I have already begun coding this using HTML. Would it be better to implement a widget or the models instead to make the text area boxes? -
Django Channels - chat
I want to create an app to allow users on my site to message each other in real time. Channels seem to be the logical choice however, all the resources I'm finding online is for making more of a chat room. Where can I find tutorials or recourses on making a single peer-to-peer chat? -
Django return a response in generic class based view
I have a generic class based view and I am trying to return a response based on some conditions but it is not happening. # Create your views here. class UserViewCreate(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer response = HttpResponse('') def perform_create(self, serializer): if serializer.is_valid(): if self.check_signin_details(self.request.data): serializer.save() self.response.status_code = 201 self.response["message"] = "User created successfully." return self.response else: self.response.status_code = 400 self.response["message"] = "Password or username policy failed." return self.response @staticmethod def check_signin_details(data): return len(data['username']) < 11 and len(data['userpassword']) > 10 I expect the response and status_code which I am setting. But I am getting a 201 everytime even on else case. Simply put, I am not getting the custom resposne. -
Get() a Model object from it's UUID
AIM As part of a weather-dependent alarm clock project, each alarm will contain three categories of info: 1) date/time, 2) weather conditionals, 3) location. Once the User completes the date/time and weather conditionals in the SetAlarmForm, I am trying to automatically complete the following fields: timezone, city and country based on the User's IP address. I currently using: alarm_id = self.request.POST.get('time'). Although, that raises the obvious ERROR (see below) as time is not unique. How do I do write: alarm_object, created = Alarm.objects.get(X=Y). Where: X = alarm_id field in the Alarm model Y = the alarm_id for the alarm just created by the User in the form. CODE Models.py class User(models.Model): """ Model representing each User """ username = models.CharField(max_length=10, unique=True) def __str__(self): return self.username class Alarm(models.Model): """ Model representing each Alarm """ alarm_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # in future, remove null=True. I included it for the time being to workaround an error. username = models.ForeignKey(User, on_delete=models.CASCADE, null=True) timezone = models.CharField(max_length=30) city = models.CharField(max_length=30) country = models.CharField(max_length=30) time = models.DateTimeField() temp_max = models.FloatField(blank=True, null=True) temp_min = models.FloatField(blank=True, null=True) Views.py class SetAlarmView(FormView): """ FormView for User to create the Alarm """ template_name = 'weather_alarm/set_alarm.html' form_class = SetAlarmForm success_url = reverse_lazy('weather_alarm:confirm-alarm') … -
Django Music Application
I am trying to write an application in Django that allows producers to share their music samples and download samples from others. I was curious if this is possible with Django's built in functionalities or if I would be better suited using something like rails or Node js. -
HTML copy and paste function, replace <br> tags with linebreaks
Here is my copy funciton: function myFunction(val, event) { var inp = document.createElement('input'); document.body.appendChild(inp) inp.value = val.replace("<p>", "").replace("</p>", "").replace(/<br *\/?>/g, "\r\n"); inp.select(); document.execCommand('copy', false); inp.remove(); alert('copied'); } HTML: <td>{{ resp|escape|linebreaks }}</td> <td>{{ resp.Question_id.Statement }}</td> <td><button onclick="myFunction('{{resp|escape|linebreaks}}')">Copy text</button></td> The text I am copying contains html tags in them. I've managed to get rid of them but for <\br> tags i want to replace them with newline break \n. But my function is only removing <\br> without adding a new line. e.g. So here we have:"<\br/>option1<\br/>option2 becomes: So here we have:option1option2 instead of: So here we have: option1 option2 -
Create a staff user ib django
I want to create a signup system with django . and I create a user with a class that is on forms.py and extends UserCreationForm . and I run server and fill the form and user is created but I cannot login with this user on the login page of django and it says me the user is not a staff user how to make my user staff ??? forms.py : class ModelNameForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username' , 'first_name' , 'last_name' , 'email' , 'password1' , 'password2' ) def save(self, commit=True): user = super (ModelNameForm , self ).save(commit=False) user.first_name = self.cleaned_data ['first_name'] user.last_name = self.cleaned_data ['last_name'] user.email = self.cleaned_data ['email'] if commit : user.save() return user views.py : def register (request): form = ModelNameForm (request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/thanks') else: form = ModelNameForm() args = {'form' : form } return render(request , 'signup.html' , args) -
Display foreign key of a FormSet value in django template
I got two models: class Box(models.Model): ... material = models.ForeignKey('Material', related_name='box_materials', on_delete=models.CASCADE) class Material(models.Model): ... name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name In form.py I got this: BoxesUpdateFormSet= inlineformset_factory(Entry, Box, form=BoxesForm, can_delete=True, extra=0) class BoxesForm(ModelForm): class Meta: model = Box fields = ['kg', 'material', 'price'] I want to display the Box material in the template, but {{ box.material }} displays a Select object, while I would like to display just a text instead. I've tried {{ box.material.value}}, but I only get the ID. With {{ box.material.name }} I get nothing. What can I do to display the value of an Child Model attribute ? -
Attribute Error: 'dict' object has no attribute 'endswith'
(y) xlm@d8cb8a102c73:~/workspace/y-server/y$ ./manage.py run_algorithm --settings=y.settings.local Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/base.py", line 454, in execute self.stdout.write(output) File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/base.py", line 111, in write if ending and not msg.endswith(ending): AttributeError: 'dict' object has no attribute 'endswith' I am trying to run the file algorithm.py with the command file run_algorithm.py (below) on a django framework. However I get the above attribute error, and I am unsure why. import logging from django.conf import settings from django.core.management.base import BaseCommand from ...algorithm import engagement_level_mapping logger = logging.getLogger(settings.LOGGER_NAME) class Command(BaseCommand): help = "TODO: describe" def handle(self, *args, **options): result = engagement_level_mapping() return result However, when printing the result, rather than returning, the file executes correctly. import logging from django.conf import settings from django.core.management.base import BaseCommand from ...algorithm import engagement_level_mapping logger = logging.getLogger(settings.LOGGER_NAME) class Command(BaseCommand): help = "TODO: describe" def handle(self, *args, **options): result = engagement_level_mapping() print(result) The command file prints a dictionary of engagement values for each user (not that relevant, but just that it prints a dictionary). -
Django webpage display login when it should be logout
I have used Django 1.11.14, python 2.7 and win 7 to build a website which could let registered user to login. however, when I log in, some page display login link again when it should be logout link. main page <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>xxxxx</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-2"> {% block sidebar %} <ul class="sidebar-nav"> <br> <li><a href="{% url 'index' %}"><mark>Home</mark></a></li> <br> <li><a href="{% url 'FWs' %}"><mark>FW request</mark></a></li> <br> </ul> <ul class="sidebar-nav"> {% if user.is_authenticated %} <li>User: {{ user.get_username }}</li> <li><a href="{% url 'my-applied' %}"><mark>My applied</mark></a></li> <br> <li><a href="{% url 'logout'%}?next={{request.path}}"><mark>Logout</mark></a></li> {% else %} <li><a href="{% url 'login'%}?next={{request.path}}"><mark>Login</mark></a></li> {% endif %} </ul> {% if user.is_staff %} <hr /> <ul class="sidebar-nav"> <li>Staff</li> {% if perms.catalog.can_mark_returned %} <li><a href="{% url 'all-applied' %}"><mark>All applied</mark></a></li> {% endif %} </ul> {% endif %} {% endblock %} </div> <div class="col-sm-10 "> {% block content %}{% endblock %} {% block pagination %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ … -
Bokeh 0.13 move from components to curdoc with django
Here (https://bokeh.github.io/blog/2018/6/13/release-0-13-0/) it is mentioned that now we can use curdoc() instead of components. I tried to move the following code view.py: script, div = components(PlotView().make_plot(), CDN) context['plot_script'] = script context['plot_div'] = div template.html: {% if plot_script %} {{ plot_script|safe }} {% endif %} {% if plot_div %} {{ plot_div|safe }} {% endif %} to the curdoc example provided in the link. But this line in the template file {{ embed(roots.region) }} doesn't make sense for django. -
Django: Highlight Table Row when user is found
I've got two models (participant, holder) which have the same fields: first_name, last_name and date_of_birth In the detail view of my participant Model I check if those fields are the same as in my holder model: for holder in Holder.objects.all(): if participant.last_name == holder.last_name and participant.first_name == holder.first_name and participant.date_of_birth == holder.date_of_birth: has_item = True and then return that with a render_to_response return self.render_to_response({ 'has_item': has_item, }) And in my HTML I've got then this: <td>{% if has_item %}<a href="{% url 'vouchers:holders' %}">Voucher(s) found</a> {% else %}No voucher found{% endif %}</td> This links the user from the detail view of my participant to my ListView of my Vouchers with all Holders listed in a table. Now my question would be, when redirecting the user to this List, is it possible to somehow highlight the exact user that was found having the vouchers? So for example if John Doe has a voucher, show the link in his profile, which redirects him to the list of all holders and highlights every row where his FirstName, Lastname and Date of birth is the same. Is that possible with maybe using JavaScript? -
Why do I get this error: _mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h'?
I'm on a windows computer running Python 3.6 and django version 2.0.7. I've created a virtual environment using virtualenv and I'd like to use mysql, so I tried installing it by using pip like so... pip install mysqlclient That throws me the error above. I've looked up possible solutions on github and stackoverflow but most of them have to do with other files, not "mysql.h". Either way though, I've tried those solutions but neither seems to work for this case. I don't know what I'm doing wrong. The full error message looks like this... _mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2 If it is of any significance, I am using git bash as my terminal. -
SQL file into JSON data
I have a sql "test.sql" file. What I want to do is convert the sql file to JSON data and save it into my database in django. What are the ways in doing this.