Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django docker image only starts python shell
I have the following docker-compose file version: '3' services: web: build: . command: bash -c "python manage.py collectstatic --no-input && gunicorn -w 2 --bind 0.0.0.0:8000 api.wsgi:application" volumes: - .:/code - static_volume:/code/api/static expose: - 8000 environment: - DJANGO_SETTINGS_MODULE=api.settings.production depends_on: - redis redis: image: "redis:alpine" celery: build: . command: celery -A api worker -l warning volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=api.settings.production depends_on: - redis nginx: build: ./nginx ports: - 80:80 volumes: - static_volume:/code/api/static depends_on: - web volumes: static_volume: which I use to build a docker image and push it to our gitlab docker registry with the following commands: docker build -t foo/api-django . docker push foo/api-django This works without a problem. But as soon as I pull the image and run it using the following command docker run -p 8000:80 -i -t foo/api-django it just shows me the python shell of the image: any advice? when i just run the docker-compose up it starts nginx, gunicorn etc. normally. -
django print all record in the cmd but display the last one on template
i have a function that retrieve data from sql server database where i am using fetchall() then for loop the retrieved data are all printed on the cmd console but when i tried to display these result on the template it only display the last record. views.py def search(request): query = cursor.execute('Select id, fullname from person') result = query.fetchall() for row in result: print("ID==>",id) IPD=row[0] return render(request,"test.html",{"IPD":IPD}) test.html {{ IPD }} -
The script django-admin is installed in '/tmp/somedir/deps/0/python/bin' which is not on PATH. Consider adding this directory to PATH
I am trying to host my Django application on Cloud Foundry, After installing the packages mentioned in requirement.txt file, I m getting error saying the package is installed in path "/tmp/somedir/deps/0/python/bin" which is not on Path. So I want to know how can I add this directory to the Path. I am using CF CLI's CF push manifest.yml cmd to push the django application. -
how to get get fix this error "The QuerySet value for an exact lookup must be limited to one result using slicing."
filtering 2 models id = request.GET.get('StudentID') studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) payment=StudentsPaymentSchedule.objects.filter(Students_Enrollment_Records=studentenroll) return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"payment":payment}) my models class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class StudentsPaymentSchedule(models.Model): Students_Enrollment_Records=models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Payment_Schedule = models.DateField(null=True,blank=True) Amount = models.FloatField() Remarks=models.TextField(max_length=500) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) can you guys help me for my assignment, cause i dont know how to connect this 2 models in views and i am little confuse in filtering . thank you in advance. -
how to check if two timestamps partially comes between given two timestamps in python
given startTime is 3:00 AM given endTime is 5:00 AM // 3am |----------------------------| 5am /// these four condition should be not match, these four comes partially in given range, // 3:30am |-------------| 4:30am // 2am|---------------|4am // 3:45am|----------------------|6am // 1am|-------------------------------------------------|7am previously what i have done is, "starttime": {"$gte": starttime, "$lte": endtime}, "endtime": {"$gte": starttime, "$lte": endtime}, in mongo query. -
how to resolve error in Django models.py?
I am new to django and was trying to make a Django project inside the virtualenv to learn but getting following error on python manage.py makemigrations: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/suraj/Documents/my_projects/django_project/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/suraj/Documents/my_projects/django_project/web_board/boards/models.py", line 11, in <module> class Topic(models.Model): File "/home/suraj/Documents/my_projects/django_project/web_board/boards/models.py", line 14, in Topic board = models.ForeignKey(Board, related_name='topics') TypeError: __init__() missing 1 required positional argument: 'on_delete' -
Django / JQuery - Changing JQuery calendar based on DB data
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" (if the apartment already isn't booked ) and book the apartment. When the user clicks on the date input field, a jquery datepicker pops up and he can then pick the date via the calendar, same for end date. Once he goes through with the booking, I want the dates to be "disabled" in the calendar so no one else can pick them. This is the datepicker that I'm using: https://jqueryui.com/datepicker/ and the code: <script> $(function () { $("#datepicker").datepicker(); }); </script> Im a total Django / web development newbie, and need some pointers in order to start somewhere with this task, I know some JS but jquery is new to me, that's why I'd like some help. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I have an Reservation model which saves the start … -
I want the sign up button to disappear when I sign up (in django templates)
Model class TeamMember(models.Model): team = models.ForeignKey(TeamInfo, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) position = models.CharField(max_length=50,default="member") class TeamInfo(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) team_name = models.CharField(max_length=50, unique=True) team_description = models.TextField(blank=True) member_count = models.IntegerField(default=1) def __str__(self): return self.team_name View class TeamInfoListView(LoginRequiredMixin,ListView): model = TeamInfo paginate_by = 20 template (https://github.com/hyunsokstar/django_inflearn2/blob/master/todo/templates/todo/teaminfo_list.html) {% for tm in p.teammember_set.all %} {% if tm.member.username == request.user.username %} <a class="btn btn-outline-info btn-sm team_register_button" data-id = {{p.id}} data-user={{request.user.id}} >탈퇴</a> {% endif %} {% endfor %} I have two questions. 1.How can I make the sign up button disappear when a user is registered? 2.For logic seems to be inefficient at present~! Is there a way to improve it? Thank you for letting me know about this. -
Fresh mysql database getting "mydb.background_task doesn't exist" - Django
I have a fresh install of a django app that uses background_tasks. If I remove the models that use background_task then I am able to do python manage.py makemigrations However, if I keep them, I get a table missing exception: "mydb.background_task doesn't exist" I have seen other people with this issue but I have tried every single suggestion: - delete all migrations files - delete sqlite3 dump file - uninstall django and django-background-tasks - make sure my machine does not have those two packages installed even outside of the virtualenv - I tried deleting my virtualenv and reinstalling everything. I have tried all of these things and python manage.py makemigrations is still giving me that exception. But nothing else does that. Django==2.1.5 django-background-tasks==1.2.0 django-compat==1.0.15 django-mysql==3.2.0 p.s: I am using Cloud SQL, I don't know if that affects anything, I don't think so. -
Formset data is not submitted via request.POST
I am using django formset to update multiple existing model objects, but after clicking the submit button nothing is received, but only non-formset data (csrf and others) Formset contains data about multiple products (forms) which may have multiple tickets (attributes) <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div id="{{ form.prefix }}"> {{ form }} </div> <a class="btn-floating btn-large waves-effect waves-light red" id="add_ticket" onclick="addTicketingBlock('{{ form.prefix }}')"><i class="material-icons">add</i></a> {% endfor %} <input type="submit" name="apply" class="waves-effect waves-light btn center-align"/> <input type="hidden" name="action" value="{{ action }}"/> </form> #addTicket button adds additional field to the specific form, not whole formset Here is what I get in request.POST in the action processing method <QueryDict: {'csrfmiddlewaretoken': ['long_hash'], '_selected_action': ['long_uuid'], 'select_across': ['0'], 'action': ['set_order_ticketing'], 'index': ['0']}> -
How to integrate a function based view into a class based view in Django?
In my site I have 2 sections for users. The user posts page and the profile page. The profile page has all their info on it, so username, description, first/last name, etc. And the user posts page has all their posts on it. However, I want to integrate them together somehow. Here is some of the code. Here is the view for the User Posts class UserPostListView(ListView): model = Post template_name = 'mainapp/user_posts.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User,username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-published_date') As you can see, I am returning the specific users posts. And now here is my profile view def view_profile(request,pk=None): if pk: user_profile = User.objects.get(pk=pk) else: user_profile = request.user context = {'user':user_profile} return render(request,'mainapp/profile.html',context) It returns all the user's info. Here is the HTML code for both the profile and user posts page {% block content %} <div class="profile-page-container"> <div class="profile-page-info"> <div class="profile-page-banner"> <div class="profile-page-banner-background"> <!-- <img src="https://cdn.pixabay.com/photo/2017/08/30/01/05/milky-way-2695569_960_720.jpg" alt="{{ user }}'s Background Image" > --> </div> <div class="profile-page-banner-text"> <h2 title="{{ user }}" id="username-profile-page">{{ user|safe|linebreaksbr|truncatechars_html:25 }} {% if user.userprofileinfo.verified %} <span class="image-profile-verified"><img draggable="false" title="Verified User" class="verifed" src="{% static 'images\verified.png' %}" alt="verified" width="25" height="25" srcset=""></span> {% endif %}</h2> <p>{{ user.first_name }} {{ user.last_name }}</p><br> </div> </div> <div class="profile-page-user-desc-box"> <p>{{ … -
How to Connect Django with Python based Crawler machine?
Good day folks Recently, I made a python based web crawler machine that scrap some news ariticles and django web page that collects search title and url from users. But I do not know how to connect the python based crawler machine and django web page together, so I am looking for the any good resources that I can reference. If anyone knows the resource that I can reference, Could you guys share those? Thanks -
Integrate django model with legacy db
I understand that Django Model is pretty fussy when it comes to the absence of a primary key. I have a legacy database (SQL Server) that I am connecting too (it is not the default one), and in that I have a database.view which I am supposed access. However, the issue is that the view does not have any primary key. How do i enable django to query from that table without being able to modify the schema? Here is what I did: I created a ReadOnlyModel and got my other django model to subclass it. This was done because I wanted to bypass the django's need for PK (evidently it did work, but threw another error - see below) class ReadOnlyModel(models.Model): def save(self, *args, **kwargs): pass def delete(self, *args, **kwargs): pass I created an ActiveObjectManager for Django to know which database to point too. The reason i used this over a router is because the router would work best if I was creating two seperate applications in the same repo. However, I am using one application: class Db2ActiveObjectManager(models.Manager): def get_queryset(self): qs = super(Db2ActiveObjectManager, self).get_queryset() if hasattr(self.model, 'use_db'): qs = qs.using(self.model.use_db) return qs Below is a sample model from the … -
How to follow HINT: Use a callable instead, e.g., use `dict` instead of `{}`?
How to follow the warnings? models.py from django.contrib.postgres.fields import JSONField from django.db import models from django_extensions.db.models import TimeStampedModel class UnderwritingValidator(TimeStampedModel): plan = models.PositiveIntegerField(null=True, blank=True, unique=True) logic = JSONField(default=dict( accept_list=[], reject_list=[] )) Then makemigrations WARNINGS: uw_validators.UnderwritingValidator.logic: (postgres.E003) JSONField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `dict` instead of `{}`. Migrations for 'uw_validators': uw_validators/migrations/0002_auto_20191011_0321.py - Remove field accept_list from underwritingvalidator - Remove field reject_list from underwritingvalidator - Add field logic to underwritingvalidator Software: postgres: 10.9 Django==2.2.5 Questions: Am I safe from error? If it safe I will ignore this warning and erase my short warning note How to fully follow the warning? -
How to see what rows were added with Django connection.cursor.execute()?
I have this python code ... sql = "INSERT INTO ... long complicated query ...;" try: with connection.cursor() as cursor: cursor.execute(sql) log.info( '%s rows inserted.' % cursor.rowcount) for row in cursor.fetchall(): print(row) except Exception as ex: err = ex log.error("sql: %s" % sql) raise err ... it prints the row count and then throws the exception: django.db.utils.InterfaceError: not a query I guess because I wasn't doing a select. But the Django documentation (https://docs.djangoproject.com/en/2.2/topics/db/sql/) says to get the affected rows call cursor.fetchall(). So how do I get the affected/rows inserted? -
How are User objects with is_active=False tested?
Here a User object is instantiated with a is_active=False attribute. I'm testing a login in conjunction with an AuthenticationForm with those same user credentials, but I'm not getting the expected response. When passing data to the form: form.is_valid() is returning False. https://docs.djangoproject.com/en/2.2/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm In the docs it says: By default, AuthenticationForm rejects users whose is_active flag is set to False. How can I set User.is_active to False, but also enter the conditional blocks subsequently so that the appropriate flash message is returned dependent on the aformentioned attribute status? def sign_in(request): import pdb; pdb.set_trace() form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): if form.user_cache is not None: user = form.user_cache if user.is_active: login(request, user) return HttpResponseRedirect( reverse('home') # TODO: go to profile ) else: messages.error( request, "That user account has been disabled." ) else: messages.error( request, "Username or password is incorrect." ) return render(request, 'accounts/sign_in.html', {'form': form}) class UserAccountSignIn(TestCase): @classmethod def setUpTestData(cls): cls.inactive_user = { 'username': 'non_user', 'password': 'secret', 'is_active': False } User.objects.create_user(**cls.inactive_user) def test_inactive_user_login_fail(self): self.client.login(**self.inactive_user) response = self.client.post(reverse('accounts:sign_in'), self.inactive_user) self.assertContains(response, "That user account has been disabled.") https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L213 Actual results:ValidationError("This account is inactive.") Expected results: A flashed messaged of: "That user account has been disabled." -
Google App Engine / Django - attempt to write a readonly database
How can I give permissions to the db.sqlite3? I can't access the source files using their google shell cloud ... I can't believe google made it so complicated ... OperationalError at /admin/login/ attempt to write a readonly database Request Method: POST Request URL: https://******.appspot.com/admin/login/?next=/admin/ Django Version: 2.2.5 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: /env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /env/bin/python3.7 Python Version: 3.7.4 Python Path: ['/srv', '/env/bin', '/opt/python3.7/lib/python37.zip', '/opt/python3.7/lib/python3.7', '/opt/python3.7/lib/python3.7/lib-dynload', '/env/lib/python3.7/site-packages'] Server time: Fri, 11 Oct 2019 02:03:43 +0000 -
How many servers do I need when I use Nuxt and back-end separately?
If I want to use nuxt only as the front end and Python as the back end, does it need a total of three servers as the Web server, node server, and backend server? -
React Links in Django/React Project
I am in the process of adding some additional functionality to my Django/React project but am hitting a snag when it comes to Linking. I'm fairly new to React so please forgive my ignorance. I have two separate HTML pages that I am rendering two different React components on. landing/react.html web_app/react.html And I have buttons on landing/react.html that need to redirect users to web_app/react.html while also rendering a different component. But whenever I use the following to link users to a different page, it renders the content of that component but none of the stylesheets. I'm assuming because those stylesheets are referenced on web_app/react.html and not landing/react.html: <Link to="/web_app/"> <button className="btn-fill"> Click This </button> </Link> The following renders the page as designed, but I can't seem to pass props using this method: <a href="/web_app/"> <button className="btn-fill"> Click This </button> </a> I've pasted some relevant code below. Is there a way that I can link users to a new component/new HTML page while also preserving the ability to pass props? App.js import React, {Component} from 'react'; import {BrowserRouter, Route, Switch} from 'react-router-dom' import './App.css'; import Comms from './comm/Comms'; import CommDetail from './comm/CommDetail'; import CommCreate from './comm/CommCreate'; import WebAppDetail from './web_app/WebAppDetail'; import … -
Angular not getting data when browser and postman are
I have an API developed in Django Rest Framework which works when called in my browser and with postman but gives a "(Failed)" response when called in Angular. Doesn't give a response code (eg 404) In the console log it claims its due to CORS but the same browser allows it then called directly. Getting: Access to XMLHttpRequest at 'http://localhost:8000/article/articletype' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. I know from the Django console that a call is being made successfully as it gives a 200 response. I have tried allowing CORS to bypass from both ends by adding headers to the Angular calls. The below is the Access-Control's I have permitted. I've also played with different Content-Types and Accepts (was text/html) but now listing as * 'Accept' : '*/*' , 'Content-Type': '*' , 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers':'*' For Django I have added the 'corsheaders' plugin with CORS_ORIGIN_ALLOW_ALL = True I have also tried returning HttpResponse of the JSON and JsonResponse in Django. In Django RFW: Currently the code looks like this but I have tried lots of different iterations jresponse = { "id" : 2, "text" : response, … -
Indent json using ujson and django_rest_framework
I have the following code: def get(self, request): with open(INSTANT_ONBOARDING_SCREENS_JSON, 'r') as json_file: return Response(ujson.load(json_file)) It reads my JSON file, and returns a response. However, when I go to this API endpoint. Everything is in 1 line. I see that ujson.dumps has an indent=4 option. I'm not sure how to display the JSON response properly (in a beautiful way) on the API endpoint. I'm using django_rest_framework, APIView to handle the GET request. -
Uncaught (in promise) Error: Request failed with status code 400, How can I solve this error in React.js + Django App?
I am programming an app with a Django rest API and React.js frontend installed in a django app. I am encountering an error when trying to make a post request from react to the rest API. Posting to the Django rest API works in postman. I am trying to set up the component with the useState hook, Redux and axios. Im not totally sure I set up the state correctly. Here is the relevant code: From the form component (I suspect the error is here): import React, { useState } from "react"; import { connect } from "react-redux"; import PropTypes from "prop-types"; import { addLead } from "../../actions/leads"; const Form = ({ addLead }) => { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [message, setMessage] = useState(""); const onSubmit = e => { e.preventDefault(); const lead = { name, email, message }; addLead(lead); // Clear Fields setName(""); setEmail(""); setMessage(""); }; return ( <div className="card card-body mt-4 mb-4"> <h2>Add Lead</h2> <form onSubmit={onSubmit}> <div className="form-group"> <label>Name</label> <input className="form-control" type="text" name="name" onChange={e => setName(e.target.value)} value={name} /> </div> <div className="form-group"> <label>Email</label> <input className="form-control" type="email" name="email" onChange={e => setEmail(e.target.value)} value={email} /> </div> <div className="form-group"> <label>Message</label> <textarea className="form-control" type="text" name="message" onChange={e => … -
Preview webpage at mobile device
I am new to html. I'm currently using django to create a website and wondering is there some way that I can preview my website at phone? For instance, if I set my width to be 1000px, how this will behave in a mobile device? -
Python/Django user detail view
I have problem with Django Rest, about user edit and detail. So this is the code class UserUpdateAPIView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UserUpdateSerializer lookup_field = 'username' permission_classes = [IsOwnerOrAdminOrReadOnly] throttle_scope = 'edit_user' and view.py is like path('<slug:username>/edit/', UserUpdateAPIView.as_view(), name='user-update'), What I need to do is to delete this <slug:username> and set it to be only /edit so when I'm calling for example http://localhost:8000/api/user/edit/ I will receive current info about my account in API and can change it if I want. I know this is put method, so is it possible to return current informations in json format about my account? -
update field in model using the same field with the function update() django
I have for many records to update a field, I must do it with the function .update() that already comes with the ORM of Django. I need to update this field concatenating a string with the value of the same field. I have tried using annotate, with F expression and Value. But it didn't work, because in the annotation of a field I can't seem to use the same field. This is what I tried to do: Model.objects.all().annotate(image=Concat(Value("Path/"), F("image"))) I have the next model: +------+-------+ | id | image | +------+-------+ | 1 | image1| | 2 | image2| | 3 | image3| When updating the model, suppose I want to concatenate the string "Path/" with field image, should be something like this +------+------------+ | id | image | +------+------------+ | 1 | Path/image1| | 2 | Path/image2| | 3 | Path/image3|