Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Querying for a subsequence using Django ArrayFields
I have an ArrayField that stores sequences of integers in it, for example, Sequences.objects.first().seq returns [5,4,4,3,2,2,1]. The sequences are always stored in decreasing order, and I want to filter Sequences to find a subsequence. However, I'm running into problems when trying to find a subsequence that contains repeated elements and I don't know how to go about solving this problem. For instance, if I wish to filter for any sequence containing the subsequence q = [5,4,4,4,2], I would try Sequences.objects.filter(seq__contains=q), but this filter will include the sequence [5,4,4,3,2,2,1], since each element of q is individually in the sequence, but not all together. -
Django says CSRF token is incorrect or missing when I try to sign in to admin section
I'm using django 2.1.1 and I'm following the django release notes can't seem to figure out what's wrong -
how can i increment a variable with an "if" in a django template?
I'm trying to increment a variable with "if" in the Django template, I've already tried all the suggestions on this site, but none have solved my problem. there is views.py class IndexView(generic.ListView): template_name = 'home/index.html' context_object_name = 'problemes' def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data['problemes'] = Probleme.objects.all() context_data['commentaires'] = Commentaire.objects.all() return context_data def get_queryset(self): result_list = self.get_context_data return result_list and index.html .... {% for problem in problemes %} {% with number_comment= 0%} {% for comment in commentaires %} {% if comment.probleme.id == problem.id %} {% number_comment ++ %} {% endif %} {% endfor %} <tr data-status="pagado"> <td> <div class="votes"> <div class="mini-counts"><span title="74 votes">74</span></div> <div>votes</div> </div> </td> <td> <div class="status answered-accepted" title="one of the answers was accepted as the correct answer"> <div class="mini-counts"><span title="2 answers">{{ number_comment }}</span></div> <div>answers</div> </div> {% endwith %} .... -
How to base64 encode a StringIO
AIM I am attempting to encode a folium choropleth as StringIO. I am basing my answer of a related query. I have checked the answers here and here. ERROR AttributeError: 'bytes' object has no attribute 'encode' CODE views.py def get_choropleth(self, request): # make choropleth ('m') html_string = m.get_root().render() f = StringIO(html_string) choropleth = base64.b64decode(f.read()) choropleth = choropleth.encode('utf8') # causing error return {'choropleth':choropleth} -
Replacing text in Django variable within template
I have a page in my web app that takes one object from the database, and prints the attributes (column: description: value) in a table. I am passing the object from my Django view to the template and rendering it like so: <table style="width:63%"> <thead> <th style="text-align: left;"><u>Field Name</u></th> <th style="text-align: left;"><u>Description</u></th> <th style="text-align: left;"><u>Value</u></th> </thead> <tbody> {% for field in obj %} {% ifnotequal field.name "poly" %} <tr> <td><span style="font-weight:bold">{{ field.name }}</span></td> <td><i>{{ field.label }}</i></td> <td>{{ field.value }}</td> </tr> {% endifnotequal %} {% endfor %} </tbody> </table> where "obj" is the object from the query. Some of the field's description have "km^2" as defined in models.py, i.e class MaxExtent(models.Model): # Model fields correspond to subset of fields in MaxExtent_2000to2015.shp: id = models.IntegerField(primary_key=True) # gridcode areaMax = models.FloatField('Max Extent area (km^2)') area2000 = models.FloatField('2000 area (km^2)') area2001 = models.FloatField('2001 area (km^2)') area2002 = models.FloatField('2002 area (km^2)') However, I do not like how that looks in my webpage as I would prefer to use superscript instead of "^2"... Is there a straightforward (or complicated I supposed) way to render these with a superscript instead of km^2? I thought about 1] removing the km^2 part from my description in the model and … -
Using RPi.GPIO with django
I have django project set on my pc and copy of that project on Raspberry pi 3. I deploy changes through pyCharm to raspi. Raspberry is my server where I host my website. I wanted to play with led light through web app. In my app I've imported import RPI.GPIO as GPIO but after server run there was ImportError: No module named 'RPi'. I've managed to install only gpio on pc (No matching distribution found for RPi), but there is still ImportError : No module named 'gpio'. Here is my code in views.py import gpio LED_PIN = 18 def turnOn(request): gpio.setmode(gpio.BOARD) gpio.output(LED_PIN, 1) return HttpResponse('') Is there any possibility to use RPi.GPIO in django on pc? -
How to add placeholder UserCreationForm django?
I'm trying to add a placeholder to the username field in the UserCreationForm but i can't understand how to do it. I have already change the forms.py file in this way /lib/site-packages/django/contrib/auth/forms.py. I add a placeholder to password1 and password2 fields and work like this: class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'placeholder':'Password'}), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput(attrs={'placeholder':'Confirmar Password'}), strip=False, help_text=_("Enter the same password as before, for verification."), ) I can see probably the username field is coming from class meta: class Meta: model = User fields = ("username",) field_classes = {'username': UsernameField} from this class but i'm not sure about that class UsernameField(forms.CharField): def to_python(self, value): return unicodedata.normalize('NFKC', super().to_python(value)) I don't understand how add a placeholder to username field this is my html <form method="post" action="."> {% csrf_token %} {% for field in form %} {{ field }}<br /> {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} {% endfor %} <input id="submit-signup-btn" type="submit" value="Iniciar"/> </form> -
how to use django-realestate documentation
i working on a real estate project using python-django i searched on google for an open source django project to get more idea about its models, to better implement my project i have found [https://django-real-estate.readthedocs.io/en/latest/][1] now i want to install the django-realestate , but i dont know how to use it , and implement its view and models , please someone can guide me , i appreciate it -
django how to display number of items
I was wondering how I do count the number of poll in my question model using set_count and I also want to display it in a template please show me using the code thanks -
Displaying images from database Digital Ocean
Why images doesn't show in template? Locally everything is fine, but when i push it online it seems (in browser) like images doesn't exist (even though I can see that they are properly saved in location pointed in models.py). I'm using digitalocean one-click feature. DB is SQLite. Here's my code: settings.py STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_URL = '/static/' models.py class ScreenShots(models.Model): img = models.ImageField(upload_to='img_api/static/img_api') ... @property def filename(self): return os.path.basename(self.img.name) def get_img_url(self): return '/static/img_api/' + self.filename template: <img src="{{ img.get_img_url }}"> <img src:"/static/img_api/test.jpg"> - that's how it looks in browser folder structure: |- project | |- setting.py etc. |- img_api | |- models.py | | - ... | |- static | |- img_api | |- here .jpg files are saved here -
In any questions django app , how to enable user to delete only those questions that were created by them
I have created a simple question apps , when clicked on questions it shows its options or choices.I made login and signup forms to make user-login.I want to know how can I limit the user to delete the questions created only by them.Every question has a delete key infront of it. I read most stuff about permissions but didnt got it how to do it. I may apply permission not to delete any question but how to restrict a user not to delete only some specific questions or questions that weren't created by them. below is views.py def addquestion(request): item_to_add = request.POST['content'] item = Question.objects.create(question_text=item_to_add,pub_date=timezone.now()) user_now = Question(user = request.user) item.save() return HttpResponseRedirect('/home/questions') def deletequestion(request,question_id): item_to_delete = Question.objects.get(id=question_id) if item_to_delete.user == request.user: item_to_delete.delete() else: return HttpResponse('You are not authorised to delete this question') Here is models .py from django.db import models from vote.models import VoteModel from django.contrib.auth.models import User # Create your models here. class Question(VoteModel,models.Model): question_text = models.TextField(max_length=300) pub_date = models.DateTimeField('date published') user = models.OneToOneField(User,on_delete = models.CASCADE,null=True) def __str__(self): return self.question_text class Choice(models.Model): choice_text = models.CharField(max_length=300) votes = models.IntegerField(default=0) question = models.ForeignKey(Question,on_delete = models.CASCADE) def __str__(self): return self.choice_text -
How can I make javascript apply to list of elements?
I want to flip cards in the browser. The elements are rendered with a Django template for loop. I'm able to flip the first card, but not the rest. I want them to flip individually. Here's html: {% for element in elements %} <div class="outer"> <div class="inner"> <div class="card-back"> <span>{{ content }}</span> </div> <div class="card-front"> <span>{{ content }}</span> </div> </div> </div> {% endear %} Here's javascript: # works for the first element var card = document.querySelector('.inner'); card.addEventListener( 'click', function() { card.classList.toggle('is-flipped'); }); # this function seems to break things function() { var cards = document.querySelectorAll(".inner"); for ( var i = 0, len = cards.length; i < len; i++ ) { var card = cards[i]; clickListener(card); } }); -
Post request in Django results in Broken Pipe
I'm trying to make a post request from a react frontend to a django backend to log a user in, and redirect to a new page. The issue I'm having is that even though the request reaches the server and I can get the data when it comes time for django to redirect, the redirect does not happen and their is an output in the console that says "Broken pipe from ('127.0.0.1', 64989)". I've done some research online about this issue, but I still can't figure out how to fix it. However, everything works fine when I use a an html form element with an action and method type. Below I have shared my code. React Frontend handleSubmit = () => { let csrfToken = Cookies.get('csrftoken') let endpoint = this.state.isLoggingIn ? LOGIN_ENDPOINT : REGISTER_ENDPOINT; axios({ url: endpoint, method: "POST", data: { username: this.state.username, password: this.state.password, displayName: this.state.displayName, }, headers: {"X-CSRFToken": csrfToken}, responseType: "json", }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); } Django Backend def login_view(request): if request.method == 'POST': #username = request.POST.get('username') <= I use this and below, for to get data sent via a form with an action and method set. #password = request.POST.get('password') body_unicode = request.body.decode('utf-8') … -
Django tests are failing randomly
I'm trying to figure out why, under unknown circumstances, tests in Django projects are failing randomly. See this patch as an example. As you can see on the bottom of the patch page, test build are failing randomly, with this error: 17:02:08 ====================================================================== 17:02:08 FAIL: test_ticket_edit (trackersite.tracker.tests.TicketEditTests) 17:02:08 ---------------------------------------------------------------------- 17:02:08 Traceback (most recent call last): 17:02:08 File "/src/trackersite/tracker/tests.py", line 654, in test_ticket_edit 17:02:08 self.assertRedirects(response, reverse('ticket_detail', kwargs={'pk': ticket.id})) 17:02:08 File "/src/.tox/jenkins/local/lib/python2.7/site-packages/django/test/testcases.py", line 283, in assertRedirects 17:02:08 (response.status_code, status_code)) 17:02:08 AssertionError: Response didn't redirect as expected: Response code was 403 (expected 302) When I uploaded a dummy patch and issued recheck several times, I wasn't able to get the tests fail. Also, another real patch is succesfully passing the tests. You can see more details on this task. How can I fix this issue? -
Reverse for 'detailed_view' with no arguments not found
Following is my code from views.py from . import views app_name = 'blogs' urlpatterns = [ path('', views.blogs_home, name='blogs'), path('<int:post_id>', views.single_blog, name='detailed_view'), ] Following code is from views.py def single_blog(request,post_id): blog_single = Blogs.objects.get(id=post_id) context = {'blog_single': blog_single} template = 'blog_home.html' return render(request, template, context) and html is given below {% for b in blogs %} <div> <h1><a href="{% url 'blogs:detailed_view' id=b.id %}">{{ b.title }}</a></h1> <p>{{ b.body }}</p> <aside>{{ b.date }}</aside> </div> {% endfor %} However, it returns the error reverse for 'detailed_view' with no arguments not found. Can you please explain and correct. Thank you Jeff -
Django background thread
I am making a Django app. it needs to do background work (interacting with outside APIs) while the server is running, so it looks to me like I need to start a separate thread independent from all outside requests. What is the best way to go about this? my first instinct was to simply import threading and start another thread, but where would I place that code in the Django app? is that even the right approach? do I need to make an outside service script that communicates with the app? my googling has only lead me to things like django-background-tasks and celery, though from my understanding those solutions are only for tasks in views that take a long time, for returning the webpage before the task is actually done. do these solutions have support for background threads? I'm not looking for running a function every x amount of time, I want it to run forever from the moment Django starts. I want it to be preferably self-contained inside the app, so a solution without an outside service script would be ideal. I want the app to be installable via pip. -
TypeError: cannot unpack non-iterable int object in Django views function
Following is my code in URL.py, views.py and HTML page. However, it returns me the error: TypeError: cannot unpack non-iterable int object. urlpatterns = [ path('', views.blogs_home, name='blogs'), path('<int:id>', views.single_blog, name='detailed_view'), ] I am trying to capture the id of posts blogs in the list view to get the blog object from the database with id query. Following is my view code. def single_blog(request,id): blog_single = Blogs.objects.get(id) context = {'blog_single': blog_single} template = 'blog_home.html' return render(request, template, context) However, as I mentioned, it returns the above error. Could someone explain what I am doing wrong -
Creating a system with multiple userprofiles
I'm currently designing a CRM-Software, which enables the user to save information about his jobs. The idea is that the user can have different Useraccounts for different Workfields he's working in. For example, if someone works as a freelance CS-engineer and as a Dj at the same time. My problem is that i don't know how to model the Userprofile into my system. My first idea was to put a 'active_userprofile' FK on my User model, which my User sets via the App. This attribute would be used to always fetch the related data for the needed Userprofile.This sounded good at first, but the more i thought about it it felt like a hack. Because what i think will happen, when i use the App simultaneously on PC & Mobile(Android/iOS) is, that the users won't be able to use seperate Userprofiles on both (or more) devices. So my Question is:What is the best way to implement a System where the User can have multiple Userprofiles and user them on different devices simultaneously? -
Are most third party packages in Python safe to use with Django and Nginx?
So I have been developing an app using the Django Platform, and recently I have been thinking about scalability in the app. I currently am developing this app in a civil engineering research lab, and we don't get a ton of traffic on our current server. I was wondering if some of the apps we develop are able to take multiple requests at the same time in our labs. From my understanding they should, based on how well our server we are using is configured (Nginx in our case, I believe). From what I understand (please correct me if I wrong) our server has some workers (or threads, I think they are the same thing) that will accept requests, then they will go through the code that I have written and generate responses based on what the request is. My main question is if I am using third party packages, are they threadsafe for this type of thing? For example, if I used pandas/numpy/numba/etc... in my controllers, would this be safe when we have multiple users sending requests to multiple threads? -
How to change the data of a table field from another?
Good evening. The goal is that when creating the Transfer model, the sum field was subtracted from whom_from and added to whom_to Bill's model. As I understand it, this needs to be done through save (), but apparently, I did not set it up correctly. What could be the problem? models.py class Bill(models.Model): title = models.CharField(max_length=100) amount = models.DecimalField(max_digits=19, decimal_places=2, validators=[MinValueValidator(0)], default=0) def __str__(self): return self.title class Transfer(models.Model): whom_from = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='whom_from') whom_to = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='whom_to') sum = models.DecimalField(max_digits=19, decimal_places=2, validators=[MinValueValidator(0)], default=0) def save(self, *args, **kwargs): self.whom_to.amount = self.whom_to.amount + self.sum self.whom_from.amount = self.whom_from.amount - self.sum super(Transfer, self).save(*args, **kwargs) -
How to get object and many to many object information
I want to get information: if request user vote for this project. My Project class: class Project(TimestampedModel): title = models.CharField(max_length=120) description = models.TextField() company = models.ForeignKey( Company, on_delete=models.CASCADE ) tags = models.ManyToManyField(Tag) votes = models.ManyToManyField(User) My query, I tried get it by annotate and filter inside, but not work queryset = Project.objects.all() if 'title' in filters.keys() and filters['title'] is not None: queryset = queryset.filter(title__icontains=filters['title']) queryset = queryset.annotate(num_votes=Count("votes")) queryset = queryset.annotate(user_vote=Count("votes__user_id", filter=Q(votes__user_id=filters['user_id']))) queryset = queryset.order_by('-created_at') -
ValueError: Related model 'user.UserProfile' cannot be resolved Django 2.1
I am trying to create a UserProfile model in my user app and instead of inheriting from models.Model, I am inheriting from django's own User model so that I would have a custom user model wwith extra fields. But when I run the python manage.py test command it gives me the following error: Creating test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\commands\test.py", line 26, in run_from_argv super().run_from_argv(argv) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\commands\test.py", line 56, in handle failures = test_runner.run_tests(test_labels) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\test\runner.py", line 604, in run_tests old_config = self.setup_databases() File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\test\runner.py", line 551, in setup_databases self.parallel, **kwargs File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\test\utils.py", line 174, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\db\backends\base\creation.py", line 68, in create_test_db run_syncdb=True, File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\User\AppData\Local\Programs\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, … -
Time difference in Django 1.11
I want my code to do two things: 1. Get datefield to give days only. 2. Get the difference btwn a depature_date and now. Then this should be posted as: 2 days remaining to book. I have been researching without any luck. Please help. Models.py from datetime import datetime; datetime.date; datetime.today; datetime.now class JoinedSafaris(models.Model): package=models.ForeignKey(Packages) Location=models.CharField(max_length=15, default="location") date_of_depature=models.DateField(default=datetime.today) today=models.DateField(default=datetime.now) PS. When i use datetime.date or datetime.day in the fields, I get an error like this: ValueError: Cannot serialize: <attribute 'day' of 'datetime.date' objects> There are some values Django cannot serialize into migration files. -
How to get and set locations using Google Maps API
I have a Django website with me. I have implemented the Google maps Javascript API to it. And when I go to mysite/maps it redirects to an HTML page which displays the Google maps. But I want the feature of getting a location input from the user and when he clicks on search it should point the location on the map. How to do that? Can some please help me out with that? Thank you. -
How to upload File from Angular 7 to Django - get error 403 (Forbidden)
I tried now in so many different ways, I can not get a file uploaded with Angular 7 to the Django Backend - shouldn't be so difficult?! My .html: <div class="form-group"> <label for="file">Choose File</label> <input type="file" id="file" (change)="handleFileInput($event.target.files)"> </div> uploader.component.ts fileToUpload: File = null; handleFileInput(files: FileList) { this.fileToUpload = files.item(0); this.uploadFileToActivity(); } uploadFileToActivity() { this.uploaderService.post(this.fileToUpload).subscribe(data => { // do something, if upload success }, error => { console.log(error); }); } my uploader.service.ts that also shows the upload progress public post( fileToUpload: File): Observable<number>{ const url = '/api/upload/'; var subject = new Subject<number>() const req = new HttpRequest('POST', url, fileToUpload, { reportProgress: true, }); this.httpClient.request(req).subscribe(event => { if (event.type === HttpEventType.UploadProgress) { const percentDone = Math.round(100 * event.loaded / event.total); subject.next(percentDone); } else if (event instanceof HttpResponse) { subject.complete(); } }); return subject.asObservable(); } And in the Django backend: views.py: def post(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): #handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'index.html', {'form': form}) forms.py: class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() and urls.py: urlpatterns = [ path(r'api/upload/', views.post, name='post'), ] When I ran this I get zone.js:2969 POST http://127.0.0.1:8000/api/upload/ 403 (Forbidden) Do I need to include an authorization token? …