Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djangotables2 shows bullets near pagenumbers
I am new to django-tables2 and was trying out few things. I followed the django-tables2 tutorial of using data from model directly without creating tables with another dataset. However bullets appear near the page numbers area. How do I remove the bullet points? Screenshot of the bottom of page -
Canonical Urls with django wagtail puput
I made my first blog with puput and wagtail. I´m using the following tag for canonical_urls: <link rel="canonical" href="{% block canonical %}{% canonical_url %}{% endblock canonical %}"/> If I open my website with http, it renders http://www.example.com as canonical. If I open my website with https, it renders https://www.example.com as canonical. If I´m not wrong, google will treat http and https as differents pages. Is it possible to set all canonical urls as https only or it doesn´t matter? -
How to solve the error: "No module named psycopg2" (postgreSQL and Django)?
I am quite new to Django, and this is my first time setting up a Databse. I followed tutorials, and created a virtual environment. In this virtual environment, the package psycopg2 is installed (as you can see in the image below). However, when I use the command "python manage.py migrate", the following error appears: "No module named psycopg2". This is strange, because it seems like psycopg2 is installed, and the right virtual environment is linked with PyCharm. Any guidance would be truly appreciated! -
Django view, using passed argument to dynamically set field to update
New to django and trying to pass an argument as the field to update however I get the error "keywords cant be an expression" Is there a proper method of dynamically setting the field? class UpdateUser(AtomicMixin, CreateModelMixin, GenericAPIView): serializer_class = UserSerializer authentication_classes = () def post(self, request): """User registration view.""" User.objects.filter(id=request.data['userID']).update(request.data['fieldToUpdate']=request.data['value']) return Response("Saved", status=status.HTTP_200_OK) -
New versions of html files not being served
I'm using a combination of nginx, gunicorn and django. All works fine except that new versions of html pages are not being served. The old pages continue to be served. I've tried restarting gunicorn and nginx and rebooting the server. Suggestions? -
Django merge Many-To-Many data
I am building IMDB clone in order to learn Django. I'm facing problem when I'm using Many-To-Many relationship with intermediate table. Here are my models: class Role(models.Model): role = models.CharField(max_length=40) description = models.TextField(null=True, blank=True) class Person(models.Model): first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) birth_date = models.DateField() brief = models.TextField() roles = models.ManyToManyField(Role, through='CrewMembership') class Media(models.Model): name = models.CharField(max_length=255) genres = models.ManyToManyField(Genre) poster = models.ImageField(upload_to='posters/%Y/%m/%d', default='posters/Placeholder.png') cast = models.ManyToManyField(Person, through='CrewMembership') ... class CrewMembership(models.Model): media = models.ForeignKey(Media) member = models.ForeignKey(Person) role = models.ForeignKey(Role) character = models.CharField(max_length=255, null=True, blank=True) And here's my view: def person_detail(request, person_id): person = get_object_or_404(Person, pk=person_id) media_list = CrewMembership.objects.filter(member_id=person_id) return render(request, 'main/person_detail.html', {'person': person, 'media_list': media_list}) I really don't know if the database design is good or not but it seems to work. At the moment I'm building the person detail page and I'm having trouble if one person worked as for example director and writer on the movie. I get 2 different rows because the roles are different. How can I merge the data and show for example Christopher Nolan worked as both director and writer? I have attached my current result -
Django templates folder
I want to create a "templates" folder in my project's root folder When I do this: {% extends "base.html "%} I get a "TemplateDoesNotExist" error. Here is my project structure: Here is the template configuration from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The logs: (Using Django 2.0.dev20170914122638) -
Resize a drop-down menu
I am very new in Django/Python, and I want to create a drop-down menu. It works well, but the size, the appearance are so strange, but I don't know how to fix it View class StatisticsIndexView(StaffRestrictedMixin, TemplateView): template_name = 'loanwolf/statistics/index.html' def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context Model class Statistics(TimeStampedModel): type_choice = models.SmallIntegerField(_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, default=0) def count_nb_loans_per_period(self): pass Form class StatisticsBaseForm(ModelForm): def __init__(self, *args, **kwargs): super(StatisticsBaseForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Statistics fields = '__all__' I think I could fix my problem with from crispy_forms_materialize.layout import ( Layout, Div, Field, Row, Column, HTML, Submit ) but it is unclear. Are there anyone here who could help me with that? Here is a picture of what it looks like Drop-Down menu -
redirect does not redirecting properly in django
I am using django 1.10. This is my sample code. The problem is after calling redirection, the address bar populated with the follow addresses. It should directly redirected to google news. But it does not. How can I solve it? def redirect_url_view(request, *args, **kwargs): // done something url = "www.news.google.com/news" return redirect(url) http://localhost:8000/www.news.google.com.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/news And in the console contains following: "GET /www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/www.news.google.com/news HTTP/1.1" 302 0 Can anybody tell what is the problem!!! -
Use Django Backward Relation to Show Only n Objects
I am currently using Django backward relationships to determine what organizations the logged in user belongs to, and then display leads that belong to this organization. This is how I am accomplishing this in my html template: {% for organization in organization %} <h3>{{ organization.name }}</h3> {% for lead in organization.lead_set.all %} {{ lead.first_name }} {% endfor %} {% endfor %} This however displays all the leads that belong to an organization, is there anyway I can limit the number of leads that show up to say the last 5? Thanks -
Dynamically detecting the text in image and tracing over them
Using Python's Open CV it is possible to detect text and it is also possible to draw lines over Images . So I have task to do like i have to create an application where if a user uploads an image my python code has to detect the text in it and trace them with multiple lines like to create a circuit over it . Please share ideas. Thanks in advance -
Grab only latest object from Q in Django/DRF
queryset = queryset.prefetch_related( Prefetch('drivernote_set', queryset=DriverNote.objects.filter(driver_id__in=queryset).order_by('-date_created') .select_related('owner'), to_attr='notes'), Prefetch('rental_set', queryset=Rental.objects.filter( # Active and reserved rentals Q(state_in=['active', 'reserved'], driver_id_in=queryset) | # Latest returned rental?? Q(state='returned', driver_id_in=queryset)) .select_related('vehicle').select_related('driver'), to_attr='rentals'), ) return queryset Is there any way to grab just the latest object via Q in Django? Let's say I'm trying to pull in all active and reserved rentals, but I only want to pull one rental with state returned (latest)? How would I go about accomplishing that via Q object? Or do I call two queries chain the querysets together? I tried latest() but it does not work. -
Extract field form django model
I have defined the following model: class User(models.Model): userid = models.CharField(max_length=26,unique=True) status = models.CharField(max_length=5) Now I would like to extract the value of my status field for a specific userid that I have saved in my database. I am doing it currently in this way: field = User.objects.filter(userid=id).values('status') Which gives me a Query Set, e.g.: <QuerySet [{'status': 'some status'}]>. However, I am not looking for the Query Set but for the Field string. So I am currently doing a workaround to get the field value: field1 = str(field) field2 = field1.replace("<QuerySet [{'status': '","") field3 = field3.replace("'}]>","") Which returns me: "some status". That is obviously super messy. So what would be the correct way to get the field string "some status" for this example? -
Django to show status of running os command
I am using django to create an app which will take the targets from the text file and then will launch the Nmap scan against the hosts specified. Everything is working fine with the only problem being showing status of the running command on browser's screen.Since I am running the command with os.system(command), I can get the output at terminal from where I have launched the runserver command. But, I am just wondering if there is any way to redirect the output to the web browsers screen. -
ImportError: No module named weather_Core_Engine.weather_DB_Handler
I'm trying to build a project on python using Django on pythinanywhere. I'm not familiar at all with Django so any hints it's more than welcome. I created a Django app called profiles and there i created some db models. so far so good. I'm using sqlite3 and I managed to migrate the db and to correctly start my project. now I have modified the file models.py but while running the migration using the command: "python ./manage.py makemigrations" I have the following issue: "16:11 ~/Mico_Weather_BackTrace $ python ./manage.py makemigrations Traceback (most recent call last): File "./manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 353, in execute self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 310, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res … -
django is adding characters to my URL
When people visit my website, django is sometimes randomly adding characters to my URL. (It happens intermittently) name_of_url.com gets re-routed to something like name_of_url.com/KiRkZ/ name_of_url.com/section gets re-routed to something like name_of_url.com/KiRkZ/section Is there a way to remove these characters? It is causing a 404 error for the visitors it happens to. -
Display latest "commentator" username in forum app [Django]
I am creating a forum app, and want to display latest commentator's username(as seen in screenshot): But I have some gaps in information, here is my code so far: Models class Forum(models.Model): """ Forum Model """ forum_author = models.ForeignKey( Profile, related_name='user_forums', null=True, blank=True, on_delete=models.CASCADE ) forum_title = models.CharField( max_length=225, verbose_name=u'Thread Title', blank=False, null=False ) forum_category = models.ForeignKey( 'Category', verbose_name=u'Thread Category', ) forum_content = MarkdownxField() class Comment(models.Model): """ Comment Model """ forum = models.ForeignKey( 'Forum', related_name='forum_comments' ) comment_author = models.ForeignKey( Profile, related_name='user_comments', null=True, blank=True, on_delete=models.CASCADE ) comment_content = MarkdownxField() created_date = models.DateTimeField( default=datetime.datetime.now, ) Forum list views - display all threads ... from app_forum.models import Forum, Comment def forum_list_view(request): forum_list = Forum.objects.all().order_by("-misc_created") return render(request, 'app_forum/forum_list.html' {'forum_list': forum_list}) My single thread views : def forum_single_view(request, pk): forum = get_object_or_404(Forum, pk=pk) forum_comments = Comment.objects.filter(forum=forum.id) paginator = Paginator(forum_comments, 10) page = request.GET.get('page', 1) try: forum_comments = paginator.page(page) except PageNotAnInteger: forum_comments = paginator.page(1) except EmptyPage: forum_comments = paginator.page(paginator.num_pages) return render(request, 'app_forum/forum_single.html', {'forum': forum, 'forum_comments': forum_comments}) -
Flake8 check on lowercase function will skip some inherited function
I use flake8 as code violation check, but I find a strange thing about the lowercase function name check. The function name like setUp won't be reported, I guess it may be the reason of this function is inherited from django TestCase class. from django.contrib.auth.models import User from django.test import TestCase class BaseTestCase(TestCase): def setUp(self): self.admin = User.objects.create_superuser( 'admin-user-name', 'admin_email@test.com', 'password') def loginNormalUser(self): self.client.login(username='neo', password='fake_password') Because the other function with the name loginNormalUser in the CamelCase, flake8 report this function. $ flake8 helpers.py helpers.py:10:9: N802 function name should be lowercase There is a related issue about the lowercase check here: flake8 doesn't report mixed-case function names, so I already install pep8-naming. -
Django forms won't render (No reverse match)
I'm trying to make a form with Django 1.10 to create a comment on a Task object. When I want to open the form, there is no field and when I try to submit, I got this error : NoReverseMatch at /tasks/29/comment/ Reverse for 'create_comment' with arguments '('',)' not found. 1 pattern(s) tried: [u'tasks/(?P[0-9]+)/comment/$'] How can I render my form on my template, and return to my "detail" view after submit ? forms.py class CreateCommentForm(forms.Form): commentary = forms.CharField(label='Commentary', widget=forms.Textarea, required=True) models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.ForeignKey(Task, on_delete=models.CASCADE) commentary = models.TextField(blank=True, max_length=5000) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.commentary views.py class CommentCreateView(SuperuserRequiredMixin, FormView): template_name = 'tasks/create_comment_modal.html' form_class = CreateCommentForm def form_valid(self, form): user = self.request.user task = Task.objects.get(id=self.kwargs['pk']) commentary = form.cleaned_data['commentary'] comment = Comment(user=user, task=task, commentary=commentary) comment.save() return HttpResponseRedirect(reverse('tasks:detail', kwargs={'pk': task.id})) urls.py url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/comment/$', views.CommentCreateView.as_view(), name='create_comment'), create_comment_modal.html {% load widget_tweaks %} <form role="form" id="comment-create-form" name="comment-create-form" method="post" action="{% url 'tasks:create_comment' task.id %}"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Add comment in task #{{ task.id }} - {{ task.title }}</h4> </div> <div class="modal-body"> {% csrf_token %} <div class="row"> <div class="col-lg-12"> <div class="form-group"> <label class="control-label" for="{{ form.commentary.id_for_label }}">Commentary</label> {% render_field form.commentary class+="form-control" %} </div> </div> </div> <div … -
Python MySQL Parameterized Queries with date
I have a sql query used in django where a parameter is a date: query="select DT_ORA_INSERIMENTO from richieste where DT_ORA_INSERIMENTO=%s", datestart but in this manner I receive the error: not enough arguments for format string it seems django don't substitute the value of the variable with his value (2017-09-02 00:00:00).. what is wrong? -
Django DRF append BASE_PATH in front of a serializer field
I currently have a serializer as follows: class UserProductsSerializer(serializers.ModelSerializer): user_name = serializers.SlugRelatedField(source='user_id', read_only=True, slug_field='name') class Meta: model = UserProducts fields = '__all__' and the model: class UserProducts(models.Model): user_id = models.ForeignKey('User', db_column='user_id', related_name='user_name') product_id = models.ForeignKey('Products', db_column='product_id', related_name='user_products') category_id = models.ForeignKey('categories', db_column='category_id', related_name='user_products') image = models.CharField(max_length=255, blank=True, null=True) notice the image field above. I have strings of filenames stored in my s3 bucket like - upload.jpg I would want to me able to append my s3 URL to this field, something like http://<my_s3_url>/upload.jpg. Where should I be doing this - in the serializer or in the view? And how can I achieve this -
Drop-down menu with crispy-forms
I am a new programmer with Django/Python, and I need a bit of help with crispy-forms to create a pull down menu. Some people add formlayout.py and forms.py to their app, but I don't know if it is related? The following images represent what I want to do now, but with 'Type' instead of 'Gender' Image #1 and Image #2 How could create a pull down menu with crispy-forms? What files do I have to add to my Django app? What library do I have to use in python? Why inserting a forms.py and formlayout.py in the app? How the forms.py interact with the template view? An example could be highly appreciated. -
DRF PUT Partial Update returning Not Found
I'm trying to get to grips with Django and DRF but having some trouble. I would like to make a PUT request to make a partial update on a record. I currently have the following parts - From models.py class MyUser(models.Model): # Link to User model instance. user = models.OneToOneField(User) first_name = models.CharField(max_length=32, null=True, blank=True) lastname = models.CharField(max_length=32, null=True, blank=True) joindate = models.DateTimeField(null=False, blank=False) def __str__(self): return self.user.username From api/views.py class MyUserDetailUpdateView(GenericAPIView, UpdateModelMixin): queryset = MyUser.objects.all() serializer_class = MyUserPartialUpdateSerializer lookup_field = 'user' def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) From api/serializers.py class MyUserPartialUpdateSerializer(serializers.ModelSerializer): class Meta: model = MyUser From urls.py url(r'^api/userupdate/(?P<user>[\w]+)/$', apiviews.MyUserDetailUpdateView.as_view(), name='my_user_detail_view_api') For testing I used httpie and try - http -v PUT http://127.0.0.1:8000/api/userupdate/johndoe/ first_name="Johnny" The server side is reporting a "Not Found: /api/userdate/johndoe/" and returns a HTTP 404 to the client. What am I missing to do a partial update? Thanks -
Django static assets reference in Jinja Templates
I have a Jinja macro defined as follows. globalmacros.html {% macro SUINavMenu(leftlist=[],logo="images/Logo_WEB_450_250.png") %} <div class="ui pointing secondary menu"> <div class="item"> <img src="{{ static({{ logo }}) }}"> </div> {% for item in leftlist %} <a class="item" href="{{ item[1] }}"> {{ item[0] }} </a> {% endfor %} </div> {% endmacro %} dashboard.html {% from "macros/globalmacros.html" import SUINavMenu %} {% block navigation %} {{ SUINavenu(leftlist=[["Home","/home/"],["New Bill","/newbill/"]], logo="images/web_logo.png") }} {% endblock navigation %} I am importing the macro defined in "globalmacros.html" into "dashboard.html" and trying to pass the logo location. However I am not sure how to do it. In a non-macro version, the following code works. <img src=" {{ static('images/logo_web.png') }} "></img> The above code in "globalmacros.html" doesnt work as Jinja does not process an {{}} inside another {{}} What is the work around for this? -
Django JWT-Auth also i have login API. Can i generate token on login and send to the front-end?
I am using 'rest_framework_jwt.authentication' and also i have Login API, if i am generating token over default auth-token API then what is the use of Login API? so can i generate token while executing login API and if its success then send back generated token to the front-end. urls.py url(r'^login/$', views.UserLoginAPIView.as_view(), name='login'), url(r'^api/auth/token/', obtain_jwt_token), serializers.py class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read_only= True) email = EmailField(label='Email Address', allow_blank= True) class Meta: model = User fields = [ 'email', 'password', 'token' ] extra_kwargs = {"password": {"write_only": True} } def validate(self, data): user_obj = None email = data.get("email", None) password = data["password"] if not email: raise ValidationError('A username or email is required to login') user = User.objects.filter( Q(email=email) ).distinct() if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("this email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("incorrect creadeintial try again") data["token"] = "SOME BLANK TOKEN" return data view.py class UserLoginAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)