Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing themes in Django (Custom templates by users)
I want to implement the feature for users to have custom templates. Like they can place themes or templates in a particular folder relative to the home folder. Each theme may have a folder and some config or preview for example(optional). 1) First I need to figure out how to set custom templates dir for an app. 2) Then I can probably do listdir and get all the folders and then give the admin an option to select the dir. 3) A setting list to specify additonal template folders by users. 1 is the problem. The main question I want answer for is how to set custom template dir which can be modified anytime. -
how to save one column value based on id column in django
I would like to save model id along with other format characters into another column, based on the model id being automatically created. For example, For example, I have column name formated_id in shipment model, and want set its value to "easter" + ID which is automatically generated. How could I achieve that? Thanks. class Shipment(models.Model): formated_id = models.CharField("formatedid",max_length= 50) class Meta: ordering = ['-id'] def save(self, *args, **kwargs): super().save(*args, **kwargs) -
Django force only one filefield use TemporaryFileUploadHandler
I have a filefield and in this filefield I want to upload a zip file and work with it from the view, but without saving it in MEDIA_ROOT, I just want to upload it and extract the xml extract info from the xml to send my model and db, the ones from the xml I have solved it, but my question is how can I use only TemporaryFileUploadHandler in this field, from the views and do all the work, the problem is that when it weighs less than 2.5mb it goes up to memory nothing more and the zipfile asks me for a path that's why I want to use the TemporaryFileUploadHandler, how can I do it? small abstract of my view: @login_required def crear_reporte(request): if request.method == 'POST': form = CreateReportForm(request.POST, request.FILES) if form.is_valid(): report = form.save(commit=False) user = request.user report.owner = UserProfile.objects.get(user_id=user.id) current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M") report.title = 'Reporte de ' + current_time + '.' report.save() filez = request.FILES['upload'] filereport = filez.name path = filez.temporary_file_path filereportcom = path + filereport with zipfile.ZipFile(filereportcom, 'r') as z: for f in z.namelist(): xmlss = len(z.namelist()) print (xmlss) print (filez.content_type) print (filez.size) return HttpResponseRedirect('/escritorio') -
SSL errors using Sauce Labs in Travis CI with Selenium webriver tests (Django project)
Trying to get some functional tests running for our Django project but we've hit an error that's proving very difficult to debug. We've attempted to set up sauce connect, but our build is failing. You can see the results of the build, but here's the stack trace. ====================================================================== ERROR: test_page_load (quote_me.tests.FunctionalTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/opt/python/3.6.3/lib/python3.6/urllib/request.py", line 1318, in do_open encode_chunked=req.has_header('Transfer-encoding')) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 964, in send self.connect() File "/opt/python/3.6.3/lib/python3.6/http/client.py", line 1400, in connect server_hostname=server_hostname) File "/opt/python/3.6.3/lib/python3.6/ssl.py", line 407, in wrap_socket _context=self, _session=session) File "/opt/python/3.6.3/lib/python3.6/ssl.py", line 814, in __init__ self.do_handshake() File "/opt/python/3.6.3/lib/python3.6/ssl.py", line 1068, in do_handshake self._sslobj.do_handshake() File "/opt/python/3.6.3/lib/python3.6/ssl.py", line 689, in do_handshake self._sslobj.do_handshake() ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:777) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/travis/build/winecountry/quote-me/quote_me/tests.py", line 77, in setUp self.selenium = webdriver.Remote(desired_capabilities=capabilities, command_executor="https://%s/wd/hub" % hub_url) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 310, in execute response … -
Django 1.11 ignoring on_delete=models.set_null
I have a Django project with a model, something like this: class Track(models.Model): title = models.CharField(max_length=255) name = models.CharField(max_lenght=255) class Disc(models.Model): a_side_disc = models.ForeignKey(Track, null=True, on_delete=models.SET_NULL) b_side_disc = models.ForeignKey(Track, null=True, on_delete=models.SET_NULL) in_jukebox = models.BooleanField() This model is totally made up, and don't make sense, but it shows my current setup in this case. Now with Django 1.11 and Django Restframework, I have a route with a delete for a Track. When I call the Route, I check if the Track is on a Disc with in_jukebox set to False. If that is the case I simply go on with the delete. I expect that both ForeignKeys in Disc are set to Null, but instead Disc is deleted as well like I would expect from CASCADE. I use Postgres as database, and inspected the generated Schema. I understand that SET_NULL is done by django and not the database. But it is not done. Am I understanding somthing wrong? Which direction is on_delete working, and if it's only one, how do I make the same on the other side? -
Django - How to use a template tag in an if statement
I thought this idea would be more popular but I am guessing it's an easy solution that I cannot figure out. What I would like to do is in a Django template page, have an IF statement equal another tag value. For example views.py def seasonstandings(request): divisions = Team.objects.order_by().values_list('division__name',flat=True).distinct() stats = WeeklyStats.objects.values('player__team__team_name').annotate( team=F('player__team__team_name'), points = Sum('finishes'), division = F('player__team__division__name') ).order_by('-points') return render(request, 'website/seasonstandings.html', {'divisions':divisions,'stats':stats}) seasonstandings.html {% for division in divisions %} {{ division }} <br> {% for stat in stats %} {% if stat.division = {{ division }} %} {{ stat.team }}<br> {% endif %} {% endfor %} {% endfor %} So if you note the IF statement is trying to use the result of the Division tag from the first for loop. My main objective here is to have a dynamic list of divisions that a team could be in and then when they are assigned their division they would get listed out under the proper division based on these for loops. The End Result looking like Division A Team 1 Team 2 Team 4 Division B Team 3 Team 5 Division C Team 6 Team 7 Any help is appreciated as always. -
Restricting an embedded powerpoint to logged in users only
I am dynamically creating Powerpoints with user's personal information. I wanted to embed them online and Microsoft has the answer for this: <iframe src='https://view.officeapps.live.com/op/embed.aspx?src=[https://www.your_website/file_name.pptx]' width='100%' height='600px' frameborder='0'> Now I am wondering can I restrict these links to specific users? I only want user JOE to see the powerpoint the program created for him. I am planning on making this in Django -
Ubuntu Python: unable to pip install dlib - Failed building wheel for dlib and machine is almost stuck
I am trying to install dlib (machine learning library) for my django python environment. however, i cant get it installed. there is error and stuck. based on this instruction, this is what I did https://www.pyimagesearch.com/2017/03/27/how-to-install-dlib/ $ sudo apt-get install build-essential cmake $ sudo apt-get install libgtk-3-dev $ sudo apt-get install libboost-all-dev $ source somedotcomenv/bin/activate <-- virtualenv $ pip install numpy $ pip install scipy $ pip install scikit-image $ pip install dlib however, it failed and i think stuck, its almost an hour at the last stage. Im not sure if its still compiling or not. [ 82%] Building CXX object CMakeFiles/dlib_.dir/src/dlib.cpp.o In file included from /usr/include/boost/python/detail/prefix.hpp:13:0, from /usr/include/boost/python/args.hpp:8, from /usr/include/boost/python.hpp:11, from /tmp/pip-build-8xkp8e7q/dlib/tools/python/src/dlib.cpp:4: /usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory compilation terminated. CMakeFiles/dlib_.dir/build.make:62: recipe for target 'CMakeFiles/dlib_.dir/src/dlib.cpp.o' failed make[2]: *** [CMakeFiles/dlib_.dir/src/dlib.cpp.o] Error 1 CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/dlib_.dir/all' failed error: cmake build failed! ---------------------------------------- Failed building wheel for dlib Running setup.py clean for dlib Failed to build dlib Installing collected packages: dlib Running setup.py install for dlib ... full execution and error logs here https://gist.github.com/axilaris/fe58937e8ac39386e6e9816833636461 This is the last top process, its stuck not sure its still compiling but its already been an hour. something is stuck. very … -
What is the point of using Gunicorn when hosting a Django project on Linux VM
I have an Linux instance running on Google Compute Engine. I installed pip and django on it and cloned a Django project that I worked on locally. Like I would on localhost I ran my app like so: python3 manage.py runserver 0.0.0.0:8080, and my server was up and running with no problems. I read online on how WSGI servers are required for python apps to run well on servers however I don't see why I would need something like gunicorn to run my app -
Translation with Django
<form class="nav navbar-nav navbar-right" "{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans "Language" %}<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a class="btn btn-default lang_selector trn" href="#" role="button" data-value="ca" href="#"><span><img src="{% static 'orders/images/canada.jpg' %}" alt=""></span>{% trans "FRENCH" %}</a></li> <li><a class="btn btn-default lang_selector step1 trn" href="#" role="button" data-value="en" href="#"><span><img src="{% static 'orders/images/usa.png' %}" alt=""></span>{% trans "ENGLISH" %}</a></li> </ul> </li> <li class="section-btn"><a href="#" data-toggle="modal" data-target="#modal-form">{% trans "Login" %}<br>{% trans "Existing Customer?" %}</a></li> </form> The previous code gives me the following dropdown menu. I'd like the language change if I select FRENCH or ENGLISH. With the question Issue trying to change language from Django template, how could I modify my HTML code assuming that the other requirements are satisfied? -
Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response
I continue to keep getting this error even though I have the headers set in my nginx configuration like so: location / { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; try_files /maintenance.html @uwsgi; } If it's at all pertinent I am seeing this due to a request being made to instagram's api. I am using Spectragram to achieve this, however I do not think that is the issue. If it is I would be happy to give more info. What is additionally odd, is I have this instagram feed plugin working correctly on my localhost:5000, used for development, where I have very little in my nginx configuration, and no headers added... Thanks for any help! -
Javascript mini Navbar insert
I have an interesting but probably simple problem. I am creating a nav bar insert that has 4 JS buttons that toggle hide a division each, I would like each button to hide the other three divisions while showing the one its own division. Currently each button is only attached to it's own division, I am asking for help that would toggle the other three divs. Upon further thought I also would like to have the spades, hearts and clubs divs toggled off while the hearts on when a viewer first enters the page. If you think that there is a better method, I am open to that too, my framework is django jfyi. Cheers! JS: // Card Navigation Bar function dhide() { var x = document.getElementById("diamonds"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } function chide() { var x = document.getElementById("clubs"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } function hhide() { var x = document.getElementById("hearts"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } function shide() { var x = document.getElementById("spades"); if (x.style.display === "none") … -
MySQL with django Grants issue while deploying on pythonanywhere
The MySQL database is connected to the pythonanywhere server. When i insert data in it it gives error 500 after doing R&D I found there is privileges or grant issue. How can i give grants. I used basic Grants query after connection.enter image description here -
Can't save ForeignKey data with Django
I'm trying to make a way to log notes associated with records. When the form is submitted, it's trying to redirect to the same url, but without the record id, which should be required to view the page. I defined it in urls with the record id, so it should be tracker/19/newnote I want it to route to tracker/19/detail, and I'm not sure why it's routing to tracker/newnote, which doesn't exist in my urls file. Maybe I need to create it? anyway, here are my files if anyone wants to take a crack at this with me. models.py class Record(models.Model): serial = models.CharField('Serial Number', max_length=9) product = models.CharField('Product', max_length=6) ticket = models.CharField('Log/RID', max_length=9) eng_date = models.DateField('Date Engaged') customer = models.CharField('Customer', max_length=80) details = models.TextField('Problem Details', max_length=800) owner = models.CharField('Owner', max_length=40) views.py def newnote(request, record_id): if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): r = Record.objects.get(pk=record_id) r.note_set.create(note_text=form.note_text, note_date=form.note_date) r.save() return HttpResponseRedirect('/tracker/%s/detail/' % record_id) else: form = NoteForm() return render(request, 'tracker/noteform.html', {'form': form}) forms.py class NoteForm(ModelForm): class Meta: model = Note fields = ['note_text', 'note_date' ] widgets = { 'note_date': DateInput(),} urls.py urlpatterns = [ path('', views.index, name='index'), path('create/', views.create, name='create'), path('<int:record_id>/detail/', views.detail, name='detail'), path('result/', views.result, name='result'), path('query/', views.query, name='query'), path('all/', … -
Django TransactionManagementError when trying to create token on user post_save signal with Django Rest Framework
I am getting a django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. error when trying to create a Token during a post_save signal with Django Rest Framework. If I remove the post_save signal for the Token creation, everything works, but I get no token so I know it's the token creation causing the issue. If I wrap the Token create statement with a with transaction.atomic(): I get no errors, but the token is never saved to the DB, but I can print the token key value? I'm currently at a loss. Note that I am using PostgreSQL if that makes a difference. Any help is appreciated. Django (1.11.7) djangorestframework (3.7.7) Here is my serializers.py: ... from rest_framework import serializers from django.contrib.auth import get_user_model class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField() password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create( username=validated_data['email'], email=validated_data['email'] ) user.set_password(validated_data['password']) user.save() return user class Meta: model = UserModel fields = ('id', 'email', 'password',) This is my signals.py: ... from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: # with transaction.atomic(): # commented out see above token = Token.objects.create(user=instance) print(token.key) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_profile(sender, instance=None, … -
Dynamic formsets with search inputs
Initially, on the page was only the FIRST formset instance with input so I can search objects in database. After adding some other dynamically via javascript, clicking any of fresh added inputs launch the search in the FIRST, initial input. The problem goes away if i refresh the page. The goal is to achieve that behaviour without refreshing the page. Even when I installed plugin designed for dynamic django forms - the inputs behave in correct way if theyre just standard inputs, but switching them to searchfields triggers behaviour mentioned above. -
how to compare a date field to the current date in django
this is my model class class Truck(models.Model): reg = models.IntegerField() host = models.CharField(max_length = 20) insuranceExp = models.DateField() pollutionExp = models.DateField() fitnessExp = models.DateField() def __str__(self): return str(self.reg) this is my function def asset(request): template = 'notice/alert.html' trucklist = Truck.objects.all() d = date.today() reminder = {'message':[],'trucklist':trucklist} for truck in trucklist: while d<=truck.insuranceExp: if (truck.insuranceExp-d).days==30: warning = 'only 30 days remaining to expire insurance of truck Id = '+str(truck.reg) reminder[message].append(warning) elif (truck.insuranceExp-d).days==15: warning = 'only 15 days remaining to expire insurance of truck Id = '+str(truck.reg) reminder[message].append(warning) elif (truck.insuranceExp-d).days==7: warning = 'only 7 days remaining to expire insurance of truck Id = '+str(truck.reg) reminder[message].append(warning) else: pass how would i compare both of them in a no. of days please help me thanks in advance -
pass data from Django to amchart JS with JSON
I want to pass data from my Django view to my html and then take the data to my chart js or pass the data directly to my amchart. views.py: def nodo_detail(request,nodo_id): El_Nodo = Nodo.objects.get(pk=nodo_id) all_nodos = Nodo.objects.order_by('pk').all() var = Variable() v = dir(var) elemento = El_Nodo.variable_set.order_by('pk').all() watts = elemento.last().Watts prefix = '' chartData = "[" for t in elemento: chartData += prefix chartData += "{\n" chartData += " date: " chartData += '"' + str(t.Data_time.year) + "-" chartData += str(t.Data_time.month) + "-" chartData += str(t.Data_time.day) + " " chartData += str(t.Data_time.hour) + ":" chartData += str(t.Data_time.minute) + ":" chartData += str(t.Data_time.second) + '"' + ",\n" chartData += " value:" chartData += str(t.Watts) + ",\n" chartData += " volume: " chartData += str(t.Watts) + "\n }" prefix = ", " chartData += "]" context = {'El_Nodo': El_Nodo, 'all_nodos': all_nodos, 'v': v, 'watts': watts, 'chartData':chartData, "asdf":json.dumps(chartData)} return render(request, 'inicio/detail.html', context) The data that I want to pass is chartData, with the for loop I try to do the JSON format also I try the JSON python librery. detail.html: {% block Stock %} <input type="hidden" id="stock" value="{{chartData}}"> <!-- or asdf--> {% endblock%} amchartjs: var chartData = JSON.parse(document.getElementById("stock").value); // or directly var chartData … -
Django crudbuilder & Bootstrap datepicker
Django==1.11.7 django-crudbuilder==0.2.5 Using Bootstrap datepicker. Now trying to use the datepicker in a crud form for a date field. In a normal Django form, this would work: self.fields['payment_date'].widget.attrs.update({'class': 'datepicker'}) But how can the class:datepicker be set for a particular field in a crud form? The documentation does'n seem to mention anything useful on css or html class -
clean method not working for URLField
I'm working on something where I require users to enter URLs. I then realized that most users don't prepend 'http://' when writing a URL and then I decided to use a clean method. After checking lots of places for URLField clean methods, I came up with this: def clean(): cleaned_data = super().clean() url = cleaned_data.get('url') if url: if not url.startswith('http://'): url = 'http://' + url cleaned_data['url'] = url return cleaned_data Unfortunately, this doesn't work as I still get the invalid url error. Is there something I'm missing? And if yes, what? -
Django Form Wizard Dynamic Form Not Saving Data
Currently Happening: Dynamically generated form and form fields are being displayed. Enter some data into the said fields, but self.get_all_cleaned_data() returns nothing. Form returns to page 0 instead of submitting the form and using done() What I want to happen: - Data in fields to be retained and displayed when going back, or to the confirmation page - Form to actually submit and use done() to process and save The following the my forms.py class OrderForm(forms.Form): class Meta: localized_fields = ('__all__',) def __init__(self, *args, **kwargs): self.fields = kwargs.pop('fields') fields = self.fields super(OrderForm, self).__init__(*args, **kwargs) if not isinstance(fields, str): for i in fields.fields.all(): widget = forms.TextInput() _type = forms.CharField if i.field_type == Field.TEXTAREA_FIELD: widget = forms.Textarea ... self.fields[i.name] = _type(**fields) This is supposed to get Database created forms and field data and generate fields accordingly. For example: Form A has fields: Name (Regular Text Field) Address (Textarea) The above code will then generate fields for those. The next block of code is from my views.py file FORM_TEMPLATES = { "0": 'order/details.html', "1": 'order/details.html', "2": 'order/details.html', "3": 'order/details.html', "4": 'order/details.html', "confirm": 'order/confirm.html', } class Order(SessionWizardView): form_list = [OrderForm] def get_current_step_form(self, company, *args, **kwargs): step_form = [Form.objects.all()] step_form.append('Confirm') return step_form def get_context_data(self, form, … -
Django 2. Auth views template_name config
I want to use Django v2 LogIn class based view but i notified something there class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/login.html' redirect_authenticated_user = False extra_context = None The template_name config was registration/login.html ? it is too strange I have another folder names. But here is as static template_name :( Many problems were due to this So question is what to do in my own views? in auth.views making template_name = None is showing a error: IsADirectoryError at /login/ Thanks) -
Using Firebase Auth with Django
I want to use firebase authentication for my django webapp. To achieve this, I think would I need to write a custom auth backend - is that right? I don't see any libraries that already do this - django-allauth looks like it comes pretty close as an alternative but I am interested in the phone number verification provided by firebase. I'm also confused about what happens to the User model and functions like request.user or user.is_authenticated. Right now I use the authenticate and login functions - how does django know that a user is logged in via firebase? Would I still be creating a User model for every user? Thanks -
Django form missing fields
I'm trying to get a simple form working. Oddly, other forms I wrote in this app are working fine, but this one wont show the fields. Can anyone tell me what I'm missing? Here are the files views.py: def newnote(request, record_id): if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/tracker/all/') else: form = NoteForm() return render(request, 'tracker/noteform.html', {'form': form}) models.py class Note(models.Model): record = models.ForeignKey(Record, on_delete=models.CASCADE) note_text = models.CharField('Notes', max_length=2000) note_date = models.DateField('Date Entered') forms.py class NoteForm(forms.Form): class Meta: model = Note fields = ['note_text', 'note_date' ] template (noteform.html) <form action="/tracker/newnote/" method="post"> <div id="fields"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </div> </form> One other note, I have commented out the div id called "fields", to rule out CSS as the issue. -
Reverse Language Translation in Django
I'm building an API using Django Rest Framework that needs to support multiple languages, we're trying to use the Django translation framework, and using the answer from here I've decided how to implement translatable choicefields. However my issue is for the reverse case. Say I have a model like this: from django.utils.translation import ugettext_lazy as _ class Payment(models.Model): OPEN = 0 CLOSED = 1 BALANCE = 2 STATUS_CHOICES = ( (OPEN, _('open')), (CLOSED, _('closed')), (BALANCE, _('balance')), ) status = models.IntegerField(choices=STATUS_CHOICES, default=OPEN, verbose_name=_("Status")) This works fine for returning the information to the user, we use the stored status value and translate it before returning. However, I also want the user to be able to POST a new payment object using any language. So if the user wants to create an open transaction, they can send {'status':'open'} but they can also send it in Spanish as {'status':'abierto'}. Is there a way to handle this automatically? Basically I want to get the reverse of the ugettext_lazy function.