Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No revision info error when running manage.py in Django
I am currently working on a Django project and have run into the follow error whenever I run any of my manage.py commands: Revision invalid: Got "no revision info! Check GIT_DIR=/Users/brockherion/dev." The issue seems to have come out of nowhere as I was able to add projects to my Django app without it. I can still run all the manage.py commands, but everyone of them throw this error. I have tried a couple of things, including: Removing PIP packages (I though django-markdownx was the cause, but it still throws the error without it) Removing my local git repo and creating a new one Checking out a new GIT branch Creating a new Django project (Works for a few commands then starts throwing it again) Merging all my branches so they are up to date I can still run my Django app. This just more of an annoyance than anything else. Again, it ONLY happens when I run manage.py, so I'm not sure if it's a GIT or Django issue. -
How to set a default field in a serializer to be the same as another field in the same serializer?
I have a serializer like this class SomeSerializer(serializers.Serializer): id = serializers.UUIDField(required=False, default=uuid.uuid4) anotherId = serializers.UUIDField(required=False, default = ????) and i want to set field 'anotherId' same as 'id' by default. This is what I expect s = SomeSerializer(data={}). data = s.data data.id # return '56e34c58-be7d-4c7c-992a-43080faf5614' data.anotherId # return '56e34c58-be7d-4c7c-992a-43080faf5614' (as id) I tried to do it like here but it didn't work class SomeSerializer(serializers.Serializer): id = serializers.UUIDField(required=False, default=uuid.uuid4) anotherId = serializers.UUIDField(required=False, default = id.get_default()) How can this be done? -
Why do I get the following error attempting to install memcached in my django app?
I'm trying to add memcached to a django app . So I installed it using the command sudo apt get install memcached When I Attempt to check the install using memcached -vv I get the error can't run as root without the -u switch I'm not sure what this error means. I need to understand before I attempt to research solutions. -
How to recieve many to many field value in model viewsets and model serializer in django?
I have a simeple app with two models Post and Categories. A post will have three fields title, body and assigned categories which should be pre created. A user will create the categories first then create the post with the categories put in the assigned categories field. I am sending the values like this--> { "id": 5, "title": "title 1", "body": "body", "categories_assigned": [ { "id": 1, "name": "technlogy" } ] } but the more I try putting the dictionary in many to many field. I ony recieve the the values as a ordered dict in a array. [OrderedDict([('name', 'technlogy')])] I know i can put it in a for loop and subscript it using i["name"]...but it only gives me the name property. I want the unique id to add in that many to many field in case there are lot of category objects having the name = technology my serializers.py file--> class CategorySerilizer(serializers.ModelSerializer): class Meta: model = models.Category fields = ['id', 'name'] class PostSerializer(serializers.ModelSerializer): categories_assigned = CategorySerilizer(many = True) class Meta: model = models.Post fields = ['id', 'title', 'body', 'categories_assigned'] def create(self, validated_data): post = models.Post.objects.create(title = validated_data["title"], body = validated_data["body"]) print(validated_data["categories_assigned"]) for i in validated_data["categories_assigned"]: print(i["name"]) // 'technlogy' return … -
Django, URL dispatcher not working when using angle brackets to capture a value
core/settings.py INSTALLED_APPS = [ ... 'api.apps.ApiConfig', ... ] core/urls.py (app URL configuration) urlpatterns = [ path('api', include("api.urls")), ] api/urls.py urlpatterns = [ path("", views.index, name="API Overview"), path("establishment/<str:username>", views.get_id_establishment_auth, name="task-establishment"), ] api/views.py @api_view(['GET']) def get_id_establishment_auth(request, username): print(username) return HttpResponse('Success'); The above code will result a 404 page Page not found if i type http://127.0.0.1:8000/api/establishment/mark when mark is a path converter i cant get what is the problem but looks like the path converter is not working (str:username). -
(django) .update() not working inside class model
I have the following code but the .update() in remove_user_invite() isn't working, and no errors are being thrown. Does anyone know what's wrong or how I can fix this? Many Thanks! models.py class StaffProfile(Profile): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, db_index=True, related_name="staff_profiles", on_delete=models.SET_NULL) objects = CustomStaffProfileManager() def remove_user_invite(self): invites = StaffUserInvite.objects.filter(staff_profile=self, used_at=None, expires_at__gt=timezone.now()) invites.update(expires_at=timezone.now()) -
Client-side and server-side rendering of HTML page in a Django single page app
this question could be a duplicate but I have a specific use case. The app is a single page Django app. The user can choose from several options in a drop-down box. Depending on the choice, a few input boxes will need to be rendered. As an example, if the user chooses to order a pizza, the options in another drop-down menu should be related to the toppings whereas an order for drinks should provide options related to the type or brands. The resulting number of input boxes could be 5 with one option or 10 with a different option. I can think of rendering the page using JS or by using Python in the back-end. Because this app will be a commercial one, I do not need SEO as users need to log into the app first. I also want to minimize the amount of code that a competitor can 're-use' from my work. Will client-side rendering open up security problems? If not, is client-side the better way to go? -
Django migrations in a replication scenario
I have a bunch of apps written in Django on a Docker Swarm. Currently all are defined to have exactly one replica. They start up run their collectstatic and migrate commands of the entrypoint.sh files and exec Uwsgi. Now I need to replicate the tired old Django applications and I can't figure out how to approach it: There is hope that the first replica will "lock" - whatever the lock maybe - I was thinking maybe a select for update on the django_migrations table, but that does not seem to be the case - it would be perfect, since the second replica would have to wait for the first one to finish (?) Maybe I'm safe by default as one already executed ALTER TABLE will make the one run by the other replica fail - not perfect as the migration command will fail and bounce the container but at least would not wreck the database Maybe there is no way and I need to cut the migration task out of the replicated containers into a "administrative container" and then run it manually I can't find an documentation about it while I don't want to believe that Django (being so "big" … -
How can I use Django to pull data from one application using REST url and push data to other application
I'm new and still in learning the concepts of Django, I need to understand how can I use Django capabilities to pull data from one application using REST API url and push the data to second application using REST API url. REST API url for APP 1 - GET - http://fqdn:port/app1/rest/users REST API url for APP 2 - POST - http://fqdn:port/app2/rest/users/action/create Scenario: Whenever a data for users is added in Application 1 , Django call the REST API url of app 1 & push it to Application 2 for user record creation. Please suggest!! Thanks In advance -
Can i pass two model in class based view?
I have creating blog website. My page has 2 part one is post one is category. My view is class based view where is pass ListView. So i can pass one model name. Have there any way to pass two model through it... -
NoReverseMatch at /NewListing
I have a form on my webpage for users to create a new listing. The form loads up okay but on submission an error comes up: NoReverseMatch at /NewListing Reverse for 'listing' with keyword arguments '{'listing': None}' not found. 1 pattern(s) tried: ['(?P<listing_id>[0-9]+)$'] The form does save the new listing and update the homepage with the new listing but I would like that once the listing is submitted, the user is taken to the new listing page and I can't seem to get that to work without this error popping up. models.py class Category(models.Model): group = models.CharField(max_length=20) def __str__(self): return f"{self.group}" class Listing(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=64) price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="categories") def __str__(self): return f"Product: {self.title} \nDescription: {self.description} \nCurrent Price: £{self.price}\nImage: {self.image} \nCategory: {self.category}" forms.py class NewListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "price", "image", "category"] title = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'})) description = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'})) price = forms.DecimalField(label='Starting Bid Price (£)') image = forms.URLField(widget=forms.URLInput(attrs={'autocomplete':'off'})) views.py def listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) return render(request, "auctions/listingPage.html", { "listing": listing }) def newListing(request): if request.method == "POST": form = NewListingForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] price = form.cleaned_data.get('price') … -
How to save tag in django to my model using django-taggit
I dont know how to save tag to my model ,can you plz guide me to do this This is my model class publish(models.Model): Userid=models.ForeignKey(Userdata,on_delete=models.CASCADE) tittle=models.CharField(max_length=20) contend=models.TextField(max_length=20000) select_cat=models.CharField(max_length=30,default='Horror') tags=TaggableManager() def __str__(self): return self.tittle And this is my form class DisplayformNew(forms.ModelForm): CHOICES=(('Horror','Horror'),('Education','Education'),('Sports','Sports'),('Story','Story'),('Comic','Comic')) title=forms.CharField(label='Title',max_length=30) text= forms.CharField(widget=forms.Textarea(attrs={"rows":15, "cols":50})) sel_cat=forms.ChoiceField(choices=CHOICES,label='Select Catagoriy') class Meta: model=publish fields=['title','text','sel_cat','tags'] And this is my views def add_new(request): form=DisplayformNew(request.POST) if form.is_valid(): new_todo=publish(Userid=Userdata.objects.get(Email=request.user.email),tittle=request.POST['title'],contend=request.POST['text'],select_cat=request.POST['sel_cat'],tags=request.POST['tags']) new_todo.save() #form.save_m2m() context={'form':form} return render(request,'newpost.html',context) I cant save Tag to my model ,can anyone help me to solve this ...... I can save it from admin view but how to save from user interface -
Getting error during installation of virtual environment package in ubuntu
I am trying to install virtual environment in ubuntu but I am getting this error: karan@karan-HP-Notebook:~/Django_Applications/projects/project_1$ sudo apt-get install python3-venv Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: libpython3-stdlib python-pip-whl python3 python3-minimal python3.6-venv Suggested packages: python3-doc python3-tk The following NEW packages will be installed: python-pip-whl python3-venv python3.6-venv The following packages will be upgraded: libpython3-stdlib python3 python3-minimal 3 upgraded, 3 newly installed, 0 to remove and 330 not upgraded. Need to get 46.0 kB/1,425 kB of archives. After this operation, 1,671 kB of additional disk space will be used. Do you want to continue? [Y/n] y Err:1 http://in.archive.ubuntu.com/ubuntu artful-updates/main amd64 python3-minimal amd64 3.6.3-0ubuntu3 404 Not Found [IP: 2403:8940:3:1::f 80] Err:2 http://in.archive.ubuntu.com/ubuntu artful-updates/main amd64 python3 amd64 3.6.3-0ubuntu3 404 Not Found [IP: 2403:8940:3:1::f 80] Err:3 http://in.archive.ubuntu.com/ubuntu artful-updates/main amd64 libpython3-stdlib amd64 3.6.3-0ubuntu3 404 Not Found [IP: 2403:8940:3:1::f 80] Err:4 http://in.archive.ubuntu.com/ubuntu artful/universe amd64 python3.6-venv amd64 3.6.3-1ubuntu1 404 Not Found [IP: 2403:8940:3:1::f 80] Err:5 http://in.archive.ubuntu.com/ubuntu artful-updates/universe amd64 python3-venv amd64 3.6.3-0ubuntu3 404 Not Found [IP: 2403:8940:3:1::f 80] E: Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/p/python3-defaults/python3-minimal_3.6.3-0ubuntu3_amd64.deb 404 Not Found [IP: 2403:8940:3:1::f 80] E: Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/p/python3-defaults/python3_3.6.3-0ubuntu3_amd64.deb 404 Not Found [IP: 2403:8940:3:1::f 80] E: Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/p/python3-defaults/libpython3-stdlib_3.6.3-0ubuntu3_amd64.deb 404 Not Found … -
Why I can't add custom middleware?
I am trying to connect my custom middleware (using Django 1.8) by copying an example from the Django manual. class SimpleMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) return response But I get an initialization error. TypeError: __init__() takes exactly 2 arguments (1 given) What's the problem? -
What django do when allow_migrate() on a database router returns false?
I'm writing a DB router to control what should be or not applied on the DB, so, implemented allow_migrate(). Here is what I did: def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'django_q': return db == 'tasks' elif app_label != 'django_q': return db == 'default' I was expecting that when a router returns False, then an app wouldn't be applied on the current DB at all, it happened somehow, no tables were created, but, the entire app migration list is added to django_migrations table at the DB. I was expecting that when allow_migrate() return False, then Django won't add anything to current DB about this app, but if this behaviour is the expected, then, this is the same as migrate --fake, right? if this so, I prefer doing it manually for the other DB. I have done some research to see what is actually done when allow_migrate() returns False but got no luck. Thanks in advance. -
django @action decorator doesnt seem to work
Im trying to write simple crm rest api in django using viewsets, however when I use @action decorator to modify my database upon posting data, it doesnt seem to do anything class PurchaseViewSet(viewsets.ModelViewSet): queryset = Purchases.objects.all() serializer_class = PurchaseSerializer @action(detail=False, methods=['post']) def api_make_purchase(self, request): product = Products.objects.get(product_name = request.data['product_name']) product.product_stock -= int(request.data['quantity']) product.sold_units += int(request.data['quantity']) product.save() return Response({'done': True}) when I query back after posting into purchases table, the product stock still stays at previous values, I dont get the response from api_make_purchase function either -
How to customize in django-rest_framework-knox LoginView
hi i am trying to create login api which will give me extra output fields by default knox login is giving 'expire' and 'token' but i want to add other values too for example it is giving me : { "expiry": "2020-10-02T17:00:22.906891Z", "token": "2a6d73cf85f3f15d855ab0386db7fcf4342167ab3d47e1d0983a775c120ff267", } ``` but i want to extra values too like : { "expiry": "2020-10-02T17:00:22.906891Z", "token": "2a6d73cf85f3f15d855ab0386db7fcf4342167ab3d47e1d0983a775c120ff267", "username" : "foo", "projects" :"["faa","fee","fuu"]", } my views.py is given below from django.shortcuts import render from .models import * from django.views.generic.edit import FormView from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def get_post_response_data(self, request): data def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] user_id_main=user.id user_name=user.username # projects_list=ProjectTable.objects.filter(id=Project_user_reletional_table.objects.filter(id=user_id)) # for a in projects_list: # print(a.name) # print(a.project_city) print(user_id_main,user_name) b=Project_user_reletional_table.objects.filter(user_id_id=user_id_main) for a in b: print(a.project_id) login(request, user) login_details=super(LoginAPI, self).post(request, format=None) return super(LoginAPI, self).post(request, format=None) please help me thanks … -
Is there a way to optimize the creation of users (that are also part of another model) in Django with just one request?
My app has Users that can be Doctors. To create a Doctor, therefore, I perform two POST requests: one for the creation of a User and one for a Doctor. The way I do this, the User has to be created first so that I can later create the Doctor (Doctor requires a 'User' field). class User(AbstractUser): ROLES = ( ('d', 'Doctor'), ('s', 'Secretary'), ('p', 'Patient'), ) role = models.CharField( max_length=1, choices=ROLES, blank=True, default='p', help_text='Role') class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... Since I'm new to Django, I don't know if two requests is the de facto way of creating this User/Doctor. This comes to mind as I am also thinking of the GET methods which will I'll need to perform later on (two requests when a Doctor logs in if I want to retrieve all of their info?) I read about subclassing, which would be something like Doctor(User), then the only necessary request would be a single POST to create a Doctor (which would alongside create the User). I am, however, skeptical of subclassing the User as I read at least 3 SO answers stating it could cause problems in the future. -
can't run as root without the -u switch
I'm trying to add memcached to a django app to help with speed issues. So I installed it using the command sudo apt get install memcached Then I attempted to see if it was installed by using the command memcached -vv I get the error can't run as root without the -u switch I'm not sure what this error means. I need to understand before I attempt to research solutions. -
Django REST Framework share class instance between files
I have some code in my apps.py's ready() method that loads some Oauth providers using the authlib module. Basically I am doing this: oauth = OAuth(fetch_token=fetch_token) allproviders = OauthProvider.objects.all() for provider in allproviders: oauth.register( name=provider.name, client_id=provider.client_id, client_secret=provider.client_secret_decrypted, access_token_url=provider.access_token_url, access_token_params=provider.access_token_params, authorize_url=provider.authorize_url, authorize_params=provider.authorize_params, api_base_url=provider.api_base_url, client_kwargs=eval(provider.client_kwargs), ) #here it saves to caches which is caches['default'] (LocMemCache) cache.set('oauth', oauth) # Uncommenting the following line gives a stack overflow # cache.get('oauth') This registers some oauth credentials (info) that can be used using the oauth variable (for example oauth.get_authorization_url() which gets me the authorize URL for that Oauth Provider. Now, I have a lot of different files (I split my views.py into multiple files). How can I access this oauth variable in those files? I have tried with django caches, but then I get a weird overflow error when I try to access the variable. How would you recommend? -
JQuery script for only one checkbox selection at a time [duplicate]
I got my script and it works pretty well (as I planned), but only after complete document loading with all checkboxes. It looks like this: You can see it disables other checkboxes in required column. But here's the thing. I need to use this script when I creating my entriesm and at first loading my page with this entries look like this: And after adding new entries script already doesn't work. I think this is about AJAX page reloading, the script is doesn't react to AJAX and don't work as a result. $(document).ready(function () { $('.field-correct :checkbox').change(function() { var $check = $(this), $div = $check.parent(); if ($check.prop('checked')) { $('[name~="choice"], [name$="correct"]').each(function() { if (!$(this).is(':checked')) { $(this).prop('disabled', true); } }); } else { $('[name~="choice"], [name$="correct"]').each(function() { if (!$(this).is(':checked')) { $(this).prop('disabled', false); $(this).css('background-color', 'red'); } }); } }); }); What should I do to make my script work with AJAX too? upd: here's html -
DJANGO with docker and postgresql
I'm novice in docker, and playing around docker to learn it more. Here is my Dockerfile FROM python:3.8.3-alpine #set the working directory for the container WORKDIR /user/src/app/ #set the env variables ENV PYTHONBUFFERED=1 ENV PYTHONWRITEBYCODE=1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install psycopg2-binary RUN apk add zlib-dev jpeg-dev gcc musl-dev #install pip for the docker image RUN pip install --upgrade pip #copy the requirement from local system to docker image inside /user/src/app/ COPY ./requirements.txt . RUN pip install -r requirements.txt #copy the complete project files after installing dependencies. COPY . . ENTRYPOINT ["/user/src/app/entrypoint.sh"] Second is entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $DB_HOST $DB_PORT; do sleep 0.1 done echo "PostgreSQL started" fi # python manage.py flush --no-input # python manage.py migrate exec "$@" And the last one docker-compose.yml version: "3.8" services: db: image: postgres:12.4-alpine environment: - POSTGRES_DB=demo_1 - POSTGRES_USER=*** - POSTGRES_PASSWORD=*** volumes: - postgres_data:/var/lib/postgresql/data/ web: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/user/src/app/ ports: - "8000:8000" depends_on: - db env_file: - ./.env volumes: postgres_data: I'm able to run postgres and make the server up … -
Django connect to mysql
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'onlineCourse', 'HOST': 'localhost', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'root', } } I tried to connect mysql to django follow django tutorial but its not work when i press in commnadline python manage.py migrate so it report error like below. someone help me please FIELD_TYPE.JSON: 'JSONField', AttributeError: module 'MySQLdb.constants.FIELD_TYPE' has no attribute 'JSON' -
read Object from Django in Javascript
I have the following situation and I don't have any solution I have a array Object coming from Django and I read it in my index.html in this way: {% for feature in Features %}..code...{% endfor %} Now I need to assign these values to a array Object in javascript/jQuery. I tried in this way but is not working: <script> var myfeatures = [{% for feature in Features %}]; </script> Have anybody any idea about how to solve this problem? Thanks -
django.core.exceptions.ImproperlyConfigured: COMPRESS_ROOT defaults to STATIC_ROOT, please define either
when I try to run the migrations , I get the following error: File "/home/shree/Desktop/projects/Hackoctomber/CRM/venv/lib/python3.6/site-packages/appconf/base.py", line 102, in _configure value = callback(value) File "/home/shree/Desktop/projects/Hackoctomber/CRM/venv/lib/python3.6/site-packages/compressor/conf.py", line 111, in configure_root + 'STATIC_ROOT, please define either') django.core.exceptions.ImproperlyConfigured: COMPRESS_ROOT defaults to STATIC_ROOT, please define either I have checked settings.py and it is configured as follows: MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" STATIC_URL = "/static/" STATICFILES_DIRS = (BASE_DIR + "/static",) COMPRESS_ROOT = BASE_DIR + "/static/" I have also added following line, but it didn't help: STATIC_ROOT = "static" Django-CRM Here is the project Where and what should I configure?