Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying my current domain in my django template not working
I send html email to the users using the EmailMultiAlternatives and it worked also but the problem is in the email message the link is not working. But when I tried doing <a href="http://127.0.0.1{% url 'add_your_details' user.username %}"> then it worked perfectly as I wanted. I tried {{ request.META.HTTP_HOST }} {{domain}} also for domain and for protocol {{protocol}} template <a href="{{ request.scheme }}://{{ request.get_host }}{% url 'add_your_details' user.username %}" target="_blank">Add your details </a> settings ALLOWED_HOSTS = ['127.0.0.1'] -
How to create a form with sticky tag similar to that of adding tags to Stack overflow's in Django?
The feature on slack that allows you search for a user when you want to send a direct message and clip it, which is also similar to the way tags are added when filling out a question on StackOverflow is called what? How can one add this feature to a Django form? Can it be added to for a ForeignKey field or only a ManyToMany Field? -
Does django-cors-headers allow access from all origins to the admin site?
I am working on a Django app with DRF and I added CORS configuration using the django-cors-headers package recommended in the documentation. I will set the origin to be my client on the production. My question is, will the admin site be available to public access from all browsers with this setup? This is the production settings I am planning on using. # CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ['client origin'] I cannot test this atm because I am far from being ready for production. Thank you. -
Django test IntegrityError in fixture teardown
I started using the factory_boy package so I've set up some factories and wanted to test that the objects created don't raise any validation errors. Here's the mixin I'm using that basically takes every factory from a module, creates an instance, then tests that there are no errors from .full_clean(). The user fixtures that are loaded are 10 instances with IDs 1 to 10. class FactoriesTestCaseMixin: fixtures = [ 'user/tests/fixtures/user.json', ] module = None def test_factories(self): err_msg = '{name} caused errors:\n{errors}' factories = [ (name, obj) for name, obj in inspect.getmembers(self.module, inspect.isclass) if obj.__module__ == self.module.__name__ and not obj._meta.abstract ] for factory in factories: name = factory[0] instance = factory[1]() errors = None try: instance.full_clean() except ValidationError as e: errors = e self.assertTrue(errors is None, err_msg.format(name=name, errors=errors)) The mixin would be used like this from django.test import TestCase from order import factories class OrderFactoriesTestCase(FactoriesTestCaseMixin, TestCase): module = factories But I keep getting an IntegrityError (traceback below) after the test successfully passes in regards to fixture teardown and I can't figure out how to get around it so my tests pass with no errors. If I run the tests for each individual app there are no errors. I never get problems … -
failing to upload image files to my django database
I am new to Django Framework, I have created a html form to upload Post title, description and Image. Image is not uploading to the database. Please look into the code and suggest me how to fix this. Models.py class Post(models.Model): title = models.CharField(max_length=1000, unique=True) img = models.ImageField(upload_to='pics_post') desc = models.TextField() views.py def index (request) : posts = Post.objects.all() if request.method == 'POST' : if request.POST.get('newpost') == 'Submit': # post_title = request.POST.get('posttitle') # post_desc = request.POST.get('post_desc') # post_image = request.FILES['post_img'] # post = Post(title = post_title, desc = post_desc, img = post_image) # post.save() # return render(request, 'index.html', {'posts' : posts}) formdata = PostForm(request.POST,request.FILES) if formdata.is_valid(): formdata.save() return render(request, 'index.html', {'posts' : posts}) else : pass return render(request, 'index.html', {'posts' : posts}) else : pass else : return render(request, 'index.html', {'posts' : posts}) HTML form <form action="#" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control newpost" name="posttitle" placeholder="Post Title" id="posttitle" required> </div> <div class="form-group"> <input type="text" class="form-control newpost" name="post_desc" placeholder="Post Description" id="postdesc" required size="100" required> </div> <div class="form-group"> <input type="file" class="newpost" name="post_img" id="postimage" accept=".png, .jpg, .jpeg"> <p class="form-text text-muted">Only png and jpg allowed</p> </div> <button type="submit" class="btn btn-primary" name='newpost' id="commentsubmit" style="float: right;" value="Submit">Submit</button> </form> The commented part in the … -
The function stops working after adding the redirection. Ajax, Django - progress bar
I added a progress bar when uploading the file according to this tutorial in my Django app. Everything worked fine but when I try to change the 'alert' in my ajax file to refresh or redirect to another page, the bar stops working. For example i change this: success : function() { alert('File uploaded!'); For this: success : updatePage; I see this message on my command line after uploading form (but everything is saved correctly in the database): Exception happened during processing of request from ('127.0.0.1', 50954) Traceback (most recent call last): File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 717, in __init__ self.handle() File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] My file upload.js $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); var formData = new FormData($('form')[0]); $.ajax({ xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { console.log('Bytes Loaded: ' + e.loaded); console.log('Total Size: ' + e.total); console.log('Percentage Uploaded: ' + (e.loaded / e.total)) var percent = Math.round((e.loaded / e.total) * 100); $('#progressBar').attr('aria-valuenow', percent).css('width', … -
Django rest framrwork Nested Serializer's fields not appearing in parent serializer
In my Django app (using drf), I've modified my model's serializer to get the front-end's desired input, but I'm having zero luck trying to nest this serializer inside another one. I've tried creating a field of the model with the to_representation method and putting a get_photos method, none of which amounted to anything. # models.py class Photo(models.Model): photo = models.OneToOneField(RawPhoto, related_name='contest_photo', on_delete=models.CASCADE) thumbnail_size = models.OneToOneField(PhotoSize, related_name='contest_photo', on_delete=models.CASCADE) thumbnail_url = models.TextField(verbose_name='thumbnail_url') class Meta: verbose_name = 'Contest Photo' @property def get_photo_src(self): return settings.MEDIA_URL + self.photo.image.name @property def get_thumbnail_url(self): # dont forget to add cache if len(self.thumbnail_url) == 0: file_name = self.get_photo_src last_dot = file_name.rfind('.') photo_name, photo_extension = file_name[:last_dot], file_name[last_dot:] self.thumbnail_url = photo_name + '_' + self.thumbnail_size.name + photo_extension return self.thumbnail_url # serializers.py class PhotoSerializer(serializers.ModelSerializer): thumbnail_height = serializers.ReadOnlyField(source='thumbnail_size.height') thumbnail_width = serializers.ReadOnlyField(source='thumbnail_size.width') src = serializers.ReadOnlyField(source='get_photo_src') thumbnail_url = serializers.ReadOnlyField(source='get_thumbnail_url') caption = serializers.ReadOnlyField(source='photo.caption') class Meta: model = Photo fields = ['src', 'thumbnail_url', 'thumbnail_height', 'thumbnail_width', 'caption'] class GallerySerializer(serializers.ModelSerializer): photos = PhotoSerializer(many=True) class Meta: model = Gallery fields = ['title', 'photos'] PhotoSerializer actually returns the full description of the object that I expect from it, but when I nest it inside GallerySerializer, it only shows thumbnail_url, which is the only field that is included in the model itself. … -
Django won't serve an image from MEDIA_URL
A beginner building a personal blog. Got a simple model with an ImageField. No matter what I try the Django won't serve an image. Judging by the console output in the Dev Tools it is looking for an image in the wrong folder. I don't know how to fix that. I tried setting up MEDIA_URL, MEDIA_ROOT and adding a urlpattern like it's being suggest here and here I have uploaded the picture via admin panel, its location is media/images/stockmarket.jpg. But for some reason the server is looking for an image here /blog/images/stockmarket.jpg Project name: 'wikb', 'blog' is an App: project_file_system models.py from django.db import models class Post(models.Model): title = models.CharField('Post Title', max_length=200) preview = models.CharField('Post Preview', max_length=400) thumbnail = models.ImageField('Post Picture', upload_to='images/', blank=True) view.py from django.shortcuts import render from django.http import HttpResponse from .models import Post def home(request): all_posts = Post.objects.all() hero_post = all_posts[0] context = {'hero_post': hero_post, 'all_posts': all_posts} return render(request, 'blog/home.html', context=context) HTML <div class="hero"> <a href="#" class="hero__link" style="background-image: url({{hero_post.thumbnail}})"> <article class="hero__article"> <h2 class="hero__heading">{{hero_post.title}}</h2> <p class="hero__preview">{{hero_post.preview}}</p> </article> </a> </div> settings.py MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" Global urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = … -
How to use grater than and less than or equl in django filter query
I am trying to filter data where added in between from date and to date. but i'm getting Cannot resolve keyword 'date_gte' into field. this error how to resolve this issue from1 = request.POST.get('from') to = request.POST.get('to') result = qwerty.objects.filter(date_gte= from1, date_lte= to) print(result) result.save() -
required=False not working with update_or_create in ModelSerializer
I am creating an API where I get some data with user_id field. If given user_id exist in DB it update rest of the data else it will create new data. Here my code: serializers.py class DataUpdateSerializer(serializers.ModelSerializer): user_id = serializers.CharField(max_length=250) email = serializers.EmailField(required=False) first_name = serializers.CharField(required=False) last_name = serializers.CharField(required=False) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'user_id', 'balance', 'device_id', 'platform') def create(self, validated_data): data_update, created = User.objects.update_or_create(user_id=validated_data['user_id'], defaults={ 'first_name': validated_data['first_name'], 'last_name': validated_data['last_name'], 'email': validated_data['email'], 'balance': validated_data['balance'], 'device_id': validated_data['device_id'], 'platform': validated_data['platform'], } ) return data_update views.py class data_update(APIView): permission_classes = (Check_API_KEY_Auth,) def post(self, request): serializer = DataUpdateSerializer(data=request.data) if serializer.is_valid(): serializer.save() username = request.data['user_id'] User.objects.filter(user_id=username).update(username=username) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_204_NO_CONTENT) email, first_name and last_name are optional and can be blank in DB or in serializer. Problem: Everything is working fine but if I don't pass email, first_name or last_name, it gives error: key_error and if I provide these fields with blank value "", this give error cannot be blank -
How to fix error "invalid literal for int() with base 10: 'Independence' Django?
I am trying to import a list of questions in my multiple choice questions model using the import_export.admin method, I am to import, but the list does not get appended to my existing list of questions, instead it throws invalid literal for int() with base 10: 'Independence'. I have tried change the format of the csv file I am uploading from comma-separated Values to CSV UTF-8(Comma-delimited). It reduced the number of columns the errors came from, from two to one. my admin.py file: class MCQuestionAdmin(ImportExportModelAdmin): list_display = ('content', 'category', ) list_filter = ('category',) fields = ('id', 'content', 'category', 'figure', 'quiz', 'explanation', 'answer_order') search_fields = ('id','content', 'explanation') filter_horizontal = ('quiz',) inlines = [AnswerInline] my models.py file: class MCQQuestion(Question): answer_order = models.CharField( max_length=30, null=True, blank=True, choices=ANSWER_ORDER_OPTIONS, help_text="The order in which multichoice \ answer options are displayed \ to the user", verbose_name="Answer Order") def check_if_correct(self, guess): answer = Answer.objects.get(id=guess) if answer.correct is True: return True else: return False def order_answers(self, queryset): if self.answer_order == 'content': return queryset.order_by('content') # if self.answer_order == 'random': # return queryset.order_by('Random') if self.answer_order == 'none': return queryset.order_by('None') def get_answers(self): return self.order_answers(Answer.objects.filter(question=self)) def get_answers_list(self): return [(answer.id, answer.content) for answer in self.order_answers(Answer.objects.filter(question=self))] def answer_choice_to_string(self, guess): return Answer.objects.get(id=guess).content class Meta: verbose_name = … -
Declacre CSRF-Token in forms.py
I'm using Djangos CSRF-Token the way it's mostly described on the internet: MyFormPage.html <form method="POST"> {% csrf_token %} {{ form.as_p }} </form> But I wonder - is there a way to include it somehow directly in the forms.py? -
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