Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save all migrations in container docker 'PostgreSQL database' in with Django
I'm new with Django and PostgreSQL together with Docker, and I don't know how to use or configure postgresql/python containers to than each migration maked are saved in my postgresql database. I have this docker-compose.yml: version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres And this is my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code And my settings.py if my project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } So, when I make python manage.py migrate, it create a db.sqlite file and not to my postsql container. I tried login inside python container with docker exec -it "id container" bash and make python manage.py migration but it still saving the information in db.sqlite3. NetworkSettings of my container postgreSQL obtained with docker inspect "id container": "Ports": { "5432/tcp": null } "Gateway": "172.20.0.1", "IPAddress": "172.20.0.2", Database exists: postgres=# \l postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 | template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres + | | | … -
django mysql get error > TypeError: 'NoneType' object is not callable
I have same issue when i run : python manage.py runserver help me :( Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/nguyenphuc/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() ... ... File "/home/nguyenphuc/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 96, in __init__ self.client = self.client_class(self) TypeError: 'NoneType' object is not callable -
Django admin site seems to ignore custom UserCreationForm
I have a Django project Project, in which I am trying to include custom user information with a UserProfile model. I have created a custom StackedInline, UserCreationForm, and UserAdmin to add this information when a user is created, but the form in the Django admin site appears unaffected. # Commons/admin.py class ProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'Profile' fk_name = 'user' class UserProfileCreationForm(UserCreationForm): phone = forms.RegexField( regex=r'^\+?1?\d{9,15}$', error_messages={'invalid': "Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."}, required=True ) phone2 = forms.RegexField( regex=r'^\+?1?\d{9,15}$', error_messages={'invalid': "Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."}, required=False ) address = forms.CharField() class Meta: model = User fields = '__all__' def save(self, commit=True): if not commit: raise NotImplementedError("Can't create User and UserProfile without database save") user = super(UserProfileCreationForm, self).save(commit=True) user_profile = UserProfile( user=user, phone=self.cleaned_data['phone'], phone2=self.cleaned_data['phone2'], address=self.cleaned_data['address'] ) user_profile.save() return user, user_profile class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) add_form = UserProfileCreationForm add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'password1', 'password2', 'phone', 'phone2', 'address') }), ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) I have the Commons app registered in INSTALLED_APPS, is … -
Can't create new project with django " Fatal error in launcher: Unable to create process using '"' "
When I try to create a new project on django from cmd I try this: C:\Users\jandr>cd C:\Users\jandr\Documents\projects C:\Users\jandr\Documents\projects>django-admin startproject mysite that is the input showed in the official django tutorial, but the output is this: Fatal error in launcher: Unable to create process using '"' I have searched for the answer for quite long and have not found it, hope this is not a reply. -
Python For loop not working
I'm having problems with my for loop in my django application. I'm trying to get it to show other users that have logged under "Users who could be friends" But nothing is showing. I'm sure my app will work once I get this fixed. I'm not sure if its my views but I am at a lose as to what I should do about this problem template <!DOCTYPE html> <html> <head> <a href="/logout">Logout</a> <form action="/success" method="GET"> {% csrf_token %} <h1>Welcome! {{request.session.name}}</h1> <h2>Here is a list of your friends!</h2> </head> <body> <table> <thead> <th>Name</th> <th>Action</th> </thead> <tbody> <tr> {%for friends in friend%} <td><a href="show/{{friends.id}}">View Profile</a></td> <td><a href="remove/{{friends.id}}">Remove Friend</a></td> {%endfor%} </tr> </tbody> </table> </body> <footer> <p>Other People who coudl be friends</p> <table> <thead> <th>Name</th> <th>Action</th> </thead> <tbody> <tr> {%for friends in extra%} <td><a href="show/{{friends.id}}"></a></td> <td><a href="join/{{friends.id}}">Add a Friend</a></td> {%endfor%} </tr> </form> </tbody> </table> </footer> Views: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect from .models import User from .models import Friend from django.contrib import messages import bcrypt # Create your views here. def index(request): return render(request,'index.html') def register(request): errors = User.objects.validate(request.POST) #print 'this process works', request.POST if len(errors) > 0: for error in errors: messages.error(request, error) … -
Django Rest API pagination populate same entry in several page
I created an API with pagination function in it, Its sort of working, but the only weird thing is let say i declared only 10 entry will be display in 1 page, for several pages (e.g: 1-3) it populate the same entry but when I click to the 4th page, it populate the next 10 entry and then same thing happen until I click to the 8th page, it populate the other 10 entry, can anyone tell me why this bug is happening. Heres my API : class ModelAFilterAPI(APIView): def get(self, request, project_id, search_type="", format=None): print(search_type) search_type_list_split = search_type.split('_') search_type_list = list(map(int, search_type_list_split)) model_object = ModelA.objects.filter(project=project_id, id__in=search_type_list) paginator = Paginator(model_object, 10) page = request.GET.get('page') try: model_object = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. model_object = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. model_object = paginator.page(paginator.num_pages) serializer = ModelASerializer(model_object, many=True) return Response(serializer.data) -
Django Social Auth Pipeline-- Checking for Duplicate Emails
So i'm piggybacking on this post here: Python Social Auth duplicating e-mails for different users Here's my issue: I provide a user with ability to signup either via regular email sign up, facebook auth or twitter auth. I'm also using same package Social Django Auth App for the user login pages. I realized that a user might try sign up with a Facebook account (associated to one email) and then try again later to register with Twitter (which could have the same email address). Based on the aforementioned post, I added a function to check for duplicate emails like so: def check_email_exists(request, backend, details, uid, user=None, *args, **kwargs): email = details.get('email', '') provider = backend.name # check if social user exists to allow logging in (not sure if this is necessary) social = backend.strategy.storage.user.get_social_auth(provider, uid) # check if given email is in use count = User.objects.filter(username=email).count() success_message = messages.success(request, 'Sorry User With That Email Already Exists') # user is not logged in, social profile with given uid doesn't exist # and email is in use if not user and not social and count: return HttpResponseRedirect(reverse('accounts:sign_up', success_message)) and my pipeline with the function: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', … -
Django - conditional mandatory fields
I have a Django form to capture Username/Password and a Sign-In button. Clearly I need Username/Password to be mandatory. I also want to have a Register button on the same form, where the Username/Password fields can't be mandatory. How do I validate the form in a way that is dependent on the button that has been pressed. Normally Validation is done on the forms clean method, but the clean method has no access to the selected button - just the entered fields. -
Tell Django not to save a model field
I want to tell Django not to save my image model field. Here's my view call: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) #if something: #don't save instance.image else: form_post = PostForm() context = { 'form_post': form_post, } return render(request, 'post/post.html', context) else: return HttpResponseRedirect("/accounts/signup/") How can I achieve this? -
Django: join string on a ManyToManyField
I am trying to make a template filter to show who liked a post. Each comment contains a ManyToManyField with the users who upvoted a post. I am trying to use the join method to simplify my code instead of using a for loop. This does not work and I get the error ManyToManyField is not iterable. #post.html ... <span class="tooltip_text">{{ comment.user_upvotes.all|format_upvote_users }}</span> ... #template_filters.py @register.filter def format_upvote_users(queryset): # This works: upvoters = '' for user in queryset: upvoters += ', ' + user # This doesn't: upvoters = ','.join(user in queryset) ... return upvoters -
Including Leaflet.js in a Django template
I am writing a Django app that displays properties of certain objects that have latitute and longitude associated with them. When someone clicks on an object name, I'd like to be able to show them the map of where the objects is. I tried including leaflet.js's map directly into my object detailed view's template like this: {% extends "base_generic.html" %} <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin=""/> {% block content %} <div id="mapid" style="width: 10px; height: 10px;"></div> <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js" integrity="sha512/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw==" crossorigin=""></script> <script> var mymap = L.map('mapid').setView([51.505, -0.09], 13); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 18, id: 'mapbox.streets', accessToken: '<my-token-here>' }).addTo(mymap); </script> {% endblock %} But this gives me the weirdest looking map - it's split into several pieces and I seem to be able to move it freely around the web page into random spots (see below and scroll all the way down, you'll see the break in the middle). Can anyone tell why? -
Modifying the Default Django Login Page
I have a Django project that requires authentication, and the django.contrib.auth code has been working great so far. However, I'd like to edit the provided login page to say something like "MyProject administration" instead of "Django administration", and alter the colors in the CSS files a little bit. I'm having trouble finding where these files are located in the project. Is there a way to edit the default files, or do I have to copy/rewrite all the functionality in my own files? I'd love to just tweak the defaults, if that's possible. -
How to filter all objects that contain multiple elements in a many-to-many relationship using Django's ORM?
I have two classes in Django linked through a ManyToManyField (the User class is the built-in User model): from django.contrib.auth.models import User class Activity(): participants = models.ManyToManyField(User, related_name='activity_participants') I want to find all the activities in which two users are simultaneously participating. I managed to solve my problem using a raw query (my app name is "core", therefore the "core" prefix in the table names): SELECT ca.id FROM core_activity_participants AS cap, core_activity AS ca INNER JOIN core_activity_participants AS cap2 ON cap.activity_id WHERE cap.user_id == 1 AND cap2.user_id == 2 AND cap.activity_id == cap2.activity_id AND ca.id == cap.activity_id However, if possible, I'd like to avoid using raw queries, since it breaks uniformity from the rest of my app. How could I make this query, or one equivalent to it, using Django's ORM? -
Django AJAX Search simplification/show all on page load
I have made a successful AJAX search box, but being fairly new, I was wondering if there was a better way to write this code. I am using Python 3.6 and Django 2. Also, I want to display all entries on page load, which currently displays nothing. If I enter text and delete it, then all my entries show, but not on initial load. Thanks! views.py def search_ajax(request): if request.method == 'POST': search_text = request.POST['search_text'] if ',' in search_text: last,first = search_text.split(",") name_search = PhoneBook.objects.filter(last_name__istartswith=last.strip() ).filter(first_name__istartswith=first.strip()) else: name_search = PhoneBook.objects.filter(last_name__istartswith=search_text.strip()) phone_search = search = PhoneBook.objects.filter(number__icontains=search_text.strip()) if search_text != "": search = list(chain(name_search, phone_search))[:10] else: search = list(chain(name_search, phone_search)) print(search) context={'search':search,} html = render_to_string('search_ajax_results.html', context) return HttpResponse(html, content_type="application/json") ajax_script.js $(function(){ $('#search_ajax_input').keyup(function(){ $.ajax({ type:"POST", url:"search-ajax/", data:{ 'search_text': $('#search_ajax_input').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus,jqXHR) { $('#search-ajax-results').html(data); }; -
Javascript doesn't refresh in Django loop
I have a Django template (html), and a javascript in it that I want to loop for various pair values. It doesn't loop. Here is the code in the template rsmgui.html: {% for field in elements %} <input type="hidden" id="theFieldLabelID" name="theFieldLabel" value="{{ field.label }}"> <input type="hidden" id="theFieldID" name="theField" value="{{ field }}"> <script src="{{ STATIC_URL }}js/loadStorage.js"></script> {% endfor %} The javascript loadStorage.js looks like this: var myFieldLabel=document.getElementById("theFieldLabelID").value.replace(/ /g,"") var myField = document.getElementById("theFieldID") alert("Label = " + myFieldLabel); localStorage.setItem(myFieldLabel, JSON.stringify(myField)); But it doesn't loop, it gets the first pair and then repeats it for the number of pairs. Any ideas how to "flush" the javascript so it reloads each time? -
Accessing Foreign Key Values
So here is my two models Offre and Recruteur: @python_2_unicode_compatible class Recruteur(models.Model): name = models.CharField(max_length=50) def __str__(self): return "Recruteur: {}".format(self.name) @python_2_unicode_compatible class Offre(models.Model): title = models.CharField(max_length=100, default=0) idRecruteur = models.ForeignKey(Recruteur, on_delete=models.CASCADE) def __str__(self): return "Offre: {}".format(self.title) I want to access the Recruteur's name from the Offre's foreign key, I simply thought of this solution but it doesnt work: component.html: <div *ngFor="let item of items" class="col-sm-6 col-md-12"> <div class="col-md-9"> {{item.idRecruteur.name }} </div> </div> and component.ts: items: any[] = []; constructor(private myService:MyServiceService) { } ngOnInit() { this.myService.getAllOffres() .subscribe( data => { const myArray = []; for (let key in data) { myArray.push(data[key]); console.log(data); } this.items = myArray; } ); } What am i doing wrong ? -
Django with upload messy CSV to multiple models
I've got a project that allows users to upload CSV files. These files are consistently formatted, so I can hard-code row/column numbers. However, each column contains data for multiple models. For example, ,Avg Split (IMP),Avg Speed (IMP),Avg Stroke Rate ,(/500) ,(M/S) ,(SPM) ,00:01:46.8 ,4.68 ,35.0 ,Split (IMP) ,Speed (IMP) ,Stroke Rate ,(/500) ,(M/S) ,(SPM) ,00:04:55.8 ,1.69 ,84.0 ,00:02:39.2 ,3.14 ,39.5 Sure- I could do the calculations backend for the averages and upload that into a model- however the numbers are already available for me in the CSV. I might as well use them. I know there's a whole host of Python and Django libraries to use. However they all seem to require pre-cleaned CSV data with headers in first row, and only date of the same type in the rest of the column. How do I clean this sort of data to make them accessible either in multiple CSVs, or use them directly from my models? Thank you for your advice. -
How to handle relative imports with tensorflow and django
My Directory structure is something like this: Desktop/ FaceRecognition/ __init__.py main_tf_code.py <- loads weights from numpy_weights/weights.npy numpy_weights/ weights.npy <- contains weights django_server/ simple_file_upload/ uploads/ core/ views.py <-File which uploads a jpg & sends to tf When I run the main_tf_code.py it loads numpy_weights/weights.npy takes a jpg path, processes the file and returns an integer. When I run a django server and import the main_tf_code.py in views.py it throws error saying FileNotFoundError: [Errno 2] No such file or directory: './numpy_weights' I have appended FaceRecognition to sys.path What changes should I do? Please Help! Thankyou! -
Django Templates can not access to context
I checked all the questions and answers in this site, but could not find a solution. I am new in Django, trying to develop a storage model and stucked already in the ListView. part of my view.py: from django.shortcuts import render, redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView from django.views.generic.detail import DetailView from Storage.models import Storage from django.http import HttpResponse class StorageListView(LoginRequiredMixin, ListView): model = Storage print(Storage.objects.order_by('-barcode')) template_name = 'Storage/Storagelist.html' def get_queryset(self): return Storage.objects.order_by('-barcode') I add print statement to check whether I reach the model and everyting seems normal: <QuerySet [<Storage: 123>, <Storage: 122>, <Storage: 121>]> However, I can not reach the context from the template file 'Storagelist.html': <h3>trial</h3> {% if storage_list %} <h3>trial</h3> {% endif %} Just to check access via url configurations, I added 'trial' at the beginning of the template and it also seems normal. I also tried to use context_object_name, but did not help either. Somehow, I can not reach to ListView context data from the template. My versions of applications are as follows: Django 2.0.3 Python 3.6.1 Can somebody please help me? -
How does website identity different user by cities automatically?
I'm using Django to build a website,I need a function,that website can automatically identify the cities of the users ,and then I will supply different content for users from different cities. But I have no clue what kind of technology I need to use. I heard something about google map api,but not sure.Anybody has such experience? -
How to 'join' a many-to-many 2 list of related Models
I have 2 models Product and Categories, with a many-to-many relation from Product to Category. I have a list of Product objects and a list of Product ids. Using the Product list ids, I get categories: categories = Category.objects.filter(products__in=products_list) Now I want to joint the products list and the categories, similar to a Prefetch, but I don't have a Queryset but a list of Product Objects. for product in products # the list with Product objects for category in categories: if ... ph.category = category Being a many to many the relations are in the intermediary table, so I don't know how to access, not to do a new query for every category. -
Get a Model over a many-to-many relation starting from a list of ids
I have 2 models Product and Categories, with a many-to-many relation from Product to Category. If I have a list with Product ids how can I get the Category. I tried: categories =Category.objects.filter(products__in=products_list) but is not working. -
Understanding M2M Relationships in the Browsable API for Django Rest Framework
I'm lost. When I use a ModelSerializer and can see the edit options I would expect for the different fields. In particular, I can see a dropdown list for FK relations and I can see a multiple selector for M2M. But, when I can't seem to mix named fields in the ModelSerializer. So, when I switch to a named field that points to another ModelSerializer I loose the ability to do any editing in the Browsable API. Here's some sample code: from rest_framework import serializers from myapp.models import ModelNameOne, ModelNameTwo, ModelNameThree from myotherapp.api.serializers import OtherSerializer class ModelNameThreeSerializer(serializers.ModelSerializer): class Meta: model = ModelNameThree fields = '__all__' class ModelNameTwoSerializer(serializers.ModelSerializer): class Meta: model = ModelNameTwo fields = '__all__' class ModelNameOneSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) note = serializers.CharField(max_length=None) other_model_name = OtherSerializer(read_only=True, required=False, many=True) model_name_two = ModelNameTwoSerializer(read_only=True, required=False) model_name_three = ModelNameThreeSerializer(read_only=True, required=False, many=True) class Meta: model = ModelNameOne fields = ( 'id', 'note', 'other_model_name', 'model_name_two', 'model_name_three', ) def create(self, validated_data): request = self.context.get("request") return ModelNameOne.objects.create(owner=request.user, note=validated_data['note'], other_model_name=validated_data['other_model_name'], model_name_two=validated_data['model_name_two'], model_name_three=validated_data['model_name_three'] ) def update(self, instance, validated_data): instance.note = validated_data.get('note', instance.note) instance.other_model_name = validated_data.get('other_model_name', instance.other_model_name) instance.model_name_two = validated_data.get('model_name_two', instance.model_name_two) instance.model_name_three = validated_data.get('model_name_three', instance.model_name_three) instance.save() return instance I'm looking for any suggestions you might have. The desired behavior is that … -
Get value in dictionary with a model pk in a Django template
I have a problem with a dictionary that comes from a view (I'm currently working on Django), the code is like the following: {{ dictionary.model.pk }} The model.pk is the ID of the object, and the dictionary contains: [ObjectID, some_number] So, if I put: dictionary.1 (model.pk = 1) I get the some_number that is the number that I want, but, if I put: dictionary.model.pk it doesn't return nothing, I think that the problem is that I have too many DOT's, but I don't have any other way to retrieve this kind of data, how con I solve this? PS: The dictionary comes from context. -
Update page with new data in Django
Let's imagine I have a Django app which can create and display some kind of articles which are storing in DB. Every article has a status value which means if status=1, it should be displayed, if status=0, it shouldn't. I create articles on some page of my app, and by default it's status is 1. In the other tab the other page is opened. Every N seconds it sends AJAX requests with the ids of currently displayed articles and gets response with the id and content of new articles which are not displayed yet. The question is - how can I automatically and dynamically render divs for new articles and fill them with data from response, if I don't want to create HTML-markup in success function of AJAX request with append() function or some kind of that stuff? I.e. I create article in one tab and it instantly displays in the other tab.