Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Highlighting individual bootstrap column
I'm making a django website, where I have to change the color of text and make a box appear when hovering over their bootstrap column. The problem I'm having is trying to individually refer to the column to only highlight that column and not another. The code: $(document).ready(function(){ $('.col-sm-2').hover(function(){ if($(this).attr('id')==$('.col-sm-2').children('.box').children('img').attr('alt')) { $(this).children('.box').css('border', '1px solid #aeaeae'); $(this).children('.box').css('padding', '0px'); $(this).children('.carinf').children('a').css('color', '#012190'); } }, function(){ $('.box').css('border', '0px'); $('.box').css('padding', '1px'); $('.shoeinf').children('a').css('color', 'black'); }); }); .box { border-radius: 18px; font-size: 150%; padding: 1px; display: inline-block; box-sizing: border-box; height: auto; max-width: 100%; float: center; } .carinf { white-space: nowrap; text-align: center; text-overflow: string; max-width: 100%; position: relative; } .box:hover { padding: 0px; border: 1px solid #aeaeae; } img { position: relative; display: block; margin-left: auto; margin-right: auto; padding: 2%; } a { color: black; text-decoration: none; } a:hover { text-decoration: none; color: #012190; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div class="container"> {% for k in latest_kickz %} {% if forloop.first %}<div class="row">{% endif %} {% sub 'market/images/{0}/{1}/{2}.png' k.manufacturer|slugify k.model|slugify k.colour|slugify as sub1 %} <div class="col-sm-2" id="{{ k.colour }} , {{ k.model }} , {{ k.manufacturer }}"> <a href="{% url 'market:detail' k.id %}"> <div class="box" > <img src="{% static sub1 %}" alt="{{ … -
Bootstrap, nav-stacked not actually stacking list entries
it seems i'm missing something obvious here i expected the HOME BLOG CONTACT entries to be stacked on top of one another at all times. what am i missing? <body class="body" style="background-color:#f6f6f6"> <div class="container-fluid" style="min-height:95%; "> <hr> <div class="row"> <div class="col-sm-2"> <br> <br> <!-- Great, til you resize. --> <!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#fff">--> <div class="well bs-sidebar" id="sidebar" style="background-color:#fff"> <ul class="nav nav-pills nav-stacked"> <li role="presentation" class="active"><a href='/'>Home</a></li> <li role="presentation"><a href='/blog/'>Blog</a></li> <li role="presentation"><a href='/contact/'>Contact</a></li> </ul> </div> <!--well bs-sidebar affix--> </div> <!--col-sm-2--> <div class="col-sm-10"> <div class='container-fluid'> <br><br> {% block content %} {% endblock %} </div> </div> </div> </div> <footer> <div class="container-fluid" style='margin-left:15px'> <p><a href="#" target="blank">Contact</a> | <a href="#" target="blank">LinkedIn</a> | <a href="#" target="blank">Twitter</a> | <a href="#" target="blank">Google+</a></p> </div> </footer> </body> -
nodejs high modular project with django architecture
I want to start a big web application. this application need to respect this constraint: use NoSQL database Hight modularity easy to use i can't use django because is not officialy support NoSQL backend. But django offert a big modularity approach. Now i decided to use NodeJS for two reason: support NoSQL backend easy to use but i don't wont to start from scratch and i want to save django modularity advantages. I see express is most used but express is too simple. someone can recommend me how to build a hight modular project with express or a nodejs web framework that can use modular django architecture ? -
docker-compose cannot start service: "exec: \"python3\": executable file not found
(I'm not deeply experienced with docker, fwiw) I have a django appication I'm containerizing. Currently when I run docker-compose up the redis service starts up, but apiexits with error: ERROR: for api Cannot start service api: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \"python3\": executable file not found in $PATH": unknown #docker-compose.yaml version: '3' services: redis: image: redis ports: - 6379 api: build: context: ../backend/ dockerfile: ../backend/Dockerfile env_file: .env volumes: - ../backend:/code/ ports: - "8001:8001" depends_on: - redis with #../backend/Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code ADD . /code/ WORKDIR /code/ RUN pip install -r requirements.txt CMD python manage.py runserver and #./.env DJANGO_SETTINGS_MODULE=backend.settings.dev DJANGO_SECRET_KEY=<redacted> SENTRY_URL=<redacted> I've also, based on other issues, tried using both CMD and RUN with their differing argument types, i.e. in the existing shell and without, but the output hasn't changed. I should also acknowledge that it's possible I'm not restarting actually catching the updates to docker-compose.yaml or Dockerfile. My workflow has been $ docker-compose down followed by $ docker-compose up. -
In Django, how to display a date widget in the HTML form for a model DateField?
I am new to Django and looking to do something simple. I have a date database field and I am trying to get Django to display it as a 'date' widget in the HTML forms. Following is my code: models.py from django.db import models class DateF(models.Model): edate = models.DateField() forms.py from django.forms import ModelForm from django import forms from .models import DateF class DateForm(forms.ModelForm): class Meta: model = DateF fields = ['edate'] views.py from django.shortcuts import render from .forms import DateForm def index(request): if request.method == 'POST': pass else: form = DateForm() return render(request, 'datef/index.html',{'form':form}) Template file <!DOCTYPE html> <html> <head> <title>Date field test</title> </head> <body> <div style="width: 600px;margin: auto;"> <h2>Date field</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} </form> </div> </body> </html> The above displayed a text input field. I tried the following in my forms.py based on the following and still could not get it to work. https://stackoverflow.com/questions/660929/how-do-you-change-the-default-widget-for-all-django-date-fields-in-a-modelform from django.forms import ModelForm from django import forms from .models import DateF from django.forms import fields as formfields from django.contrib.admin import widgets class DateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(DateForm, self).__init__(*args, **kwargs) self.fields['edate'].widget = widgets.AdminDateWidget() class Meta: model = DateF fields = ['edate'] What am I missing? Do I need … -
django-oauth-toolkit 'invalid client' error after deploy on AWS Elasticbeanstalk
I use django-oauth-toolkit with my django/django-rest-framework application. When I request an access token in dev mode on localhost, it works OK: dev@devComp:$ curl -X POST -d "grant_type=password&username= <user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ {"access_token": "fFySxhVjOroIJkD0IuEXr5WIhwdXg6", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups", "refresh_token": "14vhyaCZbdLtu7sq8gTcFpm3ro9YxH"} But if I request an access token from absolutely the same application deployed at AWS Elasticbeanstalk, I get 'invalid client' error: dev@devComp:$ curl -X POST -d "grant_type=password&username= <user_name>&password=<password>" -u"<client_id>:<client_secret>" http://my-eb-prefix.us-west-1.elasticbeanstalk.com/o/token/ {"error": "invalid_client"} Please advise me what to do to get rid of this error and normally request access tokens from django app deployed at AWS. -
Weird behavior with external class in django
I've got a weird problem here. It hurts my brain thinking about it. I've got a Django project with multiple apps. Today I added another app. (views.py) from %app_name%.%class_file% import %class_name% def api(request): t = %class_name%() data = {} data['listOtherDevices'] = t.listOtherDevices logger = logging.getLogger(__name__) logger.error(len(t.listOtherDevices)) return JsonResponse(data) The imported class fills the 'listOtherDevices'-array via __init__ perfectly fine when I run it inside a console. When I do so, there are exactly 3 elements inside this array (as there are 3 devices in my LAN the class could find). So when I visit the url (development server -> manage.py runserver) linked to this method I can see a JSON with exactly 3 entries. So far so good but now comes the weird part. When I refresh the url in my browser or visit it one more time, there are more than 3 entries. The scheme is like this: opened url 1 time: 3 entries opened url 2 times: 9 entries (+ 6) opened url 3 times: 18 entries (+ 9) opened url 4 times: 30 entries (+ 12) opened url 5 times: 45 entries (+ 15) opened url 6 times: 63 entries (+ 18) I can see a pattern there … -
Django template: 2 for loops with same iterable seems to be interfering with each other
So I have 2 for loops in an HTML template, back to back that are both using the same iterable like so: {% for counter in iSM %} #some code here {% empty %} <p>There's a missing tab here.</p> {% endfor %} </div> {% for iteration in iSM %} #some code here {% endif %} {% empty %} <p>There's a missing context here.</p> {% endfor %} The issue I have with this is it seems that the counter doesn't reset. The first for loop will operate as normal, no problem. The second for loop will trigger the empty. Switching the order of these for loops will work for whatever loop is on top. How do I go around having both loops return all elements of the view the same? -
Is there any way to add through to M2M field with keeping the related manager's .add() working?
While Django doesn't completely support adding the through attribute to a M2M field (in order to add some extra fields), it can be migrated. The main issue is, Django will complain when any code tries to .add() models to the related set even if there are no required fields in the through model outside of the FKs of the linked models. So, I want to add a nullable field to the through model and still keep .add() and remove working like it was before (and implicitely using None as the nullable field value). Adding auto_created=True in the meta almost works, but it breaks migrations amongst other things. Is there any way to make it work outside of overriding the many2many descriptor (which isn't exactly included in the public API, though a lot of third-party Django packages use it)? -
Django Widget Tweaks help text as placeholder
Is there any way to render help text as placeholder in Django Widget Tweaks. New to django widget tweaks. -
how to implement django-crispy-forms tags in Jinja2
i recently switched from using django templates to using Jinja2. how can i be able to use the {% crispy %} tags with Jinja2 templates? I am not too proficient with programming in python yet -
Retrieve and update multiple models at once in Django
I'm new to django and im currently using version 1.8 but I have two models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) holder = models.ForeignKey('Person', related_name='book_holder', on_delete=models.PROTECT, null=True, blank=True) call_id = models.CharField(blank=True, max_length=10) checking_out = models.BooleanField(default=False) available = models.BooleanField(default=True) ... class Person(models.Model): ... books_allowed = models.PositiveSmallIntegerField() books_out = models.PositiveSmallIntegerField(default=0, blank=True) day_limit = models.PositiveSmallIntegerField() ... I am going to be having a checkout page that displays a persons name and has input fields depending on the number of books they are allowed to have and the number of books they already have out so if person A can only check out 6 books and he already has 2 books to his name, there will be 4 fields but not all 4 fields have to be filled out because person A might only check out 2 books or 1 or etc. What I am having a hard time figuring out is how can I create the form, would I use model forms or is there another way to build a form that does not require all fields filled because keep in mind person X doesn't have to check out his max amount of books allowed all at once. Once I do … -
Django pgettext doesn't create context
in my Django (2.0.2) running in Python 3.6.3 I've created some Models as usual. To be able to work with the admin panel in the user's language, I've set the model's and model field's verbose_names to _('context','verbose_name') where _ aliases to pgettext_lazy. When running "makemessages -l de" it creates the django.po file as expected, containing all my strings. Different from my expectations, the blocks look like #: app/models.py:123 msgid "context" msgstr "" instead of #: app/models.py:123 msgctxt "context" msgid "verbose_name" msgst "" What could I possibly do wrong? All strings translated with gettext_lazy work fine. -
Which is better for production? Flask-Restful+SqlAlchemy vs Django-Rest
I have few months experience in Python Backend and am comfortable with Flask-Restful. I am creating a production app which is going to have a few thousand users. Should I go with Django-rest because it is prepackaged or stick with Flask-Restful with SQLAlchemy? -
Where to write AWS signing code
I'm trying to validate my AWS keys for S3 storage for my Django project. So I've found this tutorial from the offical site. It shows various Python code but it doesn't say where to write it? What file do I put this code in? -
Django group by one column but display multiple
I have 40 results of posts in Django. POST: id, title, website_id WEBSITE: id, name And these posts belong to 7 websites. I would like to group by website_id so only 1 post will be displayed per a website. I've tried this: post_list.values('website_id').annotate(Count('website_id')) or post_list.values('id', 'title').values('website_id').annotate(Count('website_id')) It will display 7 results, but only 2 columns: "website_id" and "website_id__count" I would like to display also other columns: post.id, post.title, post.website_id. I've tried different configurations, such as: post_list.values('id', 'title', 'website_id').annotate(Count('website_id')) Now, it displays all columns, but 40 results instead of 7, because it groups by post.id instead of post.website_id. Do you know how to display all columns but only 7 results, instead of 40? Thanks. -
How do I create pagination and search based on related models?
So based on the view below, that is working perfectly, I also want to change it that I can create pagination and search also for courses that belong to a specific faculty. Models hierarchy is this: faculties > departments > studies > courses. @login_required def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'courses2': Course.objects.all(), 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) -
UNIQUE constraint failed: auth_profile.user_id Django Allauth
I have a create_or_update_user_profile methods to the User model, whenever a save event occurs, but I added a new method set_initial_user_names to save a url, then now it shows me an error IntegrityError at /accounts/social/signup/ UNIQUE constraint failed: auth_profile.user_id class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=170, blank=True) avatar_url = models.CharField(max_length=256, blank=True) facebook_url = models.CharField(max_length=40, blank=True) twitter_url = models.CharField(max_length=40, blank=True) instagram_url = models.CharField(max_length=40, blank=True) web_url = models.CharField(max_length=40, blank=True) class Meta(): db_table = 'auth_profile' def __str__(self): return self.user.username @receiver(user_signed_up) def set_initial_user_names(request, user, sociallogin=None, **kwargs): preferred_avatar_size_pixels = 256 picture_url = "http://www.gravatar.com/avatar/{0}?s={1}".format( hashlib.md5(user.email.encode('UTF-8')).hexdigest(), preferred_avatar_size_pixels ) if sociallogin: if sociallogin.account.provider == 'twitter': name = sociallogin.account.extra_data['name'] user.first_name = name.split()[0] user.last_name = name.split()[1] if sociallogin.account.provider == 'facebook': user.first_name = sociallogin.account.extra_data['first_name'] user.last_name = sociallogin.account.extra_data['last_name'] picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format( sociallogin.account.uid, preferred_avatar_size_pixels) if sociallogin.account.provider == 'google': user.first_name = sociallogin.account.extra_data['given_name'] user.last_name = sociallogin.account.extra_data['family_name'] picture_url = sociallogin.account.extra_data['picture'] profile = UserProfile(user=user, avatar_url=picture_url) profile.save() @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.userprofile.save() IntegrityError at /accounts/social/signup/ UNIQUE constraint failed: auth_profile.user_id -
How to romove models in django 1.11?
I started learning django recently. I just created a music app in my project. I added a album colum in models.py. At first I set that to null=True. But later I removed that. After couple of times when I tried to make migration it shows an error like below. I tried by deleting that attribute but than another attribute 'artist' shows same problem. I can't understand why? And how to fix that? **You are trying to add a non-nullable field 'album' to song without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py** -
How do I add a link to a Custom Boolean Field and pass parameters using Django_Tables2
So I've been having lots of fun with Django_Tables2 and I have it all working really nicely which is great. My table renders with a series of columns from my database which are booleans. These are columns such as 'Completed' etc. Instead of having True and False I have created a custom definition for my boolean fields which renders glyphicons-ok and glyphicons-remove as appropriate. See code below class BootstrapBooleanColumn(BooleanColumn): def __init__(self, null=False, **kwargs): if null: kwargs["empty_values"]=() super(BooleanColumn, self).__init__(**kwargs) def render(self, value): value = bool(value) html = "<span %s></span>" class_name = "glyphicon glyphicon-remove" if value: class_name = "glyphicon glyphicon-ok" attrs={'class': class_name} attrs.update(self.attrs.get('span', {})) return mark_safe(html % (AttributeDict(attrs).as_html())) My columns are therefore coded accordingly as follows: completed = BootstrapBooleanColumn(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Completed'}}) However now I'd like to be able to click on one of the icons and have it toggle and update my database accordingly (ie switch from False to True and vice versa.) but I can't seem to be able to pass the parameters and I'm getting myself into a knot. I tried wrapping the in an anchor def render(self, value): value = bool(value) html = "<a href='/tasks/toggle/3'><span %s></span></a>" which triggers my url with a hard coded id of '3' but I … -
API endpoint as a django model
I want an API endpoint to be linked to a model that supports relationships. For example, if I have an endpoint http://api-url/users which gives all users, I want to create a model 'Order' with a field 'user' which is a ForiegnKey to a User model linked to the API. -
Attributes in django form model
hi i have django form model and i to want add my custom class for it but still i getting error: TypeError: init() got an unexpected keyword argument 'attrs' My django code: class ContactForm(forms.ModelForm): class Meta: model = ContactFormModel fields = ('name', 'email', 'phoneNumber', 'message',) widgets = { 'name': CharField(attrs={'class': 'myfieldclass'}), } Thanks for your helps. -
Django Model Form clean method not being called
I have used a Django model form to create HackathonTeam instances. The issue I am facing here is that custom clean method that I have used is not being called. All the other default validations are happening correctly. # models.py class HackathonTeam(models.Model): name = models.CharField(max_length=30) leader = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='leader_teams') hackathon = models.ForeignKey(Hackathon, on_delete=models.CASCADE, related_name='hack_teams') vacancies = models.PositiveIntegerField(default=0) current_members = models.ManyToManyField(CustomUser, related_name='member_teams') skills_required = models.ManyToManyField(Skill, related_name='hack_requirements') cutoff_date = models.DateTimeField(null=True, blank=True) # Someone may not wish to have a cut-off date closed = models.BooleanField(default=False) # forms.py ######## class HackathonTeamForm(forms.ModelForm): class Meta: model = HackathonTeam exclude = ['leader', 'current_members', 'closed'] def clean(self): print("Inside clean") cleaned_data = super(HackathonTeamForm, self).clean() print(cleaned_data) if HackathonTeam.objects.filter(hackathon=cleaned_data.get("hackathon"), name=cleaned_data.get("name")).exists(): print(1) raise forms.ValidationError("A team with the same name already exists.") return cleaned_data # views.py ######### @login_required(login_url='users:login') def add_hackathon_team(request): if request.method == 'POST': form = HackathonTeamForm(request.POST) if form.is_valid(): cd = form.clean() print(cd) print("Data is valid") # form.save() team = form.save(commit=False) team.leader = request.user team.save() return redirect('users:view_hackathon_team', pk=team.id) else: form = HackathonTeamForm() return render(request, 'users/add_hackathon_team.html', {'form': form}) The print statement in the view is being printed and new Teams are created as well. The only issue is that the clean method is not called and duplicate Teams can be created as well. -
How to upgrade to Django 2.0
I've been traying to upgrade my django versión and I've coudnt. xxx@yyyyyy:~# python Python 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (1, 11, 10, u'final', 0) xxxx@yyyyyyy:~# pip install -U Django The directory '/home/user/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/user/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Requirement already up-to-date: Django in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from Django) xxxx@yyyyyy:~# pip --no-cache-dir install -U Django Requirement already up-to-date: Django in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from Django) How it coud be up-to-date my django version if enter code hereit is not 2.0 it is (1, 11, 10, u'final', 0) And If I do an ls -s to know the files owners: xxxx@yyyyyyy:~# ls -s /home/gechichure/.cache/pip … -
Django queryset ProgrammingError: column does not exist
I'm facing a big issue with django. I'm trying to save object containing foreignKeys and 'ManyToMany` but i always get this error ProgrammingError: column [columnName] does not exist I've made serveral times all migrations but it doesn't works. I have no problem when i work with models that does not contain foreign keys. I have tried to delete the migration folder. It's seems my database doesn't want to update fields. I need to force it to create these column but i don't have any idea. class Post(models.Model): post_id = models.CharField(max_length=100,default="") title = models.CharField(max_length=100,default="") content = models.TextField(default="") author = models.ForeignKey(Users, default=None, on_delete=models.CASCADE) comments = models.ManyToManyField(Replies) numberComments = models.IntegerField(default=0) date = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(null=True) def __str__(self): return self.post_id when i'm trying to retrieve this i have : ProgrammingError: column numberComments does not exist As i said before i made makemigrations and migrate, i even deleted the migration folder. Any idea ?