Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The current path, tags/linux/, didn't match any of these
Django 3.0.8 urlpatterns = [ path('tags/slug:tag', PostListView.as_view(), name="tags"), ] I load: http://localhost:8000/tags/linux/ Problem Page not found (404) Request Method: GET Request URL: http://localhost:8000/tags/linux/ Using the URLconf defined in pcask.urls, Django tried these URL patterns, in this order: tags/<slug:tag> [name='tags'] __debug__/ ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, tags/linux/, didn't match any of these. Could you help me understand why this url didn match? And how to cope with this? -
Wagtail Pages from Django Model/AdminModel
I can't seem to find any info on this, everything points to adding models to admin. I don't need that. What I am trying to do is probably pretty simple. I have a django model AdminModel called Location. I have 23 locations plugged into the model. I would like a page for each location, with data from the model used to populate each page, and a listing page. The locations make individual use of an inventory API and google places API. The keys are stored per location in the model, so if I can just get the pages stood up on my URL I have enough to populate them. If it is possible, I would like to generate them as wagtail pages, so I can make use of some fields for content not stored in the model per location page. I'd be happy if I could just get the pages generated from the model data though. I'll take a search term or a doc link. Like I said, my search terms are only finding AdminModel instructions. Any help is appreciated. -
how filter get data in django
I use below code, where I make a mistake? Template : <a href="/product/products_filter?product={{'carpet'|urlencode }}&selling={{ 'best_seller'|urlencode }}"> ** Views: ** def products_filter(request): product = request.GET.get('product') selling = request.GET.get('selling') products = Product.objects.filter(selling=selling) return render(request, 'product/products.html', {'products':products}) -
How can i use custom model permissions to check before displaying a viewset?
I'm quite new to Django rest framework and are struggling to use the custom model permissions to check if a user is allowed to access a certain endpoint. Whenever trying to access the endpoint i get the "You are not authorized to perform this action" message even though the user is a superuser and/or has been given all app permissions both to the group and/or user. Models.py class User(AbstractBaseUser, PermissionsMixin): """ User model which inherits AbstractBaseuser. AbstractBaseUser provides the core implementation of a user model. """ email = models.EmailField( _('email address'), unique=True, ) ... class Meta: ... permissions = ( ('has_users_list', 'Can list users'), ) Permissions.py class UserOrGroupPermission(BasePermission): def has_permission(self, request, view): user_permissions = Permission.objects.filter(user=request.user) group_permissions = Permission.objects.filter(group__user=request.user) # get required permissions variable from view required_permissions_mapping = getattr(view, 'required_permissions', {}) # determine if the required permissions for the particular request method required_permissions = required_permissions_mapping.get(request.method, []) if user_permissions or group_permissions in required_permissions: return True Viewsets.py class UsersListAPIView(generics.ListCreateAPIView): queryset = User.objects.all().order_by('id') serializer_class = UsersSerializer permission_classes = [UserOrGroupPermission] required_permissions = { 'GET': ['has_users_list'] } -
Import CSV to Django, save data and show results within template
I need your help with uploading data(CSV) to django app and save data to database. Also i want to show row wise results within the template. Attached is the page image for your reference. Please guide how can i implement the same.image -
Python Social Auth’s with custom UserManger is not showing fb info
i'm using Python Social Auth to log in with facebook, it was working fine when the user was created by django default user model but when i added my custom usermanager model no info about the user is showing on the profile.html page i have the data on the database i can read them on django administration panel so the problm is in rendring the data to the html page i think models.py class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username … -
Processing abandoned The video could not be processed - Youtube API?
I am uploading mp4 videos through my website using youtube data v3 api and the http post request looks like: access_token = request.session['access_token'] url = "https://www.googleapis.com/upload/youtube/v3/videos?part=snippet" payload = { 'snippet':{ "categoryId": "22", "description": "Description of uploaded video.", "title": "Test video upload." } } files = [ ('media_body', request.FILES['media_body']) ] headers = { 'Content-Type': 'video/mp4', 'Authorization': 'Bearer '+access_token, } response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text.encode('utf8')) context = { 'r': response } return render_to_response('dashboard/manage_content/youtube.html', context) And this is the response I get: { "kind": "youtube#video", "etag": "yS7DhsHOhsDM-vXZiGUmLXcKST0", "id": "dII224dYC2o", "snippet": { "publishedAt": "2020-07-03T12:11:43Z", "channelId": "UCmv2Sec30iBc13b7ntf93Ow", "title": "unknown", "description": "", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/dII224dYC2o/default.jpg", "width": 120, "height": 90 }, "medium": { "url": "https://i.ytimg.com/vi/dII224dYC2o/mqdefault.jpg", "width": 320, "height": 180 }, "high": { "url": "https://i.ytimg.com/vi/dII224dYC2o/hqdefault.jpg", "width": 480, "height": 360 } }, "channelTitle": "Nikhil Dhoot", "categoryId": "20", "liveBroadcastContent": "none", "localized": { "title": "unknown", "description": "" } } } But on the videos tab, I get the error: Processing abandoned The video could not be processed. The fact that the video responds a success message means that all the authentication process before it has been successful. However, if required I can edit and share that code too. -
Customize the inbuilt django model form
I am working on django model forms with ajax where I have three dependent dropdown options. I want to customize the default value in django model form with an input of foreign key with dropdown select option of '---------' I want to replace that with a text that acts as a 'label'. Here is my image. I want to have something that would show as below if I used html form select: <select id="cars" name="cars"> <option selected disabled hidden value="">Cars</option> # Value that would act like this one <option value="toyota">Toyota</option> <option value="fiat">Fiat</option> <option value="audi">Audi</option> </select> -
converting string of html to it's original form in django admin
In models.py description = models.RichTextField In admin.py list_display = ['description'] I admin panel description is displayed like this : bold description: adding a description expected is this: bold description: adding a description beginner in Django assistance in this would be appreciated -
Render a django-simple-history query in a django-tables2 table
I try to render a django-simple-history queryset in a django-tables2 table. At the moment I pass the raw queryset to the template inside the context. Further I want to pass the Queryset to a Table object to use the features of the table like linkyfy columns or exclude columns. For this I have to specify a model inside the tables meta. The problem here is, that the model for the history is generated automatically. Actually code: #views.py from .tables import HistoryTable class HistoryView(LoginRequiredMixin, SingleTableView): template_name = "funkwerkstatt/history.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["table"] = Device.history.filter(id=self.kwargs["pk"]) ## futur code #context["table"] = HistoryTable(Device.history.filter(id=self.kwargs["pk"])) return context #tables.py import django_tables2 as tables class HistoryTable(tables.Table): device = tables.Column(accessor="device", linkify=True) class Meta: model = # HistoryModel?! empty_text = "No entry" exclude = ["id",] Is there a way to referent the auto generated HistoryModel -
Failing to install psycopg2-binary on new docker container
I have encountered a problem while trying to run my django project on a new Docker container. It is my first time using Docker and I can't seem to find a good way to run a django project on it. Having tried multiple tutorials, I always get the error about psycopg2 not being installed. requirements.txt: -i https://pypi.org/simple asgiref==3.2.7 django-cors-headers==3.3.0 django==3.0.7 djangorestframework==3.11.0 gunicorn==20.0.4 psycopg2-binary==2.8.5 pytz==2020.1 sqlparse==0.3.1 Dockerfile: # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . # set project environment variables # grab these via Python's os.environ # these are 100% optional here ENV PORT=8000 ENV SECRET_KEY_TWITTER = "***" While running docker-compose build, I get the following error: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the … -
Mypy complains about TestCase attributes set in setUpTestCase
I have a project written in Django (Django 3.0, Python 3.8), using django-stubs to handle type annotations. Everything went fine until I wrote some tests: from django.test import TestCase class TestSomething(TestCase): @classmethod def setUpTestData(cls): cls.some_value = 'foo' cls.another_value = 'bar' def test_me(self): self.assertNotEqual(self.some_value, self.another_value) When I run mypy, it raises '[attr-defined]' errors about the TestCase class attributes defined in setUpTestData: $ mypy --show-error-codes . my_app/tests/test_something.py:6: error: "Type[TestSomething]" has no attribute "some_value" [attr-defined] my_app/tests/test_something.py:7: error: "Type[TestSomething]" has no attribute "another_value" [attr-defined] my_app/tests/test_something.py:10: error: error: "TestSomething" has no attribute "some_value" [attr-defined] my_app/tests/test_something.py:10: error: error: "TestSomething" has no attribute "another_value" [attr-defined] I cannot find any advice about type annotations in tests (even tests in general, not to mention Django or unittest tests specifically). I don't think I am using setUpTestData to do anything it is not supposed to do, so I wonder why nobody reported such issues before. My main question is: How can I annotate this code to make mypy satisfied? A corollary question: Does it even make sense to add type annotations in tests? Maybe I should just configure mypy to ignore test modules? Here's the mypy.ini file - I would rather not change the settings to be more lenient: [mypy] … -
How do I run tasks in the background using Django?
I have an end-point in Django which initiates a function which takes really long to complete. I don't want the request to wait until this function has been completed. def MyRequest(APIView): def get(self, request, *args **kwargs): a_functio_which_takes_really_long_time() return Response({"message" : "We're Working on it."}) I tried using asyncio with Django Asynchronous Support. Also tried python threading here. But all these are making the request to wait until the function is completed. I know that we can easily achieve this using Celery. But that approach would require me to use a message-broker such as Redis, RabbitMQ or any other similar servers which I'm not supposed to use. -
03/Jul/2020 17:11:09] "GET /reset_password/ HTTP/1.1" 302 0 / [03/Jul/2020 17:11:09] "GET / HTTP/1.1" 200 11603
How i put in success_url in below urls and how i solve error which is redirects on login page and not redirect reset_password.html and obtain 302 error can you tell me how i solve urls.py path('reset_password/', auth_views.PasswordResetView.as_view(template_name="reset/password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="reset/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="reset/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="reset/password_reset_done.html"), name="password_reset_complete"), ] reset_password.html <h3>Password reset</h3> <p>Forgotten your password? Enter your email address below, and we’ll email instructions for setting a new one.</p> <form method="post"> {% csrf_token %} {{form}} <input type="Submit" name="Send email"> </form> -
django-private-chat implementation
I'm trying to integrate a private chat feature i.e any registered user can chat with another registered user, in my web application. I'm using Vue.js on front end and django backend. I'm still new to websockects, channels etc. After a bit of searching I found django-private-chat package, but the documentation does not contain much information. I'm not able to wrap my head around on the implementation of this package with a web framework like Vue. I'm also using django rest framework. -
getting model objects based on a field that is foreign key to that model !! Read the content to understand what i am asking
check the current admin panel here So basically i have a job portal and an admin can create jobs on behalf of a employer so when a employer is chosen from employer drop down it should show option to choose employerspecific question below the employer field for the job .as the employerspecific question is not a foreignkey to job i not getting idea to inline . your help is appreciated. class AbstractQuestion(ModelTimeTrackerMixin): QUESTION_TYPE_CHOICES = ( ("multiple_choice", "Multiple Choice"), ("statement", "Statement"), ) type = models.CharField("Question Type", max_length=128, blank=False, choices=QUESTION_TYPE_CHOICES) question = models.TextField("Question", blank=False) additional = JSONField("Additional", blank=True, null=True) class Meta: abstract = True class IndustryLabel(ModelTimeTrackerMixin): name = models.CharField("Label Name", max_length=256, blank=False) description = models.TextField("Description", blank=True) class Meta: verbose_name = "industry Label" verbose_name_plural = "industry Labels" def __str__(self): return self.name class Job(ModelTimeTrackerMixin): JOB_STATUS_CHOICES = ( ("draft", "Draft"), ("published", "Published"), ("on_hold", "On Hold"), ("closed", "Closed"), ) JOB_EXPERIENCE_CHOICES = ( ("none", "No prior experience required"), ("lt_1y", "Less than 1 Year"), ("1y-3y", "1 to 3 Years"), ("3y-5y", "3 to 5 Years"), ("5y-8y", "5 to 8 Years"), ("gt_8y", "More than 8 Years"), ) company_name = models.CharField("Company Name", max_length=256, blank=True) description = models.TextField("Description", blank=True) designation = models.CharField("Designation", max_length=256, blank=False) status = models.CharField("Status", max_length=64, blank=False, choices=JOB_STATUS_CHOICES) experience = … -
wrong font in url query?
Cannot find information. I do queries to some web site..., but api_key seems in the wrong font format. I tried to use simple form: base_url = 'https://somesite.ru/' coding = urlencode({'api_key':entry_code}) actual = str('...&api_key={}'.format(..., coding)) url = '{}?{}'.format(base_url, actual) I tried to use a little more complicated approach: ... coding = urlencode({'api_key':entry_code}) ... I tried to urlencode whole phrase: actual = urlencode('...&api_key={}'.format(..., coding)) When I url encode whole phrase, on the place of spaces instead of & symbol it gives me %20 symbol and host responds that xml does not support this format. When I do urlencode only api_key or do simple str query, the host tells me that it cannot recognize api_key, and shows following: Wrong api_key (ЕЖЕВРРљРђ not found in database)... The site is on the Russian web (.ru), so as I understand api_key has to be in cyrrilic, I understand my font in code is in UTF-8... What to do here? How can I change my api_key to cyrillic? -
Multiple wsgi.mod on single apache
I have one django3 application on apache http://myapp.example.com For now it works, but I want to put second django3 application on the same server with Anaconda. Is it possible? if so , How should I set WSGIPythonPath and Alias /static/ for each application?? <VirtualHost *:80> ServerAdmin webmaster@dummy-host.example.com ServerName myapp.example.com DocumentRoot "/var/www/html/myapp/current/" ErrorLog ${APACHE_LOG_DIR}/myapp_error.log CustomLog ${APACHE_LOG_DIR}/myapp_access.log combined <Directory /var/www/html/myapp/current/> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /var/www/html/myapp/current/myapp/wsgi.py WSGIDaemonProcess py37 user=ubuntu group=ubuntu python-path=/home/ubuntu/anaconda3/envs/py37/lib/python3.7/site-packages </VirtualHost> LoadModule wsgi_module /home/ubuntu/anaconda3/envs/py37/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so WSGIPythonHome /home/ubuntu/anaconda3/envs/py37/ WSGIPythonPath /var/www/html/myapp/current/ <Directory /var/www/html/myapp/current> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> Alias /static/ /var/www/html/myapp/current/static/ Alias /media/ /var/www/html/myapp/current/media/ <Directory /var/www/html/myapp/current/static> Order allow,deny Allow from all </Directory> -
getting the full path of an url from django (not django template)
I'm a bit lost on getting the full path of an url from django. From questions such as this one i should be able to get the path using get_current_site, but it seems it is not supported anymore. In specificts I have the following urls.py: app_name = "core" urlpatterns = [ path("<str:model_string>/", tables_views.table_from_model, name="table_from_model"), With django template it would be easy to acces it: {% url 'core:table_from_model' mymodel %} However i need to acces from a python script. I can of course just write something like: http://127.0.0.1:8001/alert/ but then, the moment I go live, this method would fail (the url would not anymore be 127...). Is that solvable? Thanks -
insert "+" symbol into mysql database
I have a list of phone numbers in mysql database. The phone numbers are in "234808090987" format. I want to alter it to become "+234808980898" How do i alter the database to add the + symbol to each row. I have upto 1500 numbers in the database INSERT INTO aspilos_log(category2) VALUES ('2'); the above didn't work or is there a way i can add + symbol while printing the number from the database mydb = mysql.connector.connect( host="db", user="root", passwd="aspilos", database="aspilos_log", auth_plugin="mysql_native_password" ) mycursor = mydb.cursor() mycursor.execute("SELECT PHONE_NUMBER FROM category2") results = mycursor.fetchall() for i in zip(*results): number = list(i) print (number) i mean the output of the above is (23460798509004, 23480987666556, 23498077685449), Is there a way i can print it as (+2349084998883993, +23409878929888, +234576990046989) -
Heroku Django - Random connection issues to database
We have a Django app which is launching soon and we have been testing for weeks, an issue has arisen today randomly where the application throws an exception connecting to our AWS RDS MySQL instance. This has happened 4 times, and I can't reproduce - it seems random. OperationalError at /api/ourcall/ (2005, "Unknown MySQL server host 'ourdb.ffg4565ihqjpg1.eu-west-2.rds.amazonaws.com' (11)") I changed the server host above, but the error is that. The only change we made yesterday was to scale from 3 Dyno's to 5. I don't know if that is related or if it is a DNS/networking issue? I have contacted Heroku support but haven't heard back yet. Any help would be really appreciated -
Attempting to change pages without full reloading in django and javascript
I have tried to do something with django and javascript. So for example if I want to go to my "about" page from my "home" page, I only want to load the contents of the page. There are many similar elements in both pages (such as a header image and navbar) that does not need to be reloaded. I have already 80% achieved what I want, my code is below: javascript function loadcontent(url, classname) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // below changes the url to the new page window.history.pushState(url, url, url); var htmlres = document.createElement("div"); // get the html from the ajax response and then change the required parts. htmlres.innerHTML = this.response; document.querySelector(classname).innerHTML = htmlres.querySelector(classname).innerHTML; } } xhttp.open('GET', url, true); xhttp.send(); }; window.addEventListener("popstate", function(e) { window.location.reload(); } ); example link for about page <a onclick = "loadcontent('{%url 'about_page'%}', '.content')" id = 'About'>About</a> django views.py about page def about_page(request): if request.is_ajax(): return HttpResponse('mainsite/about_page.html') return render(request, 'mainsite/about_page.html') First of, I would appreciate feedback if this is actually a good idea or not. I have just started learning web programming and this is a mini-project of sorts. Secondly, my … -
Make website deployment as efficient as possible coming from django
I recently got obsessed with optimizing a website of ours for speed and resource efficiency. The site in question is currently developed in python django. I've came across https://github.com/the-benchmarker/web-frameworks, which lists django as a rather inefficient framework. Hence my question: Is it worth it to rewrite the site into an API in a faster language (say top 1: nim, httpbeast) and then just use vue.js to offload the rendering to the client? The site is getting a lot of traction and we need to save on servers. -
Do some operation in a django serializer?
I have created a serializer, which will just call some util functions, without doing anything else. Here is my serializer: class MySerializer(serializers.Serializer): member = serializers.IntegerField() class Meta: fields = ['member'] def validate_member(self, value): try: member = patients_models.Member.objects.get(id=value) except Member.DoesNotExist: raise exceptions.ValidationError('Member with given id not found') else: return member I just want to validate my data, and then call the utility functions by passing this member object, so which is the best place to call those functions? Or should I call it in the view itself? -
Djongo search error string with parentheses
I'm working on a website using Django template and MongoDB. I implemented a search but some items have parentheses in their fields. When I use contains or icontains function to search in the database, it throw me an error or doesnt find the item. For example, if I search "Test (test" it will throw a regular expression missing error. If I search "Test (test)" It won't find anything I manage to find that parentheses are not considered as string for mongo. I tried to escape parentheses with //( and //) but it doesn't work. I don't know what I can do. Thanks for your help