Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pipenv modules not seen by Django manage.py
I just started working on a Django project. For virtual environment I am trying to use pipenv. Inside my working directory; First I created a virtualenv with $ pipenv install django $ pipenv install autoslug then activated it with $ pipenv shell After that, I started a Django project with $ django-admin startproject x Then I started an app within the project with $ django-admin startapp y Inside app y, I imported module "autoslug". I installed autoslug with $pipenv install django-autoslug When I try to make migrations with $ python manage.py makemigrations It gives an error no module named autoslug My virtualenv is activated and the module is installed inside it. Any help would be appreciated. Thanks! -
Django serializer read and write multiple model field with
How to read and write multiple models in Django rest framework Model Serializer. like I have created a user-create model view set API, for that, I create a Model Serializer. there I need to give multiple permissions. for that, I pass the user_permissions field with an array of permission's id. now, how can I define a field in the user Model Serializer that can create a user with this permission and then get the user with permission's data? class UserSerializer(serializers.ModelSerializer): class Meta: model = AbstractUser fields = "__all__" extra_kwargs = {'password': {'write_only': True},} extra_fields = ['user_permissions'] #view class RegistrationView(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = AbstractUser.objects.all() parser_classes = (FormParser, MultiPartParser) permission_classes_by_action = [IsAdminUser, ] def create(self, request, *args, **kwargs): response_data = super(RegistrationView, self).create(request,*args,**kwargs) return Response({"data": response_data.data}) request body { "username": "testuser", "email": "testuser@example.com", "first_name": "test", "last_name": "test", "password": "Abcd@123456", "user_permissions": [1, 2, 3, 4, 5] } required response { "id": 1, "email": "testuser@example.com", "username": "testuser", "first_name": "test", "last_name": "test", "is_superuser": false, "is_staff": false, "is_active": true, "date_joined": "2022-08-17T10:25:48.446821Z", "user_permissions": [ { "id": 1, "name": "Can add User", "codename": "add_user", "content_type": "account" }, { "id": 2, "name": "Can change User", "codename": "change_user", "content_type": "account" }, { "id": 3, "name": "Can delete User", "codename": … -
Django Template Language collapsed output
My template includes for loop and for each of iteration it decides does it create new messages container, just appends messages or closes container. room.html {% block body %} <div class="wrapper column"> <div class="content-container column"> <div class="leave row"> <div class="leave__container"> <a class="button-input button-pulse leave__button-pulse" href="{% url 'chat:index' %}">Leave</a> </div> {% if admin %} <div class="leave__container"> <input type="hidden" id="deleteUrl" data-url="{% url 'chat:delete_room' room_name %}"> <a class="button-input button-pulse leave__button-pulse leave__button-pulse_delete pointer">Delete</a> </div> {% endif %} </div> <div id="chat-log" class="chat column"> {% for chat in chats.all %} {% comment %} If user sent a message {% endcomment %} {% if chat.user_id == request.user.id %} {% comment %} If message first open container and messages {% endcomment %} {% if chat.user_id != chat.get_previous_user.id %} <div class="chat__container sender column"> <div class="chat__author">{{chat.user.username}}</div> <div class="chat__messages"> {% endif %} {% comment %} Message itself {% endcomment %} <div class="chat__message">{{chat.content}}</div> {% comment %} If message last then close messages and container {% endcomment %} {% if chat.user_id != chat.get_next_user.id %} </div> <div class="chat__posted">{{chat.timestamp}}</div> </div> {% endif %} {% comment %} If somebody else sent a message {% endcomment %} {% else %} {% comment %} If message first open container and messages {% endcomment %} {% if chat.user_id != … -
Why my product photo is not updating? But product title is updating
I have an update form to update information. Here problem is, product_title is updating but product_image is not working. Where is the problem that's for why the photo is not updating? views.py: def update_product(request,id): product = Products.objects.get(pk=id) form = update_product_info(request.POST or None, instance=product) if request.method == 'POST' and form.is_valid(): form.save() print(form.errors) messages.success(request,"Successfully product information updated.") return redirect("my_products") context = { 'product':product, "form":form } return render(request, "update_product.html", context) update form: class update_product_info(forms.ModelForm): class Meta: model = Products fields = ('product_title','product_image') widgets = { 'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'}), 'product_image':forms.FileInput(attrs={'class':'form-control', 'style':'font-size:13px;'}) } template: <form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <div class="d-flex align-items-center"> <button type="submit" class="btn btn-outline-dark ms-auto" value="Update" style="font-size: 13px;">Add</button> </div> -
can not send multiple select values to django view
I have a select and has multiple values but in backend knowledge_keywords list is empty knowledge_keywords = request.POST.getlist('knowledge_keywords') <div class="container"> <div class="input-group"> <span class="input-group-addon"> <input type="checkbox" class="form-check-input" name="key_words_check_box" value="1"> </span> <select class="hidden" id="keywords" name="knowledge_keywords" multiple="multiple" data-role="tagsinput"> </select> </div> </div> -
How can I build an authentication system with react,redux and django without using django default authentication?
I am building a web app in which I have a model in my Django which stores username, email, encrypted_password fields. Now I have asked to build an authentication system using this model with react. I can't use Django default user model. so, I am asking to you guys, can I do that in react with redux? I just want to get the Django API with password and email fields. Can I do my rest of the thing in react? if this is possible how can I do that? In short, I need to build an authentication system without using Django default users model or authentication system with react, redux? -
How to make a POST request in the ManyToManyField?
I have a UserAccess model which contains two user and articles fields. The articles field is ManyToManyField in relation to the Article model, so each user has the same list of articles associated with it. I want to change the is_blocked field using a POST request so that each article for each user is blocked individually. How to do it ? models.py class UserAccess(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, ) articles = models.ManyToManyField('Article') def __str__(self): return str(self.user) class Meta: verbose_name = "access" verbose_name_plural = 'access' class Article(models.Model): title = models.CharField(max_length=256) label = models.ImageField( upload_to='uploads/labels', blank=True, ) is_blocked = models.BooleanField(default=True) def __str__(self): if self.is_blocked == True: return f"‚{str(self.pk)}: {str(self.title)}" return f"{str(self.pk)}: {str(self.title)}" class Meta: ordering = ('pk',) verbose_name = "Article" verbose_name_plural = "Article" serializers.py class ArcticleSerializer(ModelSerializer): class Meta: model = Article fields = [ "pk", "title", "label", "is_blocked", ] class CurrentUserSerializer(ModelSerializer): class Meta: model = User fields = ["username"] class UserAccessSerializer(ModelSerializer): articles = ArcticleSerializer(many=True) user = CurrentUserSerializer(read_only=True) class Meta: model = UserAccess fields =[ "user", "articles", ] read_only_fields = ('created','updated') views.py class UserAccessViewSet(ModelViewSet): serializer_class =UserAccessSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): user = self.request.user return UserAccess.objects.filter(user=user) -
How can I install argon2 from terminal?
I'm having a problem with the use of Argon2PasswordHasher class from django.contrib.auth.hashers. I'm trying to study its function, starting from encode in a very basic use. When I try to install argon2 from the terminal with: pip install argon2 it shows me a lot of error: Collecting argon2 Using cached argon2-0.1.10.tar.gz (28 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: argon2 Building wheel for argon2 (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [39 lines of output] Warning: 'classifiers' should be a list, got type 'tuple' running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.10 copying argon2.py -> build\lib.win-amd64-3.10 package init file 'phc-winner-argon2_init_.py' not found (or not a regular file) running build_ext building '_argon2' extension creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\phc-winner-argon2 creating build\temp.win-amd64-3.10\Release\phc-winner-argon2\src creating build\temp.win-amd64-3.10\Release\phc-winner-argon2\src\blake2 creating build\temp.win-amd64-3.10\Release\src D:\VisualStudio\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DHAVE_CONFIG_H -Dinline=__inline -I./phc-winner-argon2 -I./phc-winner-argon2/src -I./phc-winner-argon2/src/blake2 -Ic:\OpenSSL-Win32\include -Iargon2-windows-stubs/include -IC:\Users\nicog\newApi\venv\include -IC:\Users\nicog\AppData\Local\Programs\Python\Python310\include -IC:\Users\nicog\AppData\Local\Programs\Python\Python310\Include -ID:\VisualStudio\VC\Tools\MSVC\14.29.30133\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\shared -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\winrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\cppwinrt /Tc./phc-winner-argon2/src/argon2.c /Fobuild\temp.win-amd64-3.10\Release./phc-winner-argon2/src/argon2.obj argon2.c D:\VisualStudio\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DHAVE_CONFIG_H -Dinline=__inline -I./phc-winner-argon2 -I./phc-winner-argon2/src -I./phc-winner-argon2/src/blake2 -Ic:\OpenSSL-Win32\include -Iargon2-windows-stubs/include -IC:\Users\nicog\newApi\venv\include -IC:\Users\nicog\AppData\Local\Programs\Python\Python310\include … -
How to format a number to a decimal in django template?
Hi I am trying to format a number (1999) in Django template to a decimal with 2DP, e.g. (19.99) <div class="card-body"> <p class="card-text">{{ object.max_price|stringformat:".2f" )} {{object.currency.id}}</p> <p class="card-text">{{object.min_price}} {{object.currency.id}}</p> <p class="card-text">-{{object.discount_percentage}}%</p> <p class="card-text">{{object.recommended_retail_price}} {{object.currency.id}}</p> </div> I get this error: TemplateSyntaxError at /products Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|stringformat:".2f" )} {{object.currency.id' Request Method: GET Request URL: http://localhost:8000/products?page=1 Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|stringformat:".2f" )} {{object.currency.id' I have also tried using floatformat and get a similar error: TemplateSyntaxError at /products Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|floatformat )} {{object.currency.id' Request Method: GET Request URL: http://localhost:8000/products?page=1 Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: ' )} {{object.currency.id' from 'object.max_price|floatformat )} {{object.currency.id' How is it possible to format an integer in Django jinja template as a decimal to 2DP? -
iam trying to create an API in python for hospital management system by using Flask
import time import pickle import os class Hospital: def init(self): self.sno=0 self.name='' self.age=0 self.sex="" self.email='' self.fname="" self.address="" self.city='' self.state='' self.height=0 self.weight=0 self.med='' self.bill=0 self.paymentmethod='' self.pno=0 self.bgroup='' self.dname='' def Input(self): self.sno=input("Enter Serial Number:") self.name=str(input("Enter Patient's Name:")) self.age=input("ENter Patient's age:") self.sex=str(input("Enter Patient's Sex(Male/Female): ")) self.fname=str(input("ENter Father's name:")) self.address=str(input("Enter Patient's Address:")) self.city=str(input("Enter Patient's City:")) self.state=input("Enter Patient's State:") self.height=input("Enter Patient's Height:") self.weight=input("Enter Patient's Weight:") self.bgroup=str(input("Enter Blood Group:")) self.dname=str("Enter Patient's Disease:") self.med=str(input("Enter Prescribed Medicine:")) self.email=str(input("ENter Patient's E-Mail:")) self.pno=input("Enter phone number:") self.bill=input("Enter Bill Amount:Rs.") self.paymentmethod=("Enter Payment Method(cash/cheque/card):") def Output(self): print ("Serial Number:-",self.sno) print("Patient's Name:-",self.name) print("Patient's age:-",self.age) print("Patient's Sex(Male/Female):-",self.sex) print("Father's name:-",self.fname) print("Patient's Address:-",self.address) print("Patient's City:-",self.city) print("Patient's State:-",self.state) print("Patient's Height:-",self.height) print("Patient's Weight:-",self.weight) print("Blood Group:-",self.bgroup) print("Patient's DIsease:-",self.dname) print("Prescribed Medicine:-",self.med) print("Patient's E-mail:-",self.email) print("Phone Number:-",self.pno) print("Bill Amount:-",self.bill) print("Payment Method:-",self.paymentmethod) ##functioning## import time import pickle import os def WriteHospital(): fout=open("Hospital1.DAT","ab") ob=Hospital() print("Enter Details::") ob.Input() pickle.dump(ob,fout) print("Record SAved") fout.close() def ReadHospital(): fin=open("Hospital1.DAT","rb") ob=Hospital() print("Hospital Details are::") while True: ob.Output() print except EOFErrortry: : fin.close def SearchHospitalSno(n): fin=open("Hospital1.DAT","rb") ob=Hospital() flag=False try: print print("/n Hospital Details Are:--") while True: ob=pickle.load(fin) if ob.Sno==n: ob.Output() flag=True break except EOFError: if not flag: print("/n") print("/n") print ("") print("") print("") fin.close def SearchHospitalEmail(n): fin=open("Hospital1.DAT","rb") ob=Hospital() -
Django - add to favourites button in ListView
I want to create add to favourites feature in ListView but I am struggling with passing product slug in each item. I have a table with the product name and Action (Add/Remove buttons). I want to allow users to add a specific product to favourites or remove it from there. models.py class Product(models.Model): [...] favourite = models.ManyToManyField(User, default=None, blank=True, related_name='favourite_product') slug = models.SlugField(unique=True, blank=True, max_length=254) views.py @login_required def products_in_favourites(request, slug): product = get_object_or_404(Product, slug=slug) added_to_favourite = False if product.favourite.filter(id=request.user.id).exists(): product.favourite.remove(request.user) added_to_favourite = False else: product.favourite.add(request.user) added_to_favourite = True context = { 'object': product, 'added_to_favourite': added_to_favourite, } if request.is_ajax(): html = render_to_string('favourite.html', context, request=request) return JsonResponse({'form': html}) class AddToFavourite(LoginRequiredMixin, ListView): template_name = "AddToFavourite.html" model = Product queryset = Product.objects.all() context_object_name = 'product_list' def get_context_data(self, **kwargs): context = super(AddToFavourite, self).get_context_data(**kwargs) product_item = get_object_or_404(Product, slug=self.kwargs['slug']) # how to pass slug of each product item here? added_to_favourite = False if product_item.cart.filter(id=self.request.user.id).exists(): added_to_favourite = True context['added_to_favourite'] = added_to_favourite AddToFavourite.html {% block body %} <section class="container"> <table class="table table-hover"> <thead> <tr> <th scope="col">Product</th> <th scope="col">Action</th> </tr> </thead> <tbody id="favourite"> {% for product in product_list %} <tr> <td>{{product.title}}</td> <td> {% include 'favourite.html' %} </td> </tr> {% endfor %} </tbody> </table> </section> {% endblock body %} {% block … -
Temporary Directory on Heroku with Django
On my django project I create a temporary directory, execute my code I need and every thing works great. When deploying on Heroku it just does not work anymore. I need to have a tempdirectory to run my process. After that my pdflatex file is saved in the database (works). It seems to be that a tmpdir is created, otherwise Heroku would not know the name of the directory. But maybe the directory is gone even before my process is over. What confuses me is that the structure of the path in local host looks quite different then in Heroku. I understand that each and every tempdir will have another name. But why is the structure with the directories different? Is it even possible to create temporary directory and work with them on Heroku? with tempfile.TemporaryDirectory() as tmpdir: print(tmpdir) process = subprocess.Popen( ['pdflatex', '-output-directory', f'{tmpdir}'], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) Print output in local host: /var/folders/b3/s6r951md2ps4332j54mkxknr0000gn/T/tmp0bqryfu_ Error output on Heroku server: this is the error message: [Errno 2] No such file or directory: '/tmp/tmpa65lghdx/texput.pdf' -
Issue installing uWSGI==2.0.19.1 on Mac M1 Monterey v12.5
Im having this error message that I dont know what to do ERROR: Command errored out with exit status 1: command: /Users/eingel.figueroa/Documents/Gitlab/practice/practice/test/bin/python3.10 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/kx/kbq3933x2tdgrwmw3wrcgvlc0000gq/T/pip-install-d3gcx0no/uwsgi_09432bb0c9b44a06af129191ab4686bd/setup.py'"'"'; file='"'"'/private/var/folders/kx/kbq3933x2tdgrwmw3wrcgvlc0000gq/T/pip-install-d3gcx0no/uwsgi_09432bb0c9b44a06af129191ab4686bd/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/kx/kbq3933x2tdgrwmw3wrcgvlc0000gq/T/pip-record-_2yqb6j2/install-record.txt --single-version-externally-managed --compile --install-headers /Users/eingel.figueroa/Documents/Gitlab/practice/practice/test/include/site/python3.10/uWSGI cwd: /private/var/folders/kx/kbq3933x2tdgrwmw3wrcgvlc0000gq/T/pip-install-d3gcx0no/uwsgi_09432bb0c9b44a06af129191ab4686bd/ Complete output (218 lines): /Users/eingel.figueroa/Documents/Gitlab/practice/practice/test/lib/python3.10/site-packages/setuptools/_distutils/dist.py:262: UserWarning: Unknown distribution option: 'descriptions' warnings.warn(msg) running install /Users/eingel.figueroa/Documents/Gitlab/practice/practice/test/lib/python3.10/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. warnings.warn( using profile: buildconf/default.ini detected include path: ['/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include', '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include', '/Library/Developer/CommandLineTools/usr/include', '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks'] Patching "bin_name" to properly install_scripts dir detected CPU cores: 8 configured CFLAGS: -O2 -I. -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -DUWSGI_HAS_IFADDRS -DUWSGI_ZLIB -mmacosx-version-min=10.5 -DUWSGI_LOCK_USE_OSX_SPINLOCK -DUWSGI_EVENT_USE_KQUEUE -DUWSGI_EVENT_TIMER_USE_KQUEUE -DUWSGI_EVENT_FILEMONITOR_USE_KQUEUE -I/opt/homebrew/Cellar/pcre/8.45/include -DUWSGI_PCRE -DUWSGI_ROUTING -DUWSGI_UUID -DUWSGI_VERSION=""2.0.19.1"" -DUWSGI_VERSION_BASE="2" -DUWSGI_VERSION_MAJOR="0" -DUWSGI_VERSION_MINOR="19" -DUWSGI_VERSION_REVISION="1" -DUWSGI_VERSION_CUSTOM="""" -DUWSGI_YAML -I/opt/homebrew/Cellar/yajl/2.1.0/include/ -DUWSGI_JSON -DUWSGI_JSON_YAJL -DUWSGI_XML -DUWSGI_XML_EXPAT -DUWSGI_PLUGIN_DIR=""."" -DUWSGI_DECLARE_EMBEDDED_PLUGINS="UDEP(python);UDEP(gevent);UDEP(ping);UDEP(cache);UDEP(nagios);UDEP(rrdtool);UDEP(carbon);UDEP(rpc);UDEP(corerouter);UDEP(fastrouter);UDEP(http);UDEP(signal);UDEP(syslog);UDEP(rsyslog);UDEP(logsocket);UDEP(router_uwsgi);UDEP(router_redirect);UDEP(router_basicauth);UDEP(zergpool);UDEP(redislog);UDEP(mongodblog);UDEP(router_rewrite);UDEP(router_http);UDEP(logfile);UDEP(router_cache);UDEP(rawrouter);UDEP(router_static);UDEP(sslrouter);UDEP(spooler);UDEP(cheaper_busyness);UDEP(symcall);UDEP(transformation_tofile);UDEP(transformation_gzip);UDEP(transformation_chunked);UDEP(transformation_offload);UDEP(router_memcached);UDEP(router_redis);UDEP(router_hash);UDEP(router_expires);UDEP(router_metrics);UDEP(transformation_template);UDEP(stats_pusher_socket);" -DUWSGI_LOAD_EMBEDDED_PLUGINS="ULEP(python);ULEP(gevent);ULEP(ping);ULEP(cache);ULEP(nagios);ULEP(rrdtool);ULEP(carbon);ULEP(rpc);ULEP(corerouter);ULEP(fastrouter);ULEP(http);ULEP(signal);ULEP(syslog);ULEP(rsyslog);ULEP(logsocket);ULEP(router_uwsgi);ULEP(router_redirect);ULEP(router_basicauth);ULEP(zergpool);ULEP(redislog);ULEP(mongodblog);ULEP(router_rewrite);ULEP(router_http);ULEP(logfile);ULEP(router_cache);ULEP(rawrouter);ULEP(router_static);ULEP(sslrouter);ULEP(spooler);ULEP(cheaper_busyness);ULEP(symcall);ULEP(transformation_tofile);ULEP(transformation_gzip);ULEP(transformation_chunked);ULEP(transformation_offload);ULEP(router_memcached);ULEP(router_redis);ULEP(router_hash);ULEP(router_expires);ULEP(router_metrics);ULEP(transformation_template);ULEP(stats_pusher_socket);" *** uWSGI compiling server core *** [thread 1][gcc] core/utils.o [thread 2][gcc] core/protocol.o [thread 4][gcc] core/socket.o [thread 3][gcc] core/logging.o [thread 6][gcc] core/master.o [thread 7][gcc] core/master_utils.o [thread 5][gcc] core/emperor.o [thread 0][gcc] core/notify.o core/utils.c:3676:6: warning: variable 'pos' set but not used [-Wunused-but-set-variable] int pos = 0; ^ 1 warning generated. [thread 1][gcc] core/mule.o [thread 2][gcc] core/subscription.o [thread 4][gcc] core/stats.o … -
how to start threads and wait for their end without blocking a Django server?
I have a problem with Django. I have a function that does heavy processing (dataframe manipulation). This task is executed after sending a form containing the necessary information to launch the processing which is heavy. I tried to create a thread for this function with Threading. The problem is that the process is well sent in background not to block the server except that an error appears. I think this error is normal. There are dash components (django-plotly-dash) that depend on the result of the heavy processing and since this heavy processing is sent in background django passes directly to the dash components that have no information to display and therefore returns an error. So I used Threading.join() to wait for the heavy processing to finish but it paralyzes the whole server. How can I avoid blocking the server and allow the user to navigate between pages without blocking the whole server because a heavy processing is in progress? Here is an example of execution : def read_csv(request): heavy_treatment(some_args) # <-- this block the server and return a dash componant return redirect(other_function_for_view) # <-- this loads the view containing the result of the heavy processing Then I decided to create … -
Looking up value in JSONField with unaccent and icontains
I have a Model with a JSONField: class MyModel(models.Model): locale_names = models.JSONField() The shape of the JSON Field is simple: keys are language codes (en, fr...) and values are translated strings. I'm trying to build a search query that does an unaccented icontains search on a translated value: MyModel.objects.filter(locale_names__en__unaccent__icontains="Test") This does not give the expected results, because Django interprets "unaccent" as a key to look up in the JSON, rather than the unaccent PostgreSQL function: -- Expected SQL query: something like SELECT "app_model"."*" ... FROM "app_model" WHERE UPPER(UNACCENT("messaging_blueprint"."locale_names" ->>'en')::text)) LIKE UPPER(UNACCENT('%Test%')) LIMIT 21 -- Actual SQL query SELECT "app_model"."*" ... FROM "app_model" WHERE UPPER(("messaging_blueprint"."locale_names" #>> ARRAY['en','unaccent'])::text) LIKE UPPER('%Test%') LIMIT 21 How can I tel Django to interpret __unaccent as the PostgreSQL function rather than a JSON path? -
How to access same uploaded file in memory throughout several different API calls in Django
I'm building a React/DRF app that should allow the user to upload an Excel file, then select a sheet from all available sheets in the file, and then select a column of data from the selected sheet before the processing of data takes place. I don't need to save down the file but only the final data that will be sent to the database. As there will be at least 3 separate API calls - upload file, selected sheet, select column - I'm wondering how to maintain access to that same file during the whole time in Django. Here's my frontend code: const DataProcessing: NextPage = () => { const [selectedFile, setSelectedFile] = useState<File>(""); const [isSelected, setIsSelected] = useState<boolean>(false); const [availableSheets, setAvailableSheets] = useState<Array<string>>([]); const [selectedSheet, setSelectedSheet] = useState<string>(""); console.log(availableSheets); console.log(selectedSheet); const changeHandler = (event: any) => { setSelectedFile(event.target.files[0]); setIsSelected(true); }; const handleSubmission = () => { const formData = new FormData(); formData.append("File", selectedFile); axios .post("http://localhost:8000/api/upload-file/", formData, { headers: { "Content-Type": "multipart/form-data", }, }) .then((response) => setAvailableSheets(response.data.available_sheets)) .catch((error) => { console.error("Error:", error); }); }; const handleSubmissionSheet = () => { axios .post("http://localhost:8000/api/selected-ar-sheet/", selectedSheet, { headers: { "Content-Type": "application/json", }, }) .then((response) => console.log(response)) .catch((error) => { console.error("Error:", error); }); }; … -
Use model method in class and override that method
I have a method called complete in my model, how can i use that in my class view, in my model method there is one parameter called person which is being passed i do not want my overriden method to use that parameter how can i acheive that. class Mymodel(models.Model): is_done = model.BooleanField() def complete(self, person): self.is_done = True self.save(update_fields=['is_done']) self.done_by.add(person) class MyView(SomeView): def complete_record(self): return Mymodel.complete(here it expects two arguments i need only self) and i want to get rid of self.done_by.add(person) in model's complete method -
problem while registering user in db django rest framework
hello i have a rest_framework project and this is the problem : and this is code (serializer and function in views.py) why username is like that? -
when using pipenv to create a virtual env I am getting this error
#Pipenv not working# ###when I try to use pipenv in my wsl shell this happens now! I have used pipenv in the past but all of for sudden today it isn't working. I tried uninstalling and reinstalling pipenv but it isn't working.### pipenv install django /usr/local/lib/python3.10/dist-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 0.1.43ubuntu1 is an invalid version and will not be supported in a future release warnings.warn( /usr/local/lib/python3.10/dist-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 1.1build1 is an invalid version and will not be supported in a future release warnings.warn( Creating a virtualenv for this project... Pipfile: /mnt/d/Projects/To-do-list/Pipfile Using /usr/bin/python3 (3.10.4) to create virtualenv... ⠸ Creating virtual environment...created virtual environment CPython3.10.4.final.0-64 in 445ms creator CPython3Posix(dest=/home/edzy/.local/share/virtualenvs/To-do-list-JHrSlGzr, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/edzy/.local/share/virtualenv) added seed packages: pip==22.2.2, setuptools==63.4.1, wheel==0.37.1 activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator ✔ Successfully created virtual environment!''' '''Traceback (most recent call last): File "/usr/local/bin/pipenv", line 8, in <module> sys.exit(cli()) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/cli/options.py", line 56, in main return super().main(*args, **kwargs, windows_expand_args=False) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "/home/edzy/.local/lib/python3.10/site-packages/pipenv/vendor/click/decorators.py", line 84, in new_func return … -
How to put csrf_token inside django form view
I am new in django and have faced a strange problem. If I create django template and insert {% csrf_token %} inside, it works well, but if I put @csrf_protect decorator to view, it gives me Forbidden 403 (CSRF verification failed. Request aborted). As I understand from django documentation, I can`t use both CsrfViewMiddleware and @csrf_protect. So here is the question: Is it possible to do csrf verification inside a view or should I always write templates in such situations? @csrf_protect def create_group(request): if request.method == "POST": Group.objects.create(**{key: request.POST[key] for key in request.POST}) return HttpResponseRedirect(reverse("groups:groups")) elif request.method == "GET": pass return HttpResponse(create_group_form) create_group_form = """ <form method="POST"> <label for="course">Course:</label><br> <input type="text" id="course" name="course"><br><br> <label for="length_in_months">Length in months:</label><br> <input type="number" id="length_in_months" name="length_in_months" min=1 max=12 required><br><br> <label for="price">Price:</label><br> <input type="number" id="price" name="price" min=1000 max=50000 required><br><br> <label for="number_of_students">Number of students:</label><br> <input type="number" id="number_of_students" name="number_of_students" min=3 max=30 required><br><br> <label for="lesson_duration">Lesson duration:</label><br> <input type="number" id="lesson_duration" name="lesson_duration" min=1 max=5 required><br><br> <label for="website">Website:</label><br> <input type="url" id="website" name="website"><br><br> <input type="submit" value="Submit"> </form> """ -
django email why should send both text and HTML versions of a message [duplicate]
This is an example of sending email from django document: from django.core.mail import EmailMultiAlternatives subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() why it sends both text and HTML versions of the message? I tried and send something else in text_content (like a digit or a letter ) and it still worked properly I can not get the role of text_content in this code -
Pass arguement to custom permision class in django
I have a custom permission class that extends the rest framework base permission. I am trying to pass an argument allowed_groups that will be a list of all the groups that have access to the particular view. This is my current custom permission implementation. class CustomUserPermisions(BasePermission): message = "Ooops! You do not have permissions to access this particular site" def has_permission(self, request, view): allowed_groups = [ 'group_hr', 'super_admin', 'employee'] user1 = Employee.objects.filter(user__email=request.user).first() user_groups = user1.user_group.all() for group in user_groups: if group.title in allowed_groups: return True return False I have tried adding an argument as follows. class CustomUserPermisions(BasePermission, allowed_groups): message = "Ooops! You do not have permissions to access this particular site" def has_permission(self, request, view): allowed_groups = [ 'group_hr', 'super_admin', 'employee'] user1 = Employee.objects.filter(user__email=request.user).first() user_groups = user1.user_group.all() for group in user_groups: if group.title in allowed_groups: return True return False but this is the error I am currently receiving. class CustomUserPermisions(BasePermission, allowed_groups): NameError: name 'allowed_groups' is not defined Is there a better way that I can do this? -
the password is not hashed when registering using AbstractBaseUser
I created expanded the base user using AbstractBaseUser created my UserManager and added it to the new user model. when registering with createsuperuser, everything goes fine, but if I manually create a user, his password is not hashed.\ managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username=None, email=None, phone=None, \ password=None, **extra_fields): """ Creates and saves a User with the given email and password. """ if not username: if not email and not phone: raise ValueError('The given email/phone must be set') if email: email = self.normalize_email(email) if not username: username = email user = self.model( email=email, username=username, **extra_fields ) if phone: if not username: username = phone user = self.model( username=username, phone=phone, **extra_fields ) if extra_fields.get('is_superuser'): user = self.model( username=username, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(username=username, email=email, password=password, **extra_fields) def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user( username=username, password=password, **extra_fields ) models.py from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser # from django.utils.translation import ugettext_lazy as _ from custumuser.managers import UserManager class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(verbose_name='username', … -
Django permissions and content_type objects after model deletion
When a Django model is deleted, its permissions and content_type objects related to it keep on existing, do they have any other purpose too? or should they have been deleted with the model? -
Using Tempfile as intermediate storage before uploading to model
My Django app takes the context file, and converts it into pdflatex file. The output directory is given as f'{current_path}/media/pdf'. Everything works as expected. rendered_file = template.render(context).encode('utf-8') process = subprocess.Popen( ['pdflatex', '-output-directory', f'{current_path}/media/pdf'], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_file) A problem arises when I try to run it on Heroku server. I use AWS S3 as storage. The file can not be saved with an url like this. But I need to use a model to upload the pdf file. This is the model: class pdfUploadModel(models.Model): auto_increment_id = models.AutoField(primary_key=True, default=True) image = models.ImageField(null=True, blank=True, upload_to="pdf/") As soon as the file is saved in my directory, I could upload it to the model. But as long as I can not save it in a directory, there is no way to upload it to the model. My idea is to use a temporary directory which will be created on heroku and deleted afterwards again. I do not know if this is the right approach, or if there is a more elegant solution to my problem. It would look something like this: with tempfile.NamedTemporaryFile() as name: rendered_file = template.render(context).encode('utf-8') process = subprocess.Popen( ['pdflatex', '-output-directory', ---tempdirectory--], #here should be the tempdirectory stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_file) with …