Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to change the value of foreign key to foreign key of an object Django
I am having a model structure like: class user(models.Model): name = models.CharField(max_length=100) tasks = models.IntegerField(default=0) class project(models.Model): worker = models.ForeignKey(user, on_delete=models.CASCADE) project_name = models.CharField(max_length=100) class task(models.Model): project = models.ForeignKey(project, on_delete=models.CASCADE) task_name = models.CharField(max_length=150) expected_date = models.DateField(auto_now=False,auto_now_add=False,) actual_date = models.DateField(auto_now=False,auto_now_add=False,blank=True,null=True,) I want to traverse through the task list and if actual date field is not null i.e. task completed then to update the tasks field in user class by 1. I have written the following code: a = task.objects.filter(actual_date__isnull=False) for x in a: x.project.worker.tasks+=1 However this is not giving the desired result. What should I do? -
Django trying to match wrong url path
Trying to deploy my Django app on virtual shared server. All works as expected until I try to log in to the admin app. I think it may have something to do with the way that the server deals with posts (had a similar problem with Flask). The setup works fine on my local machine. I can get to the admin login page, but when I submit my credentials I get a 404 error. In debug mode the response is: Page not found (404) Request Method: POST Request URL: https://lindcraft.williesworkshop.com/admin/login/ Raised by: django.contrib.admin.sites.login Using the URLconf defined in lindcraft.urls, Django tried these URL patterns, in this order: admin/ ^[P|p]roducts?/(?P<prod_id>\d{0,3})/$ [name='product'] ^[P|p]rices?/?$ [name='prices'] ^[P|p]arking [name='parkingIntro'] ^[D|d]isplay [name='displayIntro'] ^[C|c]ontact [name='contact'] ^[A|a]bout [name='about'] ^$ [name='index'] The current path, login/, didn't match any of these. Django seems to be looking for "login/" instead of "admin/" even though the "request URL" is "... /admin/login/" The admin part is striped off somehow. Funny thing is, the exception seems to be raised by django.contrib.admin.sites.login as though the request actually made it to admin. It seems to me that the same URL works with a GET but not with a POST. Can anyone offer any insight? FWIW, my … -
Didn't migrate a change in my model to my remote server - now it's causing problems
I changed my id in my model to a UUID field. I migrated it to my local development server, but not my remote server. I then changed the id again to a CharField - which I then migrated on my local server. However when I tried to migrate this on my remote server, it returns this error: django.db.utils.ProgrammingError: cannot cast type integer to uuid LINE 1: ..."post_post" ALTER COLUMN "id" TYPE uuid USING "id"::uuid, AL... It seems that because I skipped the UUID migration on my remote server, it's causing this error. Here's what happens when I perform showmigrations on my remote server: https://i.imgur.com/GumHXU8.png All of the boxes without the X are id-related. How can I fix this? PS: My local server works fine. -
Gunicorn returning a ModuleNotFoundError when running a Django app through Docker
I made a docker container to run my Django app, and it's currently returning a ModuleNotFoundError when referring to the Gunicorn command in the Docker instructions. I've tried as many combinations as I can in referring to the wsgi module entrypoint. None of them work. So I'm thinking there may be something wrong with my Docker instructions that I'm not seeing. Here are the Docker instructions: FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev openssl-dev py-cffi \ # Translations dependencies && apk add gettext \ # https://docs.djangoproject.com/en/2.0/ref/django-admin/#dbshell && apk add postgresql-client # Requirements have to be pulled and installed here, otherwise caching won't work COPY ./requirements /requirements # RUN pip install -r /requirements/local.txt RUN pip install -r /requirements/production.txt COPY ./compose/production/django/entrypoint.sh /entrypoint.sh # RUN sed -i 's/\r//' /entrypoint.sh # RUN chmod +x /entrypoint.sh COPY ./compose/local/django/start.sh /start.sh RUN sed -i 's/\r//' /start.sh RUN chmod +x /start.sh COPY ./compose/local/django/celery/worker/start.sh /start-celeryworker.sh RUN sed -i 's/\r//' /start-celeryworker.sh RUN chmod +x /start-celeryworker.sh COPY ./compose/local/django/celery/beat/start.sh /start-celerybeat.sh RUN … -
Django Rest Patch/Update Functions Not Working
I'm very new to Python, Django, and the Rest Framework. I'm just trying to set up a simple API to allow data to be updated in a postgresql database. I'm trying to test my patch function but it isn't having any effect in the database. I know the db connection is working since my ViewList endpoints are pulling data correctly. I've searched through many of the similar questions on here but none of them quite matched what I had or the solution provided did not work. Here's what I have currently: Model: class Users(models.Model): userid = models.IntegerField(primary_key=True) username = models.CharField(max_length=50) class Meta: managed = False db_table = 'users' URL: path('users/<int:userid>/', UsersRudView.as_view(), name='users-rud') View: class UsersRudView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'userid' serializer_class = UsersSerializer def get_queryset(self): return Users.objects.all() def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) Here's the call I'm using to test the patch function: url = 'http://127.0.0.1:8000/users/1/' payload = {"userid":1,"username":"John Smith"} r = requests.put(url, data=json.dumps(payload)) I've tried a number of different approaches but from what I've seen this should be close to what I need. I just don't know enough about this to know where my error is. I'm hoping it's … -
Pipfile.lock out of date
I'm trying to deploy a large django project to heroku. I installed Heroku CLI, logged in, created an app and ran: git push heroku master I have a Pipfile and requirements.txt already set up. I added a runtime.txt to specify that I need python 2.7. This is also in the Pipfile. This is what I get from pushing to heroku: $ git push heroku master Counting objects: 12159, done. Delta compression using up to 2 threads. Compressing objects: 100% (4853/4853), done. Writing objects: 100% (12159/12159), 20.94 MiB | 1.82 MiB/s, done. Total 12159 (delta 6859), reused 12036 (delta 6751) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.4 remote: -----> Installing pip remote: -----> Installing dependencies with Pipenv 11.8.2… remote: Your Pipfile.lock (3b2ba9) is out of date. Expected: (83a5b4). remote: Aborting deploy. remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to camp-infinity. remote: To https://git.heroku.com/camp-infinity.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/camp-infinity.git' For some reason it tries to install python 3, and it also doesn't like my … -
Login facebook with Django social-auth-app-django (1062, "Duplicate entry '' for key 'email'")
When I try to login with Facebook account in production server this error occurs: (1062, "Duplicate entry '' for key 'email'") There are no duplicate emails and just happens in production server not in local Error in: social_django/storage.py line 70 @classmethod def create_user(cls, *args, **kwargs): username_field = cls.username_field() if 'username' in kwargs and username_field not in kwargs: kwargs[username_field] = kwargs.pop('username') try: if hasattr(transaction, 'atomic'): # In Django versions that have an "atomic" transaction decorator / context # manager, there's a transaction wrapped around this call. # If the create fails below due to an IntegrityError, ensure that the transaction # stays undamaged by wrapping the create in an atomic. with transaction.atomic(): ###################### ERROR ###################### user = cls.user_model().objects.create_user(*args, **kwargs) ###################### ERROR ###################### else: user = cls.user_model().objects.create_user(*args, **kwargs) except IntegrityError: # User might have been created on a different thread, try and find them. # If we don't, re-raise the IntegrityError. exc_info = sys.exc_info() # If email comes in as None it won't get found in the get if kwargs.get('email', True) is None: kwargs['email'] = '' try: user = cls.user_model().objects.get(*args, **kwargs) except cls.user_model().DoesNotExist: six.reraise(*exc_info) return user -
Angular 5 build and Zone.js
Have the picture error after build my angular 5 app, i serve my app with a django view. I added the zone.js dependencie in my angular package.json file but i get the same error. this is my Github gists view and template, the view load all files in the static path. this works fine. Regards -
Django: CREATE data in Database via multiprocessing can cause `too many clients already`?
I'm running my django application, which getting data from websocket API and store them in my PostgreSQL Here is the part of code: class MyWebsocketClient: . . def process_message(self, msg): # Get msg from websocket server forever (until I force to quit the program) self.data_buffer.append(msg) if len(self.data_buffer) > 3000: pool = Pool(cpu_count() * 2 // 3) pool.map_async(store_data, self.data_buffer) self.data_buffer = [] def store_data(data_buffer): BinanceTick.objects.create( field1=self.data_buffer['t'], field2=self.data_buffer['p'], field3=self.data_buffer['q'], ) This works pretty well, in the parallel way. But when I tried to make query using to the same database in other interface(such as jupyter or django-shell-plus), it ouccured errors: OperationalError: FATAL: sorry, too many clients already FATAL: sorry, too many clients already Why does it happen? Belows are what I can think about: Each Pool still have a connection with DB even after it finished its task I should have added pool.close() what else What's the main problem? -
Changing model id from integer to alphanumeric
I changed by id in my model from the default id = models.AutoField(primary_key=True) to id = models.CharField(max_length=18, primary_key=True, default=random_string). Here's the function for random_string(): def random_string(chars=string.ascii_letters + string.digits): size = random.randrange(10, 15) return str(''.join(random.choice(chars) for _ in range(size))) it generates an alphanumeric string between 10 and 15 chars (e.g. Kf4Idv9Wlmq). When I performed makemigrations and migrate on my local development server, there was no problem. However when I performed makemigrations and migrate on my remote server which uses postgres, it fired the error. Any idea how I can fix this? -
Override rest-auth signup to add extra fields to my backend
I'm trying to override the RegisterSerializer to add additional field that i could save on the backend while the signup process but i couldn't get it to work. I'm using React as a view layer and it passes the data perfectly when i use the default RegisterSerializer after adding RegisterSerializer it doesn't work at all here is my code : from rest_auth.registration.serializers import RegisterSerializer class RegisterSerializerCustom(RegisterSerializer): mobile = serializers.CharField(required=False, write_only=True) def get_cleaned_data(self): return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'mobile': self.validated_data.get('mobile', ''), } def validate_mobile(self, mobile): return mobile def save(self, request): res = super(RegisterSerializerCustom, serializers).save(request) return res and i added my these in setting.py REST_AUTH_SERIALIZERS = { 'REGISTER_SERIALIZER':'user_profile.serializers.RegisterSerializerCustom', } what is the problem in my code ?! -
How to avoid repeated logic in APIView Django Rest Framework
I am doing an api for catching webhooks from a site, the website asks you to activate your webhook within the same url that will use when the webhook is called. I will have a lot of webhooks, therefore i will have a lot of repeated logic for activating the webhooks. How could this be done using Django Rest Framework's APIView? class MyWebhookView(APIView): def post(self, request): data = request.data # repeated logic if data.get('type') == constants.WEBHOOK_VERIFY: hook = Hook(ID, TOKEN) code = hook.validate(data.get('hook_id'), data.get('code')) return Response({'code': code}) # custom logic -
Django FileInput Accept Binary Files
I want to except files with python, ruby and binary extension. python and ruby works with .py,.rb but binary files should not have extension. How to indicate .py,.rb or no extension? Also how do I provide these restrictions in the model? class AlcaForm(forms.ModelForm): class Meta: model = AlcaModel widgets = { 'file': forms.FileInput(attrs={'class': 'form-control', 'accept': '.py,.rb,'}), } exclude = [] -
Django nginx The plain HTTP request was sent to HTTPS port
When I go to http://127.0.0.1:8000/ The 400 error comes up saying The plain HTTP request was sent to HTTPS port This is my nginx.conf of Django instance is the code below. What is the reason for this error? upstream sweb { ip_hash; server sweb:8000; } server { server_name oncms.ondemandkorea.com; listen 80; ssl_certificate /certs/development.crt; ssl_certificate_key /certs/development.key; ssl on; location /static/ { autoindex on; alias /static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass https://oncmsweb/; } } -
Can't login and sign up in my django-site
After deploying on heroku i faced the following problem when trying to log in to my account: elation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... All bin files includes the following stroke in the header: #!/home/far/git/django_site.git/Django_work/django_structure/bin/python -
Django разделение пользователей
Делаю сайт на Django и использую библиотеку Django-allauth для авторизации. Нужно разделить пользователей на Покупателей и поставщиков, следовательно для каждого типа пользователя после авторизации будет своя домашняя страница. Решил разделить пользователей добавив переменные is_buyer и is_supplier, написал это в модель UserProfile (создал новую модель пользователя, добавив поле user, и соединил с Django User через OneToOneField). Вопрос такой, если ещё способы сделать это? -
RelatedObjectDoesNotExist at /accounts/addtimesheet/ TimeSheet has no project
I am trying to add an object(Project) to an another object TimeSheet. When i am trying to do that I am getting an error saying that "RelatedObjectDoesNotExist at /accounts/addtimesheet/ - TimeSheet has no project." Though I had project in TimeSheet as a ForeignKey to the Project Model. I think I have missed something in my models.py while file while creating Project Model.Can someone help me what did i miss. model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) emp_name = models.CharField(max_length=500) gender = models.CharField(max_length=10) job_position = models.CharField(max_length=20) salary = models.IntegerField() def __str__(self): return self.emp_name class Project(models.Model): project_name = models.CharField(max_length=200) employees = models.ManyToManyField(Profile) def __str__(self): return self.project_name class TimeSheet(models.Model): employees = models.ManyToManyField(Profile) emp_name = models.CharField(max_length=100, default='emp_name') date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.emp_name + ' ' + self.project.project_name +' '+ str(self.date) views.py def edit_timesheet(request): if request.user.is_authenticated: if request.method == 'POST': timesheet_id = request.POST.get('timesheet_id') timesheet = TimeSheet.objects.filter(id=timesheet_id)[0] timesheet.user = request.user.username timesheet.date = request.POST['date'] timesheet.start_time = request.POST['from'] timesheet.end_time = request.POST['to'] timesheet.project = request.POST.get('project_name') timesheet.save() username = request.user.username timesheets = TimeSheet.objects.filter(user=username) return render(request, 'accounts/timesheet.html', {'timesheets':timesheets}) else: timesheet_id = request.GET.get('timesheet_id') timesheet = TimeSheet.objects.filter(id=timesheet_id)[0] grace_days = datetime.datetime.now().date()-timesheet.date # if the requested timesheet's date to be edited is more … -
How to select a random image in a Django template?
I currently have an image in a Django template which I would like to choose randomly every time the page is loaded: <!--<img src="{% static 'images/640px-Waaah.jpg' %}"/>--> <img src="{% static 'images/Crying_Baby.jpg' %}"/> I've found some custom filters on Github for this purpose (e.g. random_image), but it seems to me like this should be possible using the built-in tags, in particular, the random filter. It would be something like {% with ['images/640px-Waaah.jpg', 'images/Crying_Baby.jpg']|random as crying_baby %} <img src="{% static crying_baby %}"/> {% endwith %} but I don't believe this is valid DTL syntax. Any idea how I would go about this? (By the way, the page is Django's default 404.html and is not passed any context, so I would prefer to do it by passing a list of baby images to the context). -
Django not changing password after using reset password
I am making a website and i have just added the forgot password from django.contrib.auth. Everything works well, but when I am redirected back to the login page, it does no effect and still uses the old password. Can anyone help me? Here is my urls.py: """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views from blog.views import register urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('blog.urls')), url(r'^accounts/login/$',views.login,name='login'), url(r'^accounts/logout/$',views.logout,name='logout',kwargs={'next_page':'/'}), url(r'^accounts/register/$',register,name='register'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^password_reset/$', views.password_reset, name='password_reset'), url(r'^password_reset/done/$', views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', views.password_reset_complete, name='password_reset_complete'), ] My models.py and forms.py for thepassword_reset reset are empty. If anyone needs any more code files, please comment. Thank you very much :) -
I cannot fetch the json data in android app from django rest framework
private void jsonParse() { String url = "http://127.0.0.1:8000/products/products/"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray(""); for (int i = 0; i < jsonArray.length(); i++) { JSONObject employee = jsonArray.getJSONObject(i); int id = employee.getInt("id"); String title = employee.getString("title"); String description = employee.getString("description"); String price = employee.getString("price"); mTextViewResult.append(title + ", " + String.valueOf(id) + ", "+price +"," + description + "\n\n"); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); mQueue.add(request); } } /* Api Root Productsview List Productsview List GET /products/products/ HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "title": "t-shirt", "description": "this is a good t-shirt", "price": "39.99" }, { "id": 2, "title": "Jeans", "description": "this is a jean", "price": "89.99" } ]`Api Root Api Root The default basic root view for DefaultRouter GET /products/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "products": "http://127.0.0.1:8000/products/products/" }` */ [ { "id": 1, "title": "t-shirt", "description": "this is a good t-shirt", "price": "39.99" }, { "id": 2, "title": "Jeans", "description": "this is … -
Django: Get LIST data from HTML without forms or models
I have an HTML page with a series of list items. I would like to be able to push a button, read the data in the list, and do a sort of transformation. I thought it would be rather like this example. However, this format uses the name attribute to get the data and neither a list or list item can have names! My HTML: <form action="{% url 'index' %}" method="POST"> {% csrf_token %} <ul id="myList"> <li id="myId1">First Item</li> <li id="myId2">Second Item</li> </ul> <button type="submit">Submit</button> </form> My python: def index(request): if request.method == 'POST': var = request.POST['myList'] print(var) return render(request, "test.html", {}) Is there a way to get items in a list? Additional Information: Current output is just None. I can grab data like text boxes just fine, those are named items. I have tried a few other suggestions, like var = request.POST.get('myList'), and even started dealing with forms and models but I could only grab data that was IN the model that way, not a <li>. -
I cannot fetch json data from django rest framework and use in android app
This is my rest api This is my json data This is my android code whenever i click on parse button nothing happen. -
Revealing Database Table Names on Django web application
I know this is a topic that has been discussed a lot. Considering a django application(using an angular ui-grid for an app), with default authentication, using Oauth2 and CSRF tokens for the forms, what's your opinion on displaying db table names in the javascript file? I know there shouldn't be a major issue, if all the security setup/configuration on the application is correct, I also see a lot of comments that say the same thing, but specify that if it's possible to never reveal table names. My main argument to use the same table field names is to follow DRY, since i already had to declare all fields in the angular ui-grid object, for sake of not rewriting code, i can just use a function to create an object ready to be inserted in the django model.. With the right security setup, Would you prefer writing less code without obscuring database table names or writing more code obscuring table names? -
DRF UPDATE user group
hi i have 3 kind of groups 1.users 2.superusers 3.admins a id is comming to server with post method i'm trying to change that id's user group to superuser i did like below but it dont work i have ok response but nothing will change ..how can i fix this? class PromotUserAPIView(APIView): permission_classes = [IsAdminUser] def post(self,request): #id = request.POST.get('id') id = request.data['id'] superuser_group = Group.objects.get(name="superusers") alice_group = User.groups.through.objects.get(id=id) alice_group.group = superuser_group alice_group.save() return Response("ok") -
Django rest swagger_auto_schema customize response body
I've overridden the list function from django rest viewset to customize the response body (it returned an json array, I wanted to return an object that contains the array) I want to put this response in swagger doc too! I use drf_yasg app in django. I've written this code: from drf_yasg.openapi import Schema, TYPE_OBJECT, TYPE_STRING, TYPE_ARRAY from drf_yasg.utils import swagger_auto_schema class StudentViewSet(viewsets.ModelViewSet): @swagger_auto_schema(responses={200: Schema(type=TYPE_OBJECT)}) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response({'students': serializer.data}) I don't know how to give my response object description to the Schema object. I've searched so much but I found nothing useful!