Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extract multiple start date and end date from a string in python?
I am making a resume parser but I want to know the years of experience of the person from the experience section and want results like if there are 3 years of experience is mentioned and there are 3 companies the person worked in those 3 years and there are the start and end date mentioned on all of them so is there any way to know this is the start date and this is an end date and also can I calculate the total years of experience mentioned in the experience section by adding all those ranges. Example field Experience AI and Machine learning Intern, Dawn DigiTech (04/2022 -present), ❖, This company digitally transform multiple front- and back-office business, processes, SCM, ERP and Manufacturing Excellence., -, SpiceJet(08/2020 - 10/2021), ❖, Leading Indian airlines company worked and Developedy of 30%, Machine learning Intern, TutorBin(02/2022 - 05/2022 ), ❖, Tutorbin is an integrated online tutoring platform serving as a one-stop, solution for students and online tutors. work on Ai and Machine learning, tasks provided by the client, 60%, This is the parsed experience section so in this I want to extract dates ranges which should know the start date and end … -
How to get VScode Integrated Terminal Virtual Environment working?
I have completed a few courses online in Python and recently started a new course in Django. Previously I always used a virtual environment but would activate the environment myself, but in the course I am working through via Code with Mosh he shows a way to have VSCode activate the environment automatically in the terminal. I tried to follow along but am having a hard time getting this to work. First I tried following Mosh’s steps by locating the virtual environment location in terminal on the Mac using: pipenv --venv and this returned the location as /Users/lewpiper/.local/share/virtualenvs/storefront-7UYLLetM on my Mac. I then tried to to use this in the command palette with bin/python on the end of the path in VSCode to select the python interpreter and it didn’t seem to work. It seems like it didn't create the VSCode folder or JSON file that I saw in the lessons I was watching. Then I tried to edit the workspace settings in VSCode and add the following "python.pythonPath": "/Users/lewpiper/.local/share/virtualenvs/storefront-7UYLLetM"to match the VSCode file structure and again I am running into it not launching the terminal window with the virtual environment activated. Now when I click play in VSCode I … -
Button to hide contents of divs does not work in Django project
I have a javascript file with the following function: function sw(cl, v) { var a = document.getElementsByClassName(cl); for (var i=0; i<a.length; i++) a[i].style.display = v; } In my html file there is the following code: <script src="sw.js"> </script> <button onclick="sw('c1', ''); sw('c2', 'None'); sw('c3', 'None');">show c1</button> <button onclick="sw('c1', 'None'); sw('c2', ''); sw('c3', 'None');">show c2</button> <button onclick="sw('c1', 'None'); sw('c2', 'None'); sw('c3', '');">show c3</button> <div class="c1"> <!-- content --> </div> <div class="c2"> <!-- content --> </div> <div class="c3"> <!-- content --> </div> I tried using the function in a separate html file and it works, so do the buttons. However, I tried using that in a Django project and the buttons do not work. The mouse cursor does not change when I hover over a button but the button's color changes. The divs contain Django commands such as {% include "file.html" %}. Why won't the code work properly in the project? For context, I am trying to write a User Interface selector. The buttons are supposed to change what style is displayed. -
Flask print dict in jinja template with multiple values
I have a python/dict/flask/jinja printout problem with a dict containing multiple values. Basically. specialDict = {} specialDict[key]= Value printing it with {% for key, Value in specialDict.items() %} <a href=story/{{Value}}> <p class="fs-6 1h-1"> {{ key }} </p> </a> </ul> {% endfor %} works fine. BUT newspecialDict = {} newspecialDict[key]= Value1,Value2,Value3 printing it with the same code {% for key, Value in newspecialDict.items() %} <a href=story/{{Value}}> <p class="fs-6 1h-1"> {{ key }} </p> </a> </ul> {% endfor %} fails with KeyError : "('value1'," which is close but not "value1" . I understand flask/jinja is trying to unroll something and fails. Since for some reason python accepts dicts with multiple values even if the internet says its always just pairs of key, value (just one) there must be a way to print all the values in the template as part of the loop. tried and failed with unexpected {%: ... {% for key, value in newspecialDict.items() %} {% for innervalue in value.items() %} ... -
The new url id is getting appended after the previous request's url
I'm making a get request in django using html form as: crud.html <form action="{% url 'crudId' id %}" method="get"> <div class="col"> <div class="form-group" style="width: 20%;margin-top: 5px"> <label for="name">Id</label> <input type="number" name="id" value="{% if data %}{{ id }}{% endif %}"> </div> <input type="submit" value="OK" style="width: 30%; margin-left: 40%"> ... my view for this: class CrudPageView(View): def get(self, request, id=1): # get the id from the page oid = id ... # some data and operation ... return render(request, 'crud.html', {'data': data, 'id': oid}) and in urls.py as : path('crud/', CrudPageView.as_view(), name='crud'), path('crud/id=<int:id>', CrudPageView.as_view(), name='crudId') ... so http://localhost:8000/crud/ does work as intended and shows the page with data of id = 1; when I input any id, it also works as intended and shows the data for that id, but the url is in the form http://localhost:8000/crud/id=1?id=5 and after another input it will be http://localhost:8000/crud/id=5?id=12 What am I doing wrong? -
How to solve (unix:/home/richard/www/firstsite.sock failed (13: Permission denied) while connecting to upstream)?
I am trying do do this tutorial in a CentOS 7: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-centos-7 I want to test a Django basic project with Nginx, uWsgi into a CentOS 7. But in the browser results this error: 502 Bad Gateway nginx/1.20.1 Error502 firstsite.ini [uwsgi] project = firstsite username = richard base = /home/%(username) chdir = %(base)/%(project)/Documentos/desenvolvimento/nginxteste/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 uid = %(username) socket = /home/richard/www/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true uwsgi.service [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/usr/bin/bash -c 'mkdir -p /home/richard/www/; chown richard:nginx /home/richard/www/' ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target nginx.conf # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 4096; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen 80; server_name … -
Populate data in pdf using django
I have to show a certificate in modal with the 2 option print and email. Certificate is pdf file i just need to fill two fields in the certificate user name and course name (which is coming from backend) how can I implement this in django? -
I cant donwload complete genome of Culex pipiens pallens of the ncbi by api(Entrez) : HTTP Error 400: Bad Request
I am a DawBio student, here is my question. Hola soy un estudiante de Dawbio aqui les va mi pregunta. I put you in a situation, I am trying to download the genbank if possible of the complete genome of Culex pipiens pallens from the ncbi but I get this error. the url of de ncbi. In the db variable that I sent in the fetch I already tried with nucleotide, genome, Gen etc. I thought that with assembly I would download it but no. When I run the download_genbank() function, I get the error: HTTP Error 400: Bad Request Los pongo en una situación, estoy tratando de descargar el genbank si es posible del genoma completo de Culex pipiens pallens del ncbi pero me sale este error. en la variable db que envio en el fetch ya probe con nuclotide, genome, Gen etc. pense que con assembly me lo descargaria pero no. Cuando ejecuto la función download_genbank(), aparece el error: HTTP Error 400: Bad Request this is the page: ncbi culex pipiens pallens complete genome from pathlib import Path from Bio import Entrez from Bio.Entrez.Parser import DictionaryElement, ListElement from Bio import SeqIO from Bio.SeqRecord import SeqRecord from typing import … -
Bootstrap tabs doesn't work with Django include option
I am working with bootstrap tabs in Django on page ps_tabs_capacity.html which extends the base.html . Inside ps_tabs_capacity.html there is tab I include another ps_capacity1.html which should display Charts.js charts with info from external database . ps_tabs_capacity.html: {% extends 'app_sins/base.html' %} {% load static %} {% block main%} <body style="background-color:RGB(244,246,249)" > <div class="container-fluid"> <br> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-bs-toggle="tab" href="#home">Home</a> </li> <li class="nav-item"> <a class="nav-link" data-bs-toggle="tab" href="#menu1">GnGp</a> </li> <li class="nav-item"> <a class="nav-link" data-bs-toggle="tab" href="#menu2">Menu 2</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div id="home" class="container tab-pane active"><br> </div> <div id="menu1" class="container tab-pane fade"><br> <h3>Menu 1</h3> {% include 'app_sins/ps_capacity1.html' %} </div> <div id="menu2" class="container tab-pane fade"><br> <h3>Menu 2</h3> </div> </div> </div> </body> {% endblock main%} in views.py I use two function (there are others, but not important here) ,first one is: def index(request): cursor1=connections['default'].cursor() cursor1.execute(attach) r1=dictfetchall(cursor1) ############################################################################### cursor2=connections['default'].cursor() cursor2.execute(gngp_ntp) r2=dictfetchall(cursor2) return render(request,'app_sins/ps_capacity1.html', {"all_post" : r1,"jokso" : r2}) and second one is: def ps_tabs_capacity(request): return render (request,'app_sins/ps_tabs_capacity.html', {} ) in url.py there are: path('sins/ps_tabs', views.ps_tabs_capacity, name='ps_tabs1'), path('sins/', views.index, name='index'), If I use only ps_capacity1.html with extension of base.html, everything is OK( got info from database, it works OK) but in bootstrap taps … -
local variable 'search_keyword' referenced before assignment
I have been working on a search form and it's giving me this error when i open the url or submit the form. I am watching a codemy django tutorial and the only thing that is different is that i have some code for pagination i don't know if that's what is affecting it. base.html <form method="post" action="{% url 'listing' %}" name="searchform"> {% csrf_token %} <div class="custom-form"> <label>Keywords </label> <input type="text" placeholder="Property Keywords" name="search_keyword" value=""/> <label >Categories</label> <select data-placeholder="Categories" name = "home_type" class="chosen-select on-radius no-search-select" > <option>All Categories</option> <option>Single-family</option> <option>Semi-detached</option> <option>Apartment</option> <option>Townhomes</option> <option>Multi-family</option> <option>Mobile/Manufactured</option> <option>Condo</option> </select> <label style="margin-top:10px;" >Price Range</label> <div class="price-rage-item fl-wrap"> <input type="text" class="price-range" data-min="10000" data-max="100000000000" name="price-range1" data-step="1" value="1" data-prefix="$₦"> </div> <button onclick="location.href='listing'" type="button" class="btn float-btn color-bg"><i class="fal fa-search"></i> Search</button> </div> </form> views.py def listing(request): if request.method == 'POST' and 'searchform' in request.POST : search_keyword = request.POST['search_keyword'] propertys = Property.objects.filter(name__icontains=search_keyword) p = Paginator(Property.objects.order_by('-listed_on'), 2) page = request.GET.get('page') propertys = p.get_page(page) nums = "p" * propertys.paginator.num_pages return render(request, 'listing.html',{'search_keyword':search_keyword,'nums':nums,'propertys':propertys}) -
Deploying a Django application to Heroku - No module named 'django_project.wsgi
I'm trying to deploy a django application but I keep getting this error: ModuleNotFoundError: No module named 'django_project.wsgi' In fact, here's the full log: 2022-05-13T14:52:06.436735+00:00 app[web.1]: Traceback (most recent call last): 2022-05-13T14:52:06.436735+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-05-13T14:52:06.436736+00:00 app[web.1]: worker.init_process() 2022-05-13T14:52:06.436736+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-05-13T14:52:06.436736+00:00 app[web.1]: self.load_wsgi() 2022-05-13T14:52:06.436737+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-05-13T14:52:06.436737+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-05-13T14:52:06.436738+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-05-13T14:52:06.436738+00:00 app[web.1]: self.callable = self.load() 2022-05-13T14:52:06.436738+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-05-13T14:52:06.436740+00:00 app[web.1]: return self.load_wsgiapp() 2022-05-13T14:52:06.436740+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-05-13T14:52:06.436740+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-05-13T14:52:06.436741+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-05-13T14:52:06.436741+00:00 app[web.1]: mod = importlib.import_module(module) 2022-05-13T14:52:06.436741+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-05-13T14:52:06.436742+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2022-05-13T14:52:06.436742+00:00 app[web.1]: ModuleNotFoundError: No module named 'django_project.wsgi' 2022-05-13T14:52:06.436801+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-05-13T14:52:06.442147+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-05-13T14:52:06.541420+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [4] [INFO] Shutting … -
TypeError: 'cached_property' object is not callable - DJANGO
i want change location upload to mp3. but when i clicked upload, it goes to txt folder. so i give location to mp3, but suddenly got error. is it my code is wrong? please check it : def homepage(request): if request.method == 'POST' and request.FILES['upload']: upload = request.FILES['upload'] fss = FileSystemStorage.location(location='/media/mp3/') file = fss.save(upload.name, upload) file_url = fss.url(file) return render(request, 'homepage.html', {'file_url': file_url}) return render(request, 'homepage.html') i also add settings.py : MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and here's my folder: -
Instruct WebApp using Django to run the code locally and return results
I am a newbie to web development and python scripts. I am learning to host python scripts using Django. I would like to know how to instruct Django to run the script locally instead of running it on the server. For e.g. User visits the web app > enters parameters and submits the form > script should run locally from the client machine and return results back on the web app. The purpose of my python script is to test the network port status locally on the user machine's private network and return the results. Appreciate your advise. -
Creating a Django Model for a recipe #3
Another follow up question to Creating a Django Model for a recipe #2. I've run into an error with the following code: class Ingredient(models.Model): '''All ingredients for any recipe or individual selection''' name = models.CharField(max_length=50) department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) def __str__(self): return self.ingredient class IngredientDetail(models.Model): '''A class to identify variable quantities of ingredients''' ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) quantity = models.CharField(max_length=1) class Meta: verbose_name_plural = 'Ingredient Details' def __str__(self): return self.quantity class Recipe(models.Model): '''A Recipe class to input new recipes''' recipe = models.CharField(max_length=50) ingredients = models.ManyToManyField(Ingredient, through=IngredientDetail) instructions = models.TextField(null=True) cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL) picture = models.ImageField(upload_to= 'media/', null=True, blank=True) def __str__(self): return self.recipe I've set it up this way to associate variable quantities of ingredients with multiple recipes. However, when I run this code, the following issue is identified by Django: grocery_lists.IngredientDetail: (fields.E336) The model is used as an intermediate model by 'grocery_lists.Recipe.ingredients', but it does not have a foreign key to 'Recipe' or 'Ingredient'. As you can see, there IS a foreign key to 'Ingredient', so I'm not sure whats wrong. -
.sock file dissapearing [Django + Nginx + Gunicorn]
When trying to setup my django project on an AWS EC2 (ubuntu), it appears that whatever I do my .sock file is being deleted almost instantly by itself. My structure: home/ubuntu/sites/myapplication/manage.py [Unit] Description=gunicorn daemon After=nextwork.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/sites/myapplication ExecStart=/home/ubuntu/.local/share/virtualenvs/myapplication-yDrKR6kT/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/sites/myapplication/myapplication.sock application.wsgi:application [Install] WantedBy=multi-user.target Below are the commands I've used in no particular order (Nginx can't find the .sock file so it must be gunicorn) sudo systemctl deamon-reload sudo systemctl restart gunicorn sudo systemctl start gunicorn sudo systemctl enable gunicorn After running sudo systemctl start gunicorn I can see the .sock file appear in my application directory, however 10 seconds later it dissapears. It also instantly dissapears if I run the enable command. Most suggestions I find tell me to restart gunicorn, which doesnt work in my case. (Neither does rebooting the server FYI) It could be a permission issue but then I don't understand why the .sock file appears shortly and then is removed seemingly automatically by the system. -
Configuring PostgreSQL schema for default Django DB working with PgBouncer connection pool
I need to set the default DB schema for a Django project, so that all tables of all apps (including 3rd party apps) store their tables in the configured PostgreSQL schema. One solution is to use a DB connection option, like this: # in Django settings module add "OPTIONS" to default DB, specifying "search_path" for the connection DB_DEFAULT_SCHEMA = os.environ.get('DB_DEFAULT_SCHEMA', 'public') # use postgresql default "public" if not overwritten DATABASES['default']['OPTIONS'] = {'options': f'-c search_path={DB_DEFAULT_SCHEMA}'} This works for a direct connection to PostgreSQL, but not when connecting to PgBouncer (to use connection pools), failing with OperatonalError: unsupported startup parameter: options". It appears PgBouncer doesn't recognize options as a startup parameter (at this point of time). Another solution to set the schema without using startup parameters, is to prefix all tables with the schema . To make sure this works for built-in and 3rd party apps too (not just my own app), a solution is to inject the schema name to db_table attribute of all models when they're being loaded by Django, using class_prepared signal, and an AppConfig. This approach is close to what projects like django-db-prefix use, only need to make sure the schema name is well quoted: from django.conf import … -
Django: how to count the ratings and reviews of a post using django?
i have a model course and i also have a model review and rating that allows users rate a particular course. now i want to count all the ratings on each course when i filter. NOTE: in the courses detail view i figured out a way to count the ratings like this rating_count = CourseRating.objects.filter(course=course, rating__in=["3.0", "4.0", "5.0"]).count(). This only worked in the detail view because i get the course first using course = Course.objects.get(slug=course_slug). Now i want to count the rating in course lists view, how can i do this while using filter? this is how the detail view looks like @login_required def course_details(request, course_slug): user = request.user course = Course.objects.get(slug=course_slug) reviews_count = CourseRating.objects.filter(active=True, course=course).count() rating_count = CourseRating.objects.filter(course=course, rating__in=["3.0", "4.0", "5.0"]).count() this is how the list view look like NOTE: this is where i want to count all the rating of each course def index(request): courses = Course.objects.filter(course_publish_status="published").order_by('?') -
Detect when user register/Login on Context Proccessor Django
I have to do some checks all the time with the context proccessor.The value must be 'True' as soon as the user logs in.But when navigating the site after logging in, the value should be 'False'. So it should be a one-time True result.I need to do this both for the login process and when registering.And I have to implement them with Context Proccessor in Django. How can I do that? def user_info(request): ctx = dict() user = request.user ... ctx["isRegistered"] = False ctx["isLoggedIn"] = False # if user register website, that moment 'request' : # ctx["isRegistered"] = True return ctx -
understanding try except python/django
I need your help with understanding try-except python/Django. so I have this function: def submit_dept_head_application(request, application_id): cv = request.FILES['cv'] letter = request.FILES['letter'] candidate_id = request.data['candidateId'] rank_id = request.data['requestedRankId'] application_state = { 'candidate_id': candidate_id, 'rank_id': rank_id, 'cv_filename': cv.name, 'letter_filename': letter.name, } creator = Profile.objects.get(user=request.user.id) department = creator.department applicant = Profile.objects.get(user=candidate_id) applicant_profile_id = applicant.id rank = Rank.objects.get(id=rank_id) try: application = Application.objects.get(id=application_id) # TODO - update application except Application.DoesNotExist: application = None if application is None: application = Application(creator=creator, applicant=applicant, desired_rank=rank, application_state=application_state, department=department ) application.save() create_application_directory(application.id) ApplicationStep.objects.update_or_create( application=application, step_name=Step.STEP_1, defaults={'can_update': True, 'can_cancel': True, 'currentStep': True} ) copy_to_application_directory(cv, application.id) copy_to_application_directory(letter, application.id) send_email(settings.SENDGRID_SENDER, ['xxxxxx@gmail.com'], 'new application submitted', 'new application submitted') return Response(application.id, status=status.HTTP_200_OK) right now what is happening is that if there is no open application I create a new one. what I'm trying to do is to add another check, which is Application.objects.filter(applicant=applicant_profile_id) so if I have an opened application for this candidate it won't get to the application.save() but it will send an error. i don't really know how to do so and that's where i need your help please :) -
DRF --405 Method not allowed for update operation
I have done this before and may be it did work properly that time but now suddenly it's not working as it's expected to be. The viewset.py: class ProfileViewSet(ModelViewSet): serializer_class = ProfileSerializer http_method_names = ["post", "get", "put", "delete"] queryset = Profile.objects.all() def get(self, request, format=None): users = Profile.objects.all() serializer = ProfileSerializer(users, many=True) return Response(serializer.data) def put(self, request, pk, format=None): snippet = self.get_object(pk) serializer = ProfileSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) full_name = models.CharField(_("Name of User"), blank=True, null=True, max_length=255) phone_number = PhoneNumberField() zip_code = models.CharField(_("Zip Code"), blank=True, null=True, max_length=255) def __str__(self): return self.user.username seralizers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' urls.py router.register("profile/<int:pk>", ProfileViewSet, basename="profile_each") whenever I hit in postman It says "405 Method not allowed". Am I missing anything here please? -
Django. How to get URL by its name?
I want to get url by name specified in urls.py. Like {% url 'some_name' %} in template, but in Python. My urls.py: urlpatterns = [ ... path('admin_section/transactions/', AdminTransactionsView.as_view(), name='admin_transactions'), ... ] I want to something like: Input: url('admin_transactions') Output: '/admin_section/transactions/' I know about django.urls.reverse function, but its argument must be View, not url name -
Speech recognition suddenly detects "at" instead of "@"
usually when I say "at" for mail name speech recognition detects "@", but today when ı try the program it shows "at" instead of "@" . How can I solve this problem? -
DJANGO custom import CSV
I have a model with multiple fields. I want to make an importer (possibly with the django import-export library) that only takes two fields and with that calculates the rest of the fields that the model has. I wanted to listen and ask if you know of ways to do this. Since the documentation does not mention much. Thank you all! -
Django project located out of Apache ServerRoot
Got some problems trying to include Django-app in my already configured httpd2 apache server. I'd successfully installed mod_wsgi and set some configuration using the deployment manual: https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/modwsgi/ I added the following settings in httpd.conf WSGIScriptAlias /djangosrv/ /app/djangosrv/djangosrv/wsgi.py WSGIPythonPath /app/djangosrv <Directory /app/djangosrv/djangosrv> <Files wsgi.py> Require all granted </Files> </Directory> The project has the following structure and runs the only app named 'searchpage' /app/djangosrv -- djangosrv -- searchpage The URLs defined in /app/djangosrv/djangosrv/urls.py : urlpatterns = [ path('searchpage/', include('searchpage.urls')), path('admin/', admin.site.urls) ] When I try to open http://localhost/djangosrv/ I get 404: Page not found (404) Request Method: GET Request URL: http://localhost/djangosrv/ Using the URLconf defined in djangosrv.urls, Django tried these URL patterns, in this order: searchpage/ admin/ The empty path didn't match any of these. And when I try to access http://localhost/djangosrv/searchpage/ I get: Forbidden You don't have permission to access this resource. How can I configure routing in Django-project to make it work with non-server-root URLs ? Should I use some extra directory settings in httpd.conf and configure mod_rewrite ? CentOS 8 Apache/2.4.37 python3-mod_wsgi-4.6.4-4.el8.x86_64 python3-django3-3.1.7-1.el8 Any help would be greatly appreciated! -
Django: (fields.E300) Field defines a relation with 'Class' model , which is either not installed, or is abstract
Class model is a foreign key in File model I have no idea what causes the error above,I searched it and it mostly occurs when working with models in different apps, but that is not case in this situation, since both models are in the same models.py file. models.py from asyncio.windows_events import NULL from http.cookiejar import FileCookieJar from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin, BaseUserManager class Class (models.Model): name=models.CharField(max_length=256); def __str__(self): return self.name; class File (models.Model): file=models.FileField(); name=models.CharField(max_length=255); class_name=models.ForeignKey(Class,on_delete=models.CASCADE) def __str__(self): return self.name; class Class (models.Model): name=models.CharField(max_length=256); def __str__(self): return self.name; class CustomUserManager(BaseUserManager,): def create_superuser(self,email,name,surname,password,**other_fields): other_fields.setdefault('is_staff',True) other_fields.setdefault('is_superuser',True) other_fields.setdefault('is_active',True) if other_fields.get('is_staff') is not True: raise ValueError('super user must be assigned to is_staff= True') if other_fields.get('is_superuser') is not True: raise ValueError('Super user must be assigned to is_super_user=True') return self.create_user(email,name,surname, password,**other_fields) def create_user(self,email,name,surname,password,**other_fields): if not email: raise ValueError(('You must provide an email address')) email=self.normalize_email(email); #for example ignore the case sensitivity user=self.model(email=email,name=name,surname=surname,**other_fields) user.set_password(password) user.save() return user; class NewUser(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True,default=NULL,) name=models.CharField(max_length=255) surname=models.CharField(max_length=255) is_staff=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_teacher=models.BooleanField(default=False) classes=models.ManyToManyField(Class) objects=CustomUserManager(); USERNAME_FIELD='email' REQUIRED_FIELDS=['name','surname','is_teacher'] def __str__(self) : return self.name class Request(models.Model): requested_class=models.ForeignKey(Class,on_delete=models.CASCADE) requesting_student=models.ForeignKey(NewUser,on_delete=models.CASCADE) def __str__(self): return self.requesting_student.name # Create your models here.