Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Transform a dictionary in a list in Python
I would like get data from id property and transform in a list queryset = [{"id":1,"name":"John"},{"id":2,"name":"John"}] Expected result ('1','2') ## ID PROPERTY -
Creating Django User object for each user in backend
I'm writing a custom backend for authenticating users by their email address instead of username. I've already written a custom User model that inherits from AbstractUser: class User(AbstractUser): email = models.EmailField( _('email address'), max_length=150, unique=True, primary_key=True, help_text=_('Required. 150 characters of fewer. Must be a valid email address.'), error_messages={ 'unique':_("A user with that email address already exists."), }, ) As you can see, I've made the email-field unique, and also, a primary key. I'm following the docs for how to write the backend, and I've read this: The Django admin is tightly coupled to the Django User object. The best way to deal with this is to create a Django User object for each user that exists for your backend (e.g., in your LDAP directory, your external SQL database, etc.) You can either write a script to do this in advance, or your authenticate method can do it the first time a user logs in. It says that I should create a Django User object (which I'm guessing is the default User object django.contrib.auth.models.User) for each user in my backend. Question 1: If a backend is a class that implements get_user(user_id) and authenticate(request, **credentials) (this is said in the docs), how … -
Django fire signal user_logged_out on browser close
I'm working on a django application with a chat for users. Therefore I need to present the status logged in or logged out to the other users. To accomplish this I used the signals environment of django. As long as the users are using the log out button everything works well. In case they are jut closing the browser or the tab there's no way to detect the status switch to offline. What is the best way to fire the user_logged_out signal, when the browser or tab gets closed? -
Where does user_id in get_user(user_id) come from?
I've read that an authentication backend needs to implement the methods get_user(user_id) and authenticate(request, **credentials). Now, user_id in get_user(user_id) must, according to the docs, be a primary key of the user model, and the method must return the user object corresponding to the user_id. My question is, where does the user_id argument come from? Is it the username/email/whatever that is entered by the user upon authentication? And if so, why does it have to be a primary key? Why can't I be free to find the intended user in any way I see fit, inside of my get_user() method? -
I'm trying to "print" and oracle query in django
I'm trying to print the result of a query in a HTML page on django. I have everything set but I don't know what to put in the HTML file to print the query. For example, my view is -
django get a full-size image per click Translated with www.DeepL.com/Translator
I use django cms, but django is very flexible. I would like to know how to get a full-size image that displays to the web user when he clicks on it. I can't find a Django application that does this, but it must certainly excite. If not, what is the best way to implement this feature? Thank you -
ImportError: No module named urls while importing urls
in urls.py i am trying to import urls but it shows error from django.conf.urls import * """ImportError: No module named urls""" -
Pluralize choices of a Model's Field and translate them
I am using Django's i18n mechanisms to translate an app in several languages. Situation I have a Model with a Field takings choices: from django.utils.translation import ugettext_lazy as _ class Offer(models.Model): WEEK = 'week' MONTH = 'month' YEAR = 'year' DURATION_CHOICES = ( (WEEK, _('week'), (MONTH, _('month'), (YEAR, _('year'), ) duration = models.CharField(choices=DURATION_CHOICES, max_length=5, blank=True, null=True, \ verbose_name=_("offer's duration"), help_text=_("Duration for which an offer, once subscribed, stays valid") If I want to display this field in a template: {{ counter }} remaining {{ offer.get_duration_display}}{{ counter|pluralize}} Where counter is an integer, offer an Offer object. Here it works well enough because plural forms for ('week', 'month', 'year') are ('weeks', 'months', 'years'), same words with an 's' ending. Problem Now let's say I want to translate my app to French. This gets tricky, because the corresponding translations are ('semaine', 'mois', 'année') and their plural forms are ('semaines', 'mois', 'années'): the translation for 'month' is the same in singular and plural forms. So what I would like to do is defining custom plural forms for each choice in the duration Field. Sure enough, I could use if statements, but this is not elegant nor practical. So I tried to find a DRY solution. … -
'NoneType' object is not iterable Error
I'm trying to find the Answer views by a user. Here's what i'm trying in view, def answer_views(request): if request.user.answer_set.all: views = Answer.objects.filter(user=request.user).aggregate(Sum('hits')) else: views = 0 return ... views Here's the hits field in model, hits = models.IntegerField(default=1) But it's raising an error, TypeError: 'NoneType' object is not iterable How can I fix that? Thank You . . . -
Django tag within URL tags
I would like to use dynamic images based on a a pk of the page. To be clearer I have a survey app, using one question per page .. which mean that the user is presented a question he answers and is redirected to the next question. Each question has a different id and I would like to attach to each question an image. Right now I have a static image lik that : <div class="col-5"> <img src="{% static 'images/RightSpeech.jpg' %}" class="img-fluid" alt="Responsive image"> </div> but I would like to make it dynamic.. I tried something like that with no success: <div class="col-5"> <img src="{% static 'images/image{{question.pk}}.jpg' %}" class="img-fluid" alt="Responsive image"> </div> any idea ? -
Django parallel are fialing if tests need to access files
I have a Django app that has many tests and it's taking a long time to finish testing, I'm thinking to run those tests on parallel, I tried but there is a problem with tests that need to access files, some tests are creating files and check if these files are created and exists in a path. For example, we have a test that will check-in a git repository and check if the git repository exists in the path. How to fix this issue? -
File lock in django
In my web application,created using django. I am reading a file from different instance and displaying the file with few editable text boxes. Once we edit it, when the save is clicked the file is written on the instance from where it is read. Now I have to lock the file once an user opens the file and edits it and tell other users to wait(but still they should be able to view the file only save cannot be done). I tried django-lock, simple Filelock. But did not get a clean example and got stuck. Note: There are no Models created. Users are created through the admin page. I read many docs where it is mentioned about models. If models are the only option how should i use it in my application. -
Django Connection Timed Out
I have installed a Django server on my home computer which is accessible from internet. The user can upload a file which is processed and than is redirected to another web page from where can download the result. The duration of input file handling can take between 30 secs to ~ 10 minutes depending of it's size. If I access the website from my home network, everything is working fine but when I access it from internet, I can only use small input files which can take up to max 30 seconds to process. If I wait for the result for more than 30 seconds, I get "Connection Timed Out" on my browser. Which would be the simplest solution to overcome this problem, either a timeout parameter config or making Django to send keep alive messages to user? Thank you -
Not getting parameters from openlayer 2 -request to django 1.11
I am using openlayers 2, Python2.7 & Django 1.11. For a search, I need to send a request with parameters from openlayers(javascript) to Django 1.11. I am able to submit the request but the parameters are not getting. My code is: Javascript: var params = '' var opnLyrRequest = new XMLHttpRequest(); params = 'pid=15&ctype=25&stype=50' opnLyrRequest.open('POST','/test/search/',true); opnLyrRequest.onreadystatechange=function(){ if(opnLyrRequest.readyState==4 && opnLyrRequest.status==200){ if(pinGeoJsonFrmt.read(opnLyrRequest.responseText)!=null){ dataLoc = pinGeoJsonFrmt.read(opnLyrRequest.responseText); if (dataLoc.length > 0) alert("Found !!"); else alert("No Data Found !!"); } } } opnLyrRequest.send(params); And the Django code working on the above request is: @csrf_exempt def searchSubmit(request): print request print request.method print request.POST print request.GET .... .... The getting output like this: <WSGIRequest: POST '/test/search/'> POST <QueryDict: {}> <QueryDict: {}> The parameters are missing !! -
bootstrap navbar dropdowns not showing with django
I'm trying to add twitter-bootstrap to a django project. I've got a html file called base.html which acts as a wrapper file for other html code which is placed inside of it before it gets send back in the HttpResponse. base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="{% static '/css/bootstrap.min.css' %}" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src = "{% static '/js/bootstrap.min.js' %}"></script> <title>TITLE</title> </head> <body> {% autoescape off %}{{ content }}{% endautoescape %} </body> </html> This file is the only file which will ever get send back to the visitor of the webside so I would imagine that if I add the files bootstrap needs inside base.html that it would work also on the code in content. Infact, all the css stuff seems to work fine but whenever I try to open a dropdown menu in the navbar of my site, it does not show up. This is the source code of the page that has difficulties: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src = "/static/js/bootstrap.min.js"></script> <title>TITLE</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse … -
Fill a form field with initial values from another model (which is a foreign key)
I have 2 models, Company and Post. class Post(Meta): company = models.ForeignKey(Company, related_name='company', on_delete=models.CASCADE) company_description = models.TextField(max_length=800) What I need: 1) When a user create a post, the company FK will be set thru code 2) Also at form initialization the field company_description, will be prepopulated from the Company model, field description(not the same name) 3) On save if the user doesn't modify anything to the field, the initial value will be save 1,2,3 only on creation. I checked Django documentation regarding initialization but their example, is more simple they just get some data/text, in my case I first need to set FK, than get description from the FK Model, so not just text. -
Post form data to Api for foreign fields
I have : class StudentProgramSerializer(serializers.ModelSerializer): school_program = SchoolProgramSerializer() student = StudentSerializer() class Meta: model = School exclude = ('student_program_id', ) class CourseSerializer(serializers.ModelSerializer): school_program=SchoolProgramSerializer(read_only=False) class Meta: model = Course exclude = ('course_id',) def create(self, validated_data): program_dict = validated_data.pop('school_program.school', None) print(program_dict) program = Program.objects.get(program_name=program_dict) return Course.objects.create(program=program, **validated_data) models: class StudentProgram(models.Model): student_program_id = models.AutoField(primary_key=True) school_program = models.ForeignKey(SchoolProgram,on_delete=models.CASCADE) student = models.ForeignKey(Student,on_delete=models.CASCADE) class Course(models.Model): course_id = models.AutoField(primary_key=True) school_program = models.ForeignKey(SchoolProgram,on_delete=models.CASCADE) course_name = models.CharField(max_length=120) creation_date = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) update_time = models.TimeField(auto_now=True) def __str__(self): return self.course_name How to add a course in forms to a apiview? How to deal with foreign fileds? -
DJango Jinja logic in HTML Page, cannot display html snippet
I have the following code in an html page and am trying to use jinja logic to embed html somewhere specific (in the blog/about me section of the html) Code that doesn't work (see specifics below) <!-- About Section (Blog)--> <section class="bg-primary text-white mb-0" id="about"> <div class="container"> <h2 class="text-center text-uppercase text-white">Blog</h2> <hr class="star-light mb-5"> <div class="row"> <div class="col-lg-4 ml-auto"> <p class="lead">This is the blog section</p> {%block content%} {%endblock %} </div> <div class="col-lg-4 mr-auto"> <p class="lead">The blogs outlined in the models section and stored in the database, are going to be displayed here.</p> </div> It's these two lines that ordinarily produce an htmlsnippet output: {%block content%} {%endblock %} In another place on the site (right at the bottom) I've used the same logic, and the snippet output has displayed fine. Code that works fine <!-- Custom scripts for this template --> <script src="/static/js/freelancer.min.js"></script> <div> {%block content%} {%endblock %} </div> </body> </html> The error I get is: 'block' tag with name 'content' appears more than once 141 <div class="col-lg-4 ml-auto"> 142 <p class="lead">This is the blog section</p> 143 {%block content%} 144 {%endblock %} 145 </div> 146 <div class="col-lg-4 mr-auto"> 147 <p class="lead">The blogs outlined in the models section and stored in the … -
Enforcing unique constraint based on foreign key
I enforced a unique constraint for a column and since the constraint is enforced on the entire table, is there a way to make a column unique based on the foreign key? Models class Bucket(models.Model): """This class represents the bucket model""" title = models.CharField(max_length=255, blank=False, unique=True) class Bucketlist(models.Model): """This class represents the bucketlists model""" bucket = models.ForeignKey(Bucket, on_delete=models.CASCADE, related_name='bucketlists') name = models.CharField(max_length=255, blank=False, unique=True) E.g I created 2 buckets (bucket 1 and bucket 2) Created the following bucketlists bucketlist1 -> Bucket1 bucketlist2 -> Bucket1 Attempting to create bucketlist1 in bucket 2 bucketlist1 -> Bucket2 (This throws an error) -
How can I let the superadmin user and user itself to access a API?
I have a UserUpdateAPIView, in it I can edit the user information: class UserUpdateAPIView(RetrieveUpdateAPIView): queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4) serializer_class = UserDetailSerializer lookup_field = "username" def perform_update(self, serializer): serializer.save() The UserDetailSerializer: class UserDetailSerializer(ModelSerializer): """ user detail """ class Meta: model = User exclude = [ 'password', ] depth = 1 Now, every user can access the UserUpdateAPIView, so its a bad design. I just want the super admin and the user itself can access the APIView, how to implement it? I know I can use permissions = [IsAdminUser] to allow the admin users to access this API, but I just want to let the super admin user and the user itself to access. -
I have a TypeError: expected string or bytes-like object during "migrate" (Django)
I am using Django. I changed something in my model, which is 'datefield'. I changed it from datetimefield ('taxi_time') to datefield ('taxi_date') & timefield ('taxi_time'). I did manage.py makemigrations but I couldn't manage migrate. Error is following. Running migrations: Applying taxi.0017_auto_20171214_2256... OK Applying taxi.0018_auto_20171214_2336...Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards field, File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 238, in add_field self._remake_table(model, create_field=field) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 113, in _remake_table self.effective_default(create_field) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 229, in effective_default default = field.get_db_prep_save(default, self.connection) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1301, in get_db_prep_value value = self.get_prep_value(value) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1296, in get_prep_value return self.to_python(value) File "/home/heesu/myvenv/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1258, in … -
How to print a form using reportlab package in django?
views.py in function some_view the drawing function p.doForm is not taking a Form model as input .what i have to do to print that form into pdf. i need to conver that object into string or send info form requests from django.http import HttpResponseRedirect, HttpResponse, request from django.shortcuts import redirect, render from .forms import Form_db_att from django.utils import timezone from .models import FormDb # Create your views here. def home(request): if request.method == 'POST': form = Form_db_att(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.timestamp = timezone.now() model_instance.save() return HttpResponseRedirect('/home/test') else: form = Form_db_att() return render(request, 'mforma/name.html', {'form': form}) def thanks(request): form = Form_db_att(request.POST) model_instance = form.save() model_instance.save() return render(request, 'mforma/thanks.html', {'form': form}) from reportlab.pdfgen import canvas from django.http import HttpResponse def some_view(request): # Create the HttpReormponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = ' filename="somefilename.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.doForm(Form_db_att) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response -
How to force duration display as H:i in django?
I have a duration field which with validations, the maximum is 24 hours. However when 24 hours is displayed it shows as: 1 day, 0:00:00 I want it to show as 24:00 I am currently displaying the DurationField: <td>{{ entry.duration }}</td> -
Http delete method using jQuery ajax on django rest backend fails on Safari, but works in Chrome
I want to use django rest framework as backend and jQuery in the frontend to post and delete. Using $.ajax POST works fine. But delete call fails on Safari but works in Chrome. Here is the sample code: django models.py: from django.db import models class Article(models.Model): title = models.CharField(max_length=250) content = models.TextField() create_date = models.DateTimeField(auto_now_add=True) urls.py: urlpatterns = [ path('api/v1/articles/', views.ArticleList.as_view()), path('api/v1/articles/<int:pk>', views.ArticleItem.as_view()), ] views.py: class ArticleList(generics.ListCreateAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleItem(generics.RetrieveUpdateDestroyAPIView): query set = Articles.objects.all() serializer_class = ArticleSerializer serializer.py class ArticleSerializer(serialisers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content', 'create_date') jQuery: # on delete link $("#talk).on('click', 'a[id^=delete-]', function() { var pk = $(this).attr('id').split('-')[1]; delete_article(pk); }); function delete_article(pk){ $.ajax({ url: "api/v1/articles/"+pk, type: "DELETE", data: { pk: pk }, success: function(son) { $('#post-'+pk).hide(); console.log("delete successful") }, }) }; In Safari 11.0.1, in console it only shows "0: undefined". It is not going into success loop. In Chrome delete function is successful. -
Library, but also a project impacting another
In the moment, I have two github repositories, i.e. repo1 and repo2. Both are two django projects created by our team. In requirements.pipin ~/work_projects/repo1, I have the line -e git+ssh://git@gitlab.com/repo2.git@de5622dcf0b9a084f9b0a34cdd1d932026904370#egg=repo2 Hence, repo2 becomes a library used by repo1 in ~/.virtualenvs/venv/src (repo1's virtual environment). In the moment, I need to modify both repositories at the same time. My main focus in the moment is that each time I modify repo2, I need to test out the results on repo1. I want to look at the impact of repo2 on repo1 once modified. I don't want to push my changes on github and reinstall repo2 on repo1 each time I want to see those changes. How could I make it works easily, workaround?