Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting following error when I create a django project in pycharm for Mac OS
I have been installed django using following command in terminal: sudo pip3 install django and I got this response: kinredondeMacBook-Air:~ kinredon$ sudo pip3 install jiango The directory '/Users/kinredon/Library/Caches/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 '/Users/kinredon/Library/Caches/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 satisfied: jiango in /usr/local/lib/python3.6/site-packages Requirement already satisfied: django<1.5,>=1.4 in /usr/local/lib/python3.6/site-packages (from jiango) then I create a django project in Pycharm and I get this following error: Error:Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/bin/django-admin.py", line 2, in <module> from django.core import management File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 54 except ImportError,e: ^ SyntaxError: invalid syntax Anyone can help me? Thanks! -
AttributeError at /admin/login/ 'tuple' object has no attribute 'rsplit'
Hye . i come accross this error when i try to login to my admin page . AttributeError at /admin/login/ 'tuple' object has no attribute 'rsplit' Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.10 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'rsplit' Exception Location: C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\utils\module_loading.py in import_string, line 15 Python Executable: C:\Users\Adila\Envs\tryFOUR\Scripts\python.exe and i dont know why this error is raised and i dont know how exactly to fix it . i do search about this error and most of them when they try to run the collectstatic command. the error is caused by the comma and i did delete the comma behind the closed bracket here : STATICFILES_DIRS= ( os.path.join(os.path.dirname(BASE_DIR), "static", "static") ) but i still cant access to my admin page . i did follow to the traceback : def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: msg = "%s doesn't look like a module path" % dotted_path six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) module = import_module(module_path) i try to make my own custom registration page for user and super … -
Django file uploading error
i am trying to upload file but unable to do so, my function in view, def user_in(request): if not request.user.is_authenticated: return render(request, 'accounts/logout.html') else: if request.method == 'POST': form_new = Fileupload(request.POST, request.FILES ) if form_new.is_valid(): return redirect('in') else: form_new = Fileupload() return render(request, 'accounts/in.html', {'form_new': form_new}) my form, class Fileupload(forms.Form): BrowseFile=forms.FileField() class Meta: model=User and my template, <form action="." method="POST" enctype="multipart/form-data" > <h3>Welcome to DropBox<br><br></h3> {% csrf_token %} {{form_new.as_p}} <p><input type="submit" value="Save" ></p> <br> <a href="{% url 'logout' %}">Logout</a> {%else%} <p>You must login first</p> <a href="{% url 'login' %}">Logout</a> {% endif %} <br> </form> after pressing submit button i do not see any doc in media location. Am i doing something wrong or anything missing? Thanks in advance. -
django model get field method
I have a requirement, when a field say Price in a django model Lead is accessed I have to apply some business logic and update the price. I can accomplish in Serializers / Views. However this object is accessed by several views and hence its not a viable design to have a code in several place. So i'm looking for a way where i can get control like get_price(self). class Lead(models.Model): price = models.IntegerField(_('price'), default=10) def get_price(self): ''' Looking for something like this ''' get_price to be called when any serializers/ views access this model. -
Using bt module in Django gives error for pandas Key error volume Exception
index = [u'bfh', u'qhf'] then i will convert into comma seprated value like index = ", ".join(str(bit) for bit in index) after run, data = bt.get(index, start=start, end=end) gives an error Django Version: 1.8 Exception Type: KeyError Exception Value: 'Volume' in pandas -
Use a 'join-query' like ‘’SQLAlchemy‘’ in ‘’Django‘’?
How to use Django: get user followed_set all articles? use in sqlAlchemy: Article.query.join(Follow, Follow.followed_id == Article.user_id)\ .filter(Follow.follower_id == self.id) My Code: class User(AbstractUser): # Author pass class Article(models.Model): content = models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Follow(models.Model): # user ManyToMany timestamp = models.DateField(auto_now_add=True) follower = models.ForeignKey(User, related_name='followed_set', on_delete=models.CASCADE) followed = models.ForeignKey(User, related_name='follower_set', on_delete=models.CASCADE) -
Trouble updating BooleanField with Django ModelForm
Using Django 1.11 and Python 3.4 I have a model: class ToDo(models.Model): completed = models.BooleanField(default=False) I want users to be able to update this field for the model by clicking a checkbox, so I made a ModelForm as follows: class CompletedForm(ModelForm): class Meta: model = ToDo fields = ['completed'] The problem I am having is understanding how I can get the database to update whenever the user clicks the checkbox, so that the completed field will toggle between True or False. In views.py: if request.method == 'POST': for x in range(0, all_todos.count()): a = all_todos[x] completedform = CompletedForm(request.POST, instance=a) else: for x in range(0, all_todos.count()): a = all_todos[x] print(a) completedform = CompletedForm(instance=a) I've rendered the checkboxes in the event of either GET or POST method, and linked each box to a particular instance. I assume that most of the logic will take place in the POST method since this is making a change to the database. Thank you -
How to Embed a Hyperlink - Django app
I'm pretty much new to web development using Django, python, html, I've created have a basic Django app that displays a list of users from mysql, and all works just fine. I now want to make it so that user can click on the return value such as total books by users, date, etc.. is a link that when clicked on will redirect to other page and displays the detail of that query, hopefully someone can walk me through..Thanks in advance.. # here I get all counter I need and it works just fine def _get__user_info(self, qs): user.data['total_book'] self._get_all_count(mydata, "total") ..... -
Context from Django Render Not Displaying Till Refresh?
I am using an AJAX call to POST a value to my views. From my views I am finding the product based on the value(id) passed to my view. I add it to my invoice and apply it to my context which I render at the bottom of my view. The context will not be displayed until I refresh, but I can't have that. I am stuck. ... elif request.is_ajax(): product_id = request.POST.get('value') if product_id: product_info = Product.objects.get(id=product_id) new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info) invoice.attached_products.add(new_invoice_product) context['attached_products'] = invoice.attached_products.all() ... return render(request, 'inventory/invoice_create.html', context) -
Regist form cannot be sent
Regist form cannot be sent. I wrote in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if login_form.is_valid(): user = login_form.save() login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return redirect('profile') context = { 'login_form': login_form, 'regist_form': regist_form, } return render(request, 'registration/accounts/login.html', context) in login.html <body> <ul class="top-menu"> <h3 class="login">Login</h3> <div class="container"> <form action="{% url 'login' %}" method="post" role="form"> {% csrf_token %} <div class="form-group"> <label class="email_form">Email</label> <input for="id_email" name="email" type="text" value="" placeholder="Email" class="form-control"/> </div> <div class="form-group"> <label class="password_form">Password</label> <input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12" placeholder="Password" class="form-control"/> </div> <button type="submit" class="btn btn-primary btn-lg">Login</button> <input name="next" type="hidden" value="{{ next }}"/> </form> </div> </ul> <div class="newaccount"> <h2>New Account registration</h2> <form class="form-inline" action="{% url 'accounts:detail' %}" method="POST"> <div class="form-group"> <label for="id_username">Username</label> {{ form.username }} {{ form.username.errors }} </div> <div class="form-group"> <label for="id_email">Email</label> {{ form.email }} {{ form.email.errors }} </div> <div class="form-group"> <label for="id_password">Password</label> {{ form.password1 }} {{ form.password1.errors }} </div> <div class="form-group"> <label for="id_password">Password(conformation)</label> {{ form.password2 }} {{ form.password2.errors }} <p class="help-block">{{ form.password2.help_text }}</p> </div> <button type="submit" class="btn btn-primary btn-lg">Regist</button> <input name="next" type="hidden"/> {% csrf_token %} </form> </div> </body> in forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from .models import User class … -
Access Django's class model and display on template
I am new to django and is working on my pet project. I am having a bit of problem accessing the data from one of my classes in models.py models.py class Team_Region(models.Model): name = models.CharField(max_length=50) # String representation def __str__(self): return self.name class Team_Name(models.Model): t_name = models.CharField(max_length=100) logo = models.ImageField(upload_to='team_logos', blank=True) region_member = models.ForeignKey(Team_Region, related_name='regions') def __str__(self): return self.t_name + ' - ' + str(self.region_member) class Team_Member(models.Model): mem_name = models.CharField(max_length=100) position = models.CharField(max_length=50) member_of_team = models.ForeignKey(Team_Name, related_name='teams') def __str__(self): return self.mem_name + ' - ' + self.position + ' - ' + str(self.member_of_team) views.py # Display regions in list class TeamRegionListView(ListView): context_object_name = 'regions_list' model = Team_Region template_name = 'dota_teams/team_regions_list.html' # Display all teams associated to the region class TeamRegionDetailView(DetailView): context_object_name = 'region_teams' model = Team_Region template_name = 'dota_teams/team_regions_detail.html' class MemberDetailView(DetailView): context_object_name = 'team_members' model = Team_Name template_name = 'dota_teams/member_detail.html' urls.py url(r'^$', views.TeamRegionListView.as_view(), name='all_regions'), url(r'^(?P<pk>\d+)/$', views.TeamRegionDetailView.as_view(), name='region_teams'), url(r'^(?P<pk>\d+)/(\d+)/$', views.MemberDetailView.as_view(), name='member_details'), I'm not sure how to access the mem_name and position variables under the Team_Member class. In my views.py, if I use the model Team_Name, the ID is not properly assigned to the region and team. I have tried accessing the Team_Member by using a For loop from Team_Region and use … -
Python Django button not redirecting correctly according to URL
I implemented my own map-search form such that once map-search is clicked it would use the onclick search function. function search() { var query = document.getElementById("search").value; if (query == ""){ $("#button-group").addClass("hidden"); }else{ $("#button-group").removeClass("hidden"); jsonLayer.clearLayers(); $.getJSON('http://localhost:8000/search/'+ query, function (boundary) { jsonData = boundary[0].geojson; jsonLayer.addData(jsonData); lon = boundary[0].lon; lat = boundary[0].lat; boundingbox = boundary[0].boundingbox; map.fitBounds([ [boundingbox[0],boundingbox[2]], [boundingbox[1],boundingbox[3]] ]); }); } } After that function is fired, the button-group, that is initially hidden will be revealed. I tried clicking one of the buttons that was revealed which I have set to go to another template in Django but instead it will append in the url my query resulting to: http://localhost:8000/?search=Test <div class="col-lg-offset-3 col-lg-6"> <div class="input-group"> <input id="search" name="search" type="text" class="map-search form-control input-sm"> <span class="input-group-btn"> <button class="map-search btn btn-default btn-sm" type="button" onclick="search()"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> <div id="button-group" class="button-group hidden"> <a href="{% url 'trips_view' %}"><button class="btn btn-primary btn-lg btn-space col-sm-3">View Trips</button></a> <a href="{% url 'manage' %}"><button class="btn btn-primary btn-lg btn-space col-sm-3">Manage Trips</button></a> </div> </div> My Url url(r'^view/', views.trips_view, name='trips_view') I checked my network and it would go in this order: 1.) localhost:8000 2.) Click map-search -> it loads query 3.) Click button from button-group with url to another template 4.) It will … -
Django 1.8 csrf NameError: Undefined
I am using Django_Mako_Plus on top of Django. And as I try to put a ${csrf_input} after my form. I am getting a NameError: Undefined. The middleware is correct. What am I doing wrong? Below is my code: <div class="backgroundregister"> <form id="registerform" action="/homepage/register" method="post" style="margin-top: -7vh;">${csrf_input} <div class="form-group" id="register-id"> ${ form.as_table() } <button style="margin-top:15px; height:40px; width:300px; margin-left:3px; margin-top:30px;" type="submit" class="dissimulation"> </div> </form> </div> I am using Django 1.8 Thank you for all your help in advance. -
How filter by a foreign key on Django 1.11
I'm trying to search on CRUD by a field that's a foreign key, but I allways get the error: Related Field got invalid lookup: icontains That's was my admin.py: from django.contrib import admin from .models import Subject class SubjectAdmin(admin.ModelAdmin): list_display = ['owner', 'name', 'slug'] search_fields = ['owner', 'name', 'slug'] prepopulated_fields = {'slug': ('name',)} admin.site.register(Subject, SubjectAdmin) I saw on a forum that I need to change the "owner" by "owner__name", but now I get another error: Related Field got invalid lookup: name -
Cannot connect to remote PostgreSQL instance from Django app running within Docker container
I am trying to connect a Django app running inside of a docker container to a PostgreSQL database running on another computer (lets say with an IP address of 192.168.1.22). Thus far in my experimentation, I always get the following error when attempting to connect to the PostgreSQL instance from a docker container (my code works fine outside of the docker container): Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I've made sure that I allow all inbound connections to the PostgreSQL database (by changing the config file for my PostgreSQL server as recommended here. Here is my settings code in my Django app for the database connection: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sa_server_db', 'USER': 'sa_admin', 'PASSWORD': 'PAfk17!x!?', 'HOST': '192.168.1.22', 'PORT': '5432', } } Here is my Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 # Install dependencies RUN mkdir /config ADD /config/requirements.pip /config/ RUN pip install -r /config/requirements.pip # Install source code RUN mkdir /src WORKDIR /src COPY ./src/ /src/ ENV UWSGI_WSGI_FILE=/src/xxxxxxxxx/wsgi.py UWSGI_HTTP=:8000 UWSGI_MASTER=1 UWSGI_WORKERS=2 UWSGI_THREADS=8 UWSGI_UID=1000 UWSGI_GID=2000 UWSGI_LAZY_APPS=1 UWSGI_WSGI_ENV_BEHAVIOR=holy RUN python /src/manage.py collectstatic --noinput EXPOSE 8000 CMD ["uwsgi", "--http-auto-chunked", "--http-keepalive"] Here is the script I use to build (& run) my … -
csfr token needed for form created in template - django
I have a django project and I want to create a form within an html template that is dynamic in the sense that it changes based on what is grabbed from the database. If I want to create a form in this manner - within the html. Do i need to include the csfr tocken to the form before processing the form? -
data How to keep form when user gets redirected back to the form when they fail a validation (Python, Django)?
I know this might be a duplicate question, but the previous one was an older question and those questions uses a form instance which doesn't really help me. How do I keep my form data after a failed validation? I have multiple dropdowns and input fields and I hate to see my users re-do and re-type everything when they fail validation in the backend. Let's say I have this very simple form: HTML: <form class="" action="/register" method="post"> <label for="">First Name</label> <input type="text" name="" value=""> <label for="">Last Name</label> <input type="text" name="" value=""> <label for="">Password</label> <input type="password" name="" value=""> </form> views.py: def register(self): ..... if errors: for err in errors messages.errors(request, err) return redirect('/') else: messages.success(request, "Welcome User!") return redirect('/dashboard') Most examples that I came across were using the form instance which uses form.save() etc. I opted out on that one. Is there a way to auto-populate my form with the data that the user submitted if they were to fail validation? Thanks! -
ModelSerializer is not saving changes to DATA when passed back to the view in DRF but are shown in the serializer
I've seen several questions that sound related on SO and GitHub, but I haven't been able to resolve my issue. Also read through the ModelSerializer section in the DRF documentation: http://www.django-rest-framework.org/api-guide/serializers/#modelserializer Anyway, I am sending part of unique URL that is emailed to the user to DRF for validation. When it has been validated it should allow the user to answer the security questions associated with the account. It is supposed to update the data object with the security questions so that they can be rendered in React. When I print(data), it shows the sq1 and sq2 that I set while still in the serializer. When it gets back to the view.py, and I print out print(new_data), it is just showing the original data sent from React to the API. From what I gather it is related to ModelSerializer, but am not finding a fix for my situation. How do I update the data so it returns my changes back to the ./view.py and React? # ./views.py class ValidateKeyAPIView(APIView): permission_classes = [AllowAny] serializer_class = ValidateKeySerializer def post(self, request, *args, **kwargs): data = request.data serializer = ValidateKeySerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data print(new_data) return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) # ./serializers.py … -
different text depending on if user has liked a post
I have this if statement in my template to display different buttons depending on if a user had like a post. There are the same trigger link, url, and view, however the text either says "Like" or "Unlike" depending on if the user has previously liked that post or not. However it is not working, no errors, just not working. likes is a ManyToManyField in the UserPost model. Template: {% if request.user.username in post.likes %} <a class="link right-margin" href="{% url 'feed:post_like' post.id %}"> Unlike: {{ post.likes.count }} </a> {% else %} <a class="link right-margin" href="{% url 'feed:post_like' post.id %}"> Like: {{ post.likes.count }} </a> {% endif %} -
Django: Cannot access variable set in middleware
I am trying to add a variable to my request variable in my custom middleware. Later I want to access that variable from my view. Here are the relevant bits: middleware.py class DomainInterceptMiddleware(object): def process_request(self, request): request.myvar = 'whatever' settings.py - Added this above CommonMiddleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'page.middleware.DomainInterceptMiddleware', # 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] views.py def index(request): output = request.myvar return HttpResponse(output) However, on trying to access /index, I get this error File "/path/to/views.py", line 32, in index output = request.myvar AttributeError: 'WSGIRequest' object has no attribute 'myvar' Where am I going wrong? -
Deploying with zappa, Django project in subfolder
I'm new to Docker, AWS Lambda and Zappa, but I'm trying to configure a project with very little success. I connect to Docker (docker-compose run web bash), activate the environment, configure the AWS credentials and run zappa init and zappa deploy. However, after deployment I get an error (executing zappa tail): ModuleNotFoundError: No module named 'project' I believe that that's because my dir structure is not the standard: Dockerfile zappa_settings.json requirements.txt project\ - manage.py - root\ - settings.py - wsgi.py - ... So, my django project is inside the project folder, as I don't like having all the files thrown there and mixed with other configuration files. My zappa config file looks like this: { "dev": { "aws_region": "us-east-2", "django_settings": "project.root.settings", "profile_name": "default", "project_name": "task", "runtime": "python3.6", "s3_bucket": "bucket-name" } } And Dockerfile: FROM lambci/lambda:build-python3.6 # Copy in your requirements file ADD requirements.txt /requirements.txt # Copy your application code to the container RUN mkdir /code/ WORKDIR /code/ ADD . /code/ ENV PS1 'zappa@$(pwd | sed "s@^/var/task/\?@@")\$ ' ADD zappa_settings.json /var/task/zappa_settings.json WORKDIR /var/task RUN virtualenv /var/venv && \ source /var/venv/bin/activate && \ pip install -U pip zappa && \ pip install -r /requirements.txt && \ deactivate CMD ["zappa"] Can you tell … -
Django custom filter error. Returns "invalid filter"
I've been trying to create this custom filter in Django, and I can't for the life of me make it work. in my templatetags folder I have the files __init__.py and alcextra.py in my template I first load the static files and then the templatetags. I've tried reseting the server and deleting and creating the files again. {% load staticfiles %} {% load alcextra %} Which is then extended to my main html file. I have tried putting it in the main html file. in alcextra.py I have written from django import template register = template.Library() @register.filter def multiply(value, arg): return value * arg I have tried loads of different @register versions like @register.filter("multiply", multiply) @register.filter(name="multiply") @register.filter() @register.simple_tag(takes_context=True And all return the same error, invalid filter: 'multiply'. At this point I don't know what to do or what to try. Overview of the directory -
Wagtail admin - default ordering of child pages
In the admin area I have to activate the "Enable ordering of child pages" every time. Is there a way to set this as a permanent option? The main problem is that the listing in the child pages view changes depending on if this is activated or not(if you have changed the ordering), which might be a bit confusing for some. Potentially one could change the default ordering of the children list to match the manually ordered list somehow? -
How to route a multi-part form in django
I'd like my users to be able to place orders. For this kind of order, the user uploads a csv. The app parses, the CSV, serializes the data, and then needs to show the user a new view with the data and a "confirm order" button. I'm not sure how to do this in django. class UploadSampleSheetView(LoginRequiredMixin, FormView): form_class = UploadSampleSheetForm template_name = 'pages/upload.html' def form_valid(self, form): uploaded_sample_sheet = self.request.FILES['uploaded_sample_sheet'] sample = _parse_sample_sheet_to_sample_model(uploaded_sample_sheet) sample.save() return super().form_valid(form) def get_success_url(self): return reverse("orders:create") # how do I get the data over? class CreateOrderView(LoginRequiredMixin, CreateView): model = Order form_class = NewOrderForm template_name = 'pages/complete_order.html' What I'm looking for is some way that, on success, the UploadSampleSheetView can return a CreateOrderView with sample data. In general, I'd love to be pointed to a reference about how to build user flows like this one. How does one view defer to another? I'm seeing a lot of return HttpResponseRedirect('url') which seems a little messy. How do I pass data around views? -
Django 1.11 don't included urls.py
Hello I'm working in my first Django App and I have the next problem: The included URLconf 'eventus.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. . ├── eventus │ ├── eventus │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── db.sqlite3 │ │ ├── settings │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── base.cpython-36.pyc │ │ │ │ └── local.cpython-36.pyc │ │ │ ├── base.py │ │ │ ├── local.py │ │ │ ├── prod.py │ │ │ └── staging.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── myapps │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-36.pyc │ ├── events │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── forms.cpython-36.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ ├── admin.py │ …