Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to authenticate the default and a custom User model parallelly?
Our project deems necessary the need for a custom PublicUser model. We need to preserve the default authentication for the /admin/ endpoint as well. In contrast, we'll have a public /public/login/ endpoint wherein we'd like to implement the aforementioned custom PublicUser model that we can we with the default authenticate(), login(), and logout functions. So, chronologically, the default User model must still work with the /admin/ endpoint; the PublicUser model must work with the /public/login/ endpoint. And, both the models must work with the default authentication(), login(), and logout() functions so as to manage public sessions with ease. Note: We do not want to change the default authentication model for the /admin/ endpoint. It must be separate. AUTH_USER_MODEL = "users.PublicUser" # Refrain from doing this Any suggestions on how to go about this? Thanks! -
Example for customizing the ignored pattern list in Django's collectstatic
Like other questions here, I want to ignore my .scss files when running collectstatic. But because I'm using Heroku, which runs a collectstatic automatically, I would rather customize collectstatic's ignore pattern list rather than change the management command. Django 2.2 provides a way to do this, as documented below: The default ignored pattern list, ['CVS', '.', '~'], can be customized in a more persistent way than providing the --ignore command option at each collectstatic invocation. Provide a custom AppConfig class, override the ignore_patterns attribute of this class and replace 'django.contrib.staticfiles' with that class path in your INSTALLED_APPS setting: from django.contrib.staticfiles.apps import StaticFilesConfig class MyStaticFilesConfig(StaticFilesConfig): ignore_patterns = [...] # your custom ignore list My problem is that, this being my first Django project, I don't quite know how to provide a custom AppConfig class (and diving into the AppConfig docs hasn't helped). I mean, should I add this class to a whole new app or use an existing one? Is this class going to be in a apps.py file? If so, what should be the best app to do so? So I'm asking if anyone could provide me with an example of the best practice. For reference, right now my app … -
Django Prefetch Related
I have complicated prefetch_related in django, for execute query, database only need 0.06s for 200 rows in each prefetch_related attribute but for execute all response it's need 60s, I think when I want to call attribute in , django requires searching 200 data in the list of result How to solve it? Thanks in advance queryset = Cart.objects.filter(deleted_at__isnull=True)\ .filter(status__in=['sent', 'inbound', 'outbound', 'finished'])\ .annotate(**self.get_annotated_fields)\ .select_related('agent', 'agent_buyer', 'agent__user', 'agent_buyer__user', 'invoice')\ .prefetch_related('cartdetail_set','cartdetail_set__transaction','cartdetail_set__product', 'cartlog_set','agentcost_set') -
How to provide access of special information page to specific users
I am building website using django/python. This website include some webpages (say P1 and p2) in which p2 is form which can be accessed by p1 and link to p1 will be given to specific users via email and messages. I want to prevent other than specific users to go on p1 page of site. consider the situation I have given the link to some user x1 he uses the link and read p1 page and fill form on p2 page now link should expire AND generally URL https://www.website.com/home/p1 should not be directly accessible if entered in browsers for any user. that will prefectly make those pages safe from access of other people. This is quite complex situation how django authentication should be used for it? (Please note that my website does not have single link pointing towards p1 or p2 just the generated link will be way to access p1 and then p2 through p1 can we generate link like that?) -
how to implement django oauth2 access token in react js for login
curl -X POST -d "grant_type=password&username=iamrraj&password=Rahul@1995" -u"yNI7J9nrxyAMBG9fpVSSqmYngIkl4aVH4AJqmcI3:yLXp34jUXiaMZsLnkctbikJiS8UwkC2fmzTf9W6IO5gSBlCAcv6rFwq003F4vDL9sFimInEEbYt4TeTmPtwT5YrEenSYMQsoRuFqUdK3BtykTrWnZAPQwWrqeyZ2CMrO" http://localhost:8000/o/token/ And here is react js code import { AUTH_LOGIN} from 'react-admin'; var _client_id = 'xxxxxxxxx'; var _grant_type = 'password'; export default (type, params) => { if (type === AUTH_LOGIN) { const {username, password } = params; let _data = "grant_type="+_grant_type+"&username="+username+"&password="+password+"&client_id="+_client_id const request = new Request('http://localhost:8000/api/ps/o/oauth/token/', { method: 'POST', headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded',}), body : _data, }) return fetch(request) .then(response => { if (response.status < 200 || response.status >= 300) { throw new Error(response.statusText); } return response.json(); }) .then(({ access_token }) => { localStorage.setItem('token', access_token); }); } return Promise.resolve(); How to implement this is login form i don't know i am knew in react js so i need help how to do this -
Django. If boolean true = redirect
I set up a redirect for objects in the directory. If there is a mark in the checkbox, it means a redirect to the category. But now I have all the objects redirected to a category. What am I doing wrong? In my models.py is_redirect = models.BooleanField('Redirect', default=False) In my views.py def kv(request, kv_id): kv = get_object_or_404(Objects, pk=kv_id) response = redirect('/category/') response.status_code = 301 context = { 'kv': kv } if Objects.objects.all().filter(is_redirect=True): return response else: return render(request, 'listings/product-templates/listing-kv.html', context) -
Django REST framework reset password confirmation not working
I am building a user authentication backend with djano using rest_auth and allauth. This is my api app's urls.py urlpatterns = [ path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path("account/", include('allauth.urls')), ] after running server, I am going to rest-auth/password/reset, type in the email and post. an error occurs saying: NoReverseMatch at /api/v1/rest-auth/password/reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. I found this SO question which helped: NoReverseMatch at /rest-auth/password/reset/ and after looking at the django REST framework official demo: https://django-rest-auth.readthedocs.io/en/latest/demo.html, I included other endpoints in my url.py as suggested: urlpatterns = [ # rest framework authentication: login/logout/signup etc ... path('rest-auth/', include('rest_auth.urls')), # url endpoint for registration path('rest-auth/registration/', include('rest_auth.registration.urls')), # url endpoint to confirm email for change of password path('password-reset/confirm', TemplateView.as_view(template_name="password_reset_confirm.html"), name="password-reset-confirm"), # url link to change password (sent via email) path('password-reset/confirm/<uidb64>/<token>/', TemplateView.as_view(template_name="password_reset_confirm.html"), name='password_reset_confirm'), # to handle different account emails (facebook, github, gmail, etc .. ) path("account/", include('allauth.urls')), ] where I also included my simple html landing page when resettinthe g password. This works. an email is sent with a confirmation link and the html pages load up. however after I confirm my email in my custom pages, the default page for the django REST … -
How to call function from another class file, while using "enque" in django+RQ?
I am using RQ for queue and jobs management in my Django project, Want to push some data in a queue. But it gives me an error, which is No module named 'myFolder.MyPythonFile.py' RQ is installed in my Django project. I am pushing queue from this file apps/queue/views/push_queue.py from jobs_folder.my_first_job import background_task job = q.enqueue(background_task, 'my_param') And I want to call a function which is located in this file jobs_folder/my_first_job.py import time def background_task(n): delay = 2 print("Task Runing") print(f"Simulationg {delay} second delay") time.sleep(delay) print(len(n)) print("Task Compelete") return len(n) Error is: jobs_folder not found, Because of this queue is not creating. from jobs_folder.my_first_job import background_task ModuleNotFoundError: No module named 'jobs_folder.my_first_job' I am not using Django-rq, I am using https://github.com/rq/rq -
cant display image in mamage.py in django
script website I am creating website using django but i m not able to see image on website -
How to use DRF Custom serializer field with DB model
I'm using relation database which is having Binary Field, So how can I use DRF serializer to save the field value I have referred the documentation https://www.django-rest-framework.org/api-guide/fields/#custom-fields and understood some of the part and created below, but I'm not sure how to use it in serializer Model class MyData(models.Model): data = models.BinaryField() Custom Field class BinaryField(serializers.Field): def to_representation(self, value): return value.decode('utf-8') def to_internal_value(self, value): return value.encode('utf-8') But how should I use this in my below serializer class BlobDataSerializer (serializers.ModelSerializer): class Meta: model = MyData fields = ('id', 'data') So basically I'm trying to store incoming data in binary field. Thanks in advance -
How to set ALLOWED_HOSTS Django setting in production when using Docker?
I always set my ALLOWED_HOSTS from an environment variable in Django. In my development .env I always set ALLOWED_HOSTS=.localhost,.127.0.0.1 and in production ALLOWED_HOSTS=mydomain.dom,my_ip_address Now I am currently getting acquainted with Docker, and the question is what is the value of the ALLOWED_HOSTS in production. Should it remain as localhost, since I understand localhost will refer to the host container or should I set it as my domain. I am using Nginx for reverse proxy to forward requests. -
Is there a function in Django that can be used for checking if an Oracle database is compressed?
I have read Django documents on databases and setting, but I haven't found a function that can be used for checking if my Oracle database is compressed. Any help? -
How to link Django 2.2.5 web framework to GitHub?
I have created a repository on GitHub and logged into my account on Pycharm Django settings. Currently I haven't had any luck with the terminal commands. I don't know if this is the right way to do things? Looks like I've tried commands that are for older versions of Django. git init -
Where in Django code put code disconnecting signal and doing monkey-patching?
I'm working on custom authorization backend for Django 2.2. I don't want django to update last_login for user so I wanted to disconnect signal user_logged_in from triggering update_last_login. I also have to do monkey patch in SimpleJWT library changing User to point OtherUserModel Where is the best place to put this code? For now, I have added in CoreConfig.ready method and it works but is it a good place for this logic? from django.apps import AppConfig class CoreConfig(AppConfig): name = 'core' def ready(self): from django.contrib.auth import user_logged_in from django.contrib.auth.models import update_last_login user_logged_in.disconnect(update_last_login, dispatch_uid='update_last_login') import rest_framework_simplejwt.state rest_framework_simplejwt.state.User = OtherUserModel -
Showing the uploaded csv file on Django template
I have a project that accepts an uploaded .csv file and shows it on the admin via the models.py. What I want to happen is to show these uploaded .csv file on the template. my views are: def data_upload(request): template = "home.html" if request.method == 'GET': return render(request, template) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a .csv file.') data_set = csv_file.read().decode('ISO-8859-1') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=','): _, created = Table.objects.update_or_create( page=column[0], keyword=column[1], interval=column[2], email=column[3], notes=column[4], billing=column[5], ) context = {} return render(request, template, context) The views are already working when I upload the .csv file. On the home.html file, this is what I did: <table class="table table-condensed"> <thead> <tr> <th>...</th> </tr> </thead> <tbody> <tr> <th class="center-align" scope="row"><i class="small material-icons green">check</i></th> {% for t in tables %} <td class="center-align">{{t.page}}</td> <td class="center-align">{{t.keyword}}</td> <td class="center-align">{{t.interval}}</td> <td class="center-align">{{t.email}}</td> <td class="center-align">{{t.notes}} </td> <td class="center-align">{{t.billing}}</td> {% endfor %} </tr> </table> How do I properly iterate on the template to show what I uploaded on my html file? -
Django runserver not running when importing another python file
I'm new to Django, so I am trying to import a python file in the views.py inside my Django app. When I run the server with python manage.py runserver it's not doing anything. When I comment out the import part it works for some odd reason I've already tried some solutions. Like: import [file] from . import [file] from .[file] import [function in the file] and all these still didn't work. DETAILS: -Python version 3.7.3 -Django version 2.2.5 CODE: Note: this is in views.py import bot def process(request): username = request.POST["username"] email = request.POST["email"] code = generate_code(random.randrange(5, 12)) data = {"username": username, "email": email, "code": code} bot.say("Hi", channel_id=600617861261819906) return render(request, "process.html", data) -
Unit Testing - Get Request that includes JSON-data
I´m currently creating Unit-Tests for existing endpoints. I have a GET-Request Endpoint to whom I send JSON Data is a kind of filter parameters. By using Postman everything works well. When I create the Unit-Tests the JSON Parameters are not used. In the documentation I saw that data in the request is send as Parameter in the URL. But that is not working for me. Thanks in advance! Checked the django documentation Views.py def get_queryset(self): return self.model.objects.filter( **{ field + '_id': self.request.data[field] for field in ['post', 'user', 'product'] if field in self.request.data } ).order_by( '-time_stamp' ) Unit Test response = self.client.get( "/api/v1/post/get_clicks_stats/", data={ "user": "5b1d4efa-09e1-4a29-ba50-314d34cd50f0", } ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['count'], 1) -
SQL script replace all id in data base
I have imported not correct data. All users in my data base have id with .0, for exaple user.id 123321.0. I need to replace all .0 from all database. I have writen script like this: UPDATE users_groups, user_synchronization, `user additional info`, major_minor, commitment, budget, users SET users_groups.user_id = REPLACE(users_groups.user_id, '.0', ''), user_synchronization.user_id = REPLACE(user_synchronization.user_id, '.0', ''), `user additional info`.user_id = REPLACE(`user additional info`.user_id, '.0', ''), major_minor.major_id = REPLACE(major_minor.major_id, '.0', '') AND major_minor.minor_id = REPLACE(major_minor.minor_id, '.0', ''), commitment.dealer_id = REPLACE(commitment.dealer_id, '.0', '') AND commitment.grower_id = REPLACE(commitment.grower_id, '.0', ''), budget.user_id = REPLACE(budget.user_id, '.0', ''), users.id = REPLACE(users.id, '.0', ''); but i have an error: Data truncation: Truncated incorrect DOUBLE value: 'D22203' -
Running manage.py shell with -c flag within docker-compose run
I want to run a script that runs Django code in my docker container. My initial plan was to run the following: docker-compose run web python manage.py -c "import django; print(django.__version__)" However, that isn't working: it prompts manage.py shell: error: unrecognized arguments. I guess it has to do with the fact that -c is a flag shared both by manage.py and by bash, or at least that's what I gathered from the docker-compose docs and Django's. If I run docker-compose run web bash, it prompts the shell, where I can do python manage.py shell -c "...". How can I do that in just one step? Any help is much appreciated. -
Getting Check that 'apps.ChatbotConfig.name' is correct. after restructuring
I changed my project's structure adding everything in a src folder, but my server stopped working. The error i'm getting is : Cannot import 'chatbot'. Check that 'apps.ChatbotConfig.name' is correct I tried looking for an answer, and most of the suggest to change apps.py to name = 'src.chatbot', but that didn't work for me. Tried changing the apps.ChatbotConfig.name but if change anything, it says no Module named 'chatbot'. Here is my structure. base.py DJANGO_APPS = [ "apps.ChatbotConfig", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "django.contrib.messages", # "django.contrib.humanize", # Handy template tags "django.contrib.admin", "debug_toolbar", 'django.contrib.staticfiles', ] apps.py from django.apps import AppConfig class ChatbotConfig(AppConfig): name = 'chatbot' admin.py from django.contrib import admin from django.apps import apps app = apps.get_app_config('chatbot') for model_name, model in app.models.items(): admin.site.register(model) Full traceback Traceback (most recent call last): File "C:\Users\lbajarunas\virtualenv\lib\site-packages\django\apps\config.py", line 143, in create app_module = import_module(app_name) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'chatbot' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "C:\Users\lbajarunas\virtualenv\lib\site-packages\django\core\management\__init__.py", line … -
django: How to render CharField as right to left?
In my app froms.py I defined my textfield as: class ContactForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'نام' } )) but as it can be seen in the screenshot, the text of placeholder and the actual text (that user would add) is being rendered left to right. How can I make it to render in right to left form? -
Effective ways of reusing python-request in function for internal api calls
I'm using python request lib for internal calls in our Django app. we have many helper functions for such internal calls. The problem with this approach is we are repeating the same function for different internal calls. Differences being request_url, request_data, request_response(tuple/list/dict). We are using the following function for internal calls, the same function is used for different calls based on the difference in input data, URL and response. for ex: get_data_from_service1, get_data_from_service2 etc def get_data_from_service(data): request_url = BASE_URL + "api/post/service/" request_data = rqt.get_service_request_translator(data) try: request_response = requests.post(url=request_url, data=request_data) except requests.exceptions.RequestException as ex: logger_excp.exception(str(ex)) return error_msg.UNABLE_TO_REACH_SERVICE if request_response.status_code == 200: models_data = request_response.json().get("data") total_count = request_response.json().get("total_count") return models_data, total_count elif request_response.status_code == 500: logger.error(request_response.text) return error_msg.PROBLEM_WITH_SERVICE else: logger.error(request_response.text) return error_msg.SOMETHING_WENT_WRONG please help with the following points. What would be an effective way of not repeating function everywhere should something like a base class be used? How to handle timeouts at global(base class/factory function?) and local functions? for ex: a base class/function having a timeout of say timeout=5 while local function having a timeout of timeout=2 or no timeout at all. how to change the error response of such functions. say for example if I want to raise an exception instead … -
Creating a control number for controlling a post
I want to create a control number that will be controlling every post posted by user, every time a user post in the site control number should be attached in the database in each post. Same number will be used for mobile payment, once user has payed using control number post will be deleted I want to use primary key to generate numbers but I get error named "1091, "Can't DROP 'id'; check that column/key exists"" views.py @login_required def Claim(request): max_val = Documents.objects.aggregate(max_no=Max('pay_no'))['max_no'] or 0 # then just make new object, and assign max+1 to 'that_field_in_question' control_number = Documents(pay_no=max_val) control_number.save() return render(request, 'loststuffapp/claim.html', context={'documents':Documents.objects.all()}) models.py class Documents(models.Model): docs_name = models.CharField(max_length=200) item_type = models.CharField(default="", max_length=100 ) police_station = models.CharField(max_length=255,) phone_no = models.CharField(max_length=10, blank=False, validators=[int_list_validator(sep=''),MinLengthValidator(10),]) date = models.DateTimeField(default=timezone.now) Description = models.TextField(blank=True, null=True) pay_no = models.IntegerField(default=11001, primary_key=True) publish = models.BooleanField(default=False) image = models.ImageField(upload_to="Documents",blank=False) """docstring for Documents""" def __str__(self): return self.docs_name -
Django query OneToMany by multiple fields
I have schema similar to this one (obviously this one is simplified) class Pet(models.Model): name = TextField() date_vaccinated = DateTimeField(null=True) # null indicates no vaccination owner = ForeignKey(Person, related_key="pet") class Person(models.Model): name = TextField() people_with_a_vaccinated_pet_named_rex = Person.objects.filter(pet__date_vaccinated__isnull=False, pet__name="Rex") As indicated in the last line I'm trying to find all people who have a pet called Rex that is also vaccinated. The query I wrote will find all people with a pet named rex, and a vaccinated pet (not necessarily the same pet..) Is there a way to query with multiple conditions on the same OneToMany relation? P.S the real query I'm trying to write is more similar to the following: Person.objecs.filter(pet__class1__date__isnull=False, pet__class1__class2__class3__name="blabla") where I want to reach class 3 only through class1 instances that their date is not null -
how to pass default value from database to mapfield panel in wagtail
This is my code.zoom_level is a column in my model, so i want to pass the respective value as default zoom value in my mapfieldpanel zoom_level = models.CharField(max_length=255) MapFieldPanel('latlng_address',latlng=True,zoom=zoom_level) but i am getting error like Object of type 'CharField' is not JSON serializable I tried MapFieldPanel('latlng_address',latlng=True,zoom='zoom_level'), zoom_level is passing as a string.How i can pick the value from database and pass it as a default value