Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AuthenticationForm Customization
I am relatively new to django and want to customize the AuthenticationForm but an not sure how to do it. I essentially want to override the init function to be able to inject attributes and control what is displayed on the form. Specifically I would like to add this for my login form: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget = forms.widgets.TextInput(attrs={ 'class': 'form-control' }) self.fields['password1'].widget = forms.widgets.PasswordInput(attrs={ 'class': 'form-control' }) My issue is that I let django do all of the work for me when creating my login view/form therefore I am unsure how to customize it. Reading the docs the LoginView uses the default AuthenticationForm. Any help is greatly appreciated! -
django + ngnix, serving media files
i show you directly my code: i handle the link ewayApp/media/{stuff} with django: urls.py: path('ewayApp/media/<str:media_url_1>/<str:media_url_2>/<str:media_url_3>',course.getMedia), the handler: course.py: def getMedia(request, media_url_1, media_url_2, media_url_3): ...some stuff... url = '/protected/' + media_url_1+'/'+media_url_2+'/'+media_url_3 response['X-Accel-Redirect'] = url return response and i'm sure going for the first link i pass through this function because i have some prints along the function. my ngnix settings: location ~ / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://127.0.0.1:8080; } location ^~ /protected/ { internal; alias path/to/media/media/; } So, the django server runs on 127.0.0.1:8080 and ngnix proxies all the requests there. when accessing these media files if i go straight to the link https://website.com/ewayApp/media/{stuff} ngnix returns me back 404 error not found. I checked if the media are stored in path/to/media/media/, and they are, but obviously in subdirectories with media_url_1, media_url_1 ... that are specified in {stuff} How to solve this? Thanks in advance. -
Django Ajax file upload with progressbar
I'm working on a project where I want to add a progress bar with AJAX when uploading a file. until now I did this but it's not working. I'm using S3 bucket to store the images. models.py class post(models.Model): image = models.ImageField(upload_to='post_pics', null=True, blank=True) content = models.TextField() def __str__(self): return self.content My forms.py class UploadForm(forms.ModelForm): class Meta: model = post fields = ('image', 'content',) My views.py def home_view(request): form = UploadForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, } return render(request, 'blog/upload.html', context) My urls.py from django.urls import path from blog.views import home_view urlpatterns = [ path('post/upload/', home_view, name="upload"), ] My upload.html <div id="alert-box"></div> <div id="image-box"></div> <br> <form action="" id="upload-form"> {% csrf_token %} {{form.as_p}} </form> <br> <div id="progress-box" class="not-visible">progress</div> <div id="cancel-box" class="not-visible"> <button id="cancel-btn" class="btn btn-danger">cancel</button> </div> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script> <script> console.log('hello world') const uploadForm = document.getElementById('upload-form') const input = document.getElementById('id_image') console.log(input) const alertBox = document.getElementById('alert-box') const imageBox = document.getElementById('image-box') const progressBox = document.getElementById('progress-box') const cancelBox = document.getElementById('cancel-box') const cancelBtn = document.getElementById('cancel-btn') const csrf = document.getElementsByName('csrfmiddlewaretoken') input.addEventListener('change', ()=>{ progressBox.classList.remove('not-visible') cancelBox.classList.remove('not-visible') const img_data = input.files[0] const url = URL.createObjectURL(img_data) console.log(img_data) const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('image', img_data) $.ajax({ … -
Convert any file format to pdf and store in database as pdf version using python- django
models.py: ----------- class File(models.Model): file = models.FileField( upload_to='documents/%Y/%m/%d', null=True, blank=True, verbose_name=_('file') ) pdf_file_version = models.FileField( upload_to='pdf_documents/%Y/%m/%d', null=True, blank=True, verbose_name=_('pdf file version') ) signals.py ------------- @receiver(post_save, sender=File) def create_pdf_file_version(sender,instance,created,**kwargs): if created: initial_path = instance.file.path print(initial_path) year = time.strftime('%Y') month = time.strftime('%m') day = time.strftime('%d') new_name = '/'.join(['pdf_documents', year, month, day,os.path.basename(initial_path).split('.')[0] + '.pdf']) new_path = os.path.join(settings.MEDIA_ROOT, 'pdf_documents', year, month, day, os.path.basename(initial_path).split('.')[0] + '.pdf') if not os.path.exists(os.path.dirname(new_path)): os.makedirs(os.path.dirname(new_path)) shutil.copy2(initial_path, new_path) output = pypandoc.convert_file(initial_path, 'pdf', outputfile=new_name) instance.pdf_file_version = new_name instance.save() here,I need get uploaded file ,and needs to convert any format to pdf directly without reading it.and save in database as pdf_file_version separately.I must maintain original version and pdf version -
Django: How not to reload the entire page on just a few content updates?
I am using Django as my Web Framework. I want to update the content of a page when the user clicks a button. Is it possible to not update the entire page? For example, if I wanted to program a todo list. Then I would not want to reload the whole page when adding an item at the bottom. Is there a solution for just updating the updatet elements? In my example code below it is unfortunately so that the entire page is reloaded every time def test(request): if request.method == 'POST': context = { 'results': 'Some kind of result', } return render(request, 'users/register.html', context) return render(request, 'users/register.html') -
Dynamic periodic tasks - alternatives to Celery beat
If one wants to set up dynamic and standard periodic tasks scheduling and in a Django project, are there any stable alternatives to celery and celery beat? (when I say dynamic I mean such thing as described here) Would Dramatiq or any other schedulers, for instance, allow for such customization as dynamic user-launched schedulling of periodic tasks? Or are there any other strategies for creating some kind of dynamic schedule with periodic tasks for Django in general ? -
How to view django database on sqliteonline
I want my database deployed on sqliteonline instead of django admin but i am stuck at how to do that. Thanks in advance. It will be of much help! -
Django Models: Automatic field 'modelname_id' is generated
I have been working with from past few month. I saw a weird thing. I have two model like via one to one relationship. one is a core user model and second one is specific user detail model. when i got an attribute error i found an unknown field and when i added it to the admin site in list display i just confused. see my models below models.py class DocsAppointUserModel(AbstractBaseUser,PermissionsMixin): type_choices = ( ('M', 'Moderator'), ('D', 'Doctor'), ('P', 'Patient'), ('A', 'Admin'), ('AS','Admin Staff'), ) first_name = models.CharField(verbose_name="First Name",default="",max_length=30) last_name = models.CharField(verbose_name="Last Name",default="",max_length=30) user_type = models.CharField(verbose_name="User Type",max_length=2,choices=type_choices,default='P') user_email = models.EmailField(verbose_name="Email",max_length=50,primary_key=True) joined_on = models.DateTimeField(auto_now_add=True) last_active_on = models.DateTimeField(auto_now=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) #staff for site admin USERNAME_FIELD = 'user_email' #for logging it with email REQUIRED_FIELDS = ["first_name","last_name","user_type"] objects = UserManager() def has_perm(self,perm,obj=None): #returns true if the user has specified permission , # print(perm,obj) if self.is_superuser: return True else: if perm in self.get_user_permissions(): return True else: return False def has_module_perms(self,app_Label): # return true if any user has permission for a perticular module(app) given if self.is_superuser: return True else: all_perm = list(self.get_user_permissions()) for i in all_perm: if i.split('.')[0]==app_Label: return True else: return False def __str__(self): return f'{self.user_email}' def get_full_name(self): … -
I want to send js Array in django
the error it throws is 'NoneType' object has no attribute 'split' . But if i remove first line in script $("#btn").click(function() { ............"except in between ajax code" .............. }); then it runs perfectely why this happens i dont know. <script> $("#btn").click(function() { $.ajax({ method: 'GET', url: '/food_output', data: {'list': list.join(",")}, success: function (data) { alert("worked"); console.log(list); }, error: function (data) { alert("not work"); console.log(list); } }); }); </script> in vews.py def food_output(request): lists = request.GET.get('list') lists =lists.split(',') print(lists) return render(request, "food_output.html") -
Getting Error while deleting Cart item using DestroyAPIView with Javascript. (Django)
I'm using DestroyAPIView with Javascript to delete the cart item in Django While clicking on delete button it shows the following error on chrome console: jquery.min.js:2 DELETE http://127.0.0.1:8000/showdata/2342; 404 (Not Found) send @ jquery.min.js:2 ajax @ jquery.min.js:2 destoryCart @ (index):46 onclick @ (index):1 (index):55 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} and in vs code terminal showing: Not Found: /showdata/2342; and all my code goes here: views.py class CartDestroyAPIView(DestroyAPIView): # DeleteView permission_classes = [IsAuthenticated] # Or anything else you want authentication_classes = [SessionAuthentication] # Or anything else you want serializer_class = productserializers queryset = Cart.objects.all() index.html <script> $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/showdata ', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr><td style="font-style:bold">' +data[i].product.name+'</td><td style="font-style:bold">' +data[i].product.price+'</td><td><a href=' +data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><button onclick="destoryCart('+data[i].product.id+')" type="button" class="btn btn-outline-danger">DELETE</button></td></tr>'); $("#tableProduct").append(row); } } }); }); const destoryCart = (id) => { let url = `http://127.0.0.1:8000/showdata/${id};` $.ajax({ beforeSend: function(xhr){xhr.setRequestHeader('X-CSRFToken', "{{ csrf_token }}"); }, url: url, type: 'DELETE', success: (data) => { console.log("deleted!"); }, error: (err) => { console.log(err); } }); }; </script> urls.py path('cart_destroy/<int:pk>', views.CartDestroyAPIView.as_view(), name ='cart_destroy'), WHAT IS WRONG GOING WITH THIS CODE. -
How can I have an image field in a Django Model?
I wanted to have a feature on my website that allows you to click on a link near an image and have that take you to another page which displays the image and a description. I figured that I could do this with a Model that has an image field and a text field for the description, but I don't know how to store an image! Is there a function or such that allows you to have an image field in a Django model? If so, what is it and where do I need to store images relative to the models.py file for it to work? Thanks in advance. -
DRF test multiple image upload
I'm trying to test multiple image upload to my server. Here is the serializer: class ImageSerializer(serializers.ModelSerializer): image = serializers.ListField( child=serializers.ImageField(allow_empty_file=True) ) ImageFactory: def get_image(): image = Image.new("RGB", (2000, 2000)) file = tempfile.NamedTemporaryFile(suffix=".jpg") image.save(file) return file Test: def test_upload_multiple_images(self): self.image = get_image() with open(self.image.name, "rb") as file: payload = { "image": [file, file] } response = self.client.post( reverse("gallery-list", args=[self.item.pk]), data=payload, format="multipart" ) When testing via Postman, images from the array are saved correctly. However when using the test case, I get the following message from the response: {'image': [{'message': 'The submitted file is empty.', 'code': 'empty'}]} Before adding allow_empty_file=True, there were two of those messages being returned. Has anyone got any idea why that would happen? -
Django: how can I cache a template fragment conditionally?
I currently cache a page for unauthenticated users like this: {% with cache_timeout=request.user.is_authenticated|yesno:"0,600" %} {% cache cache_timeout my_page_cache user.is_authenticated LANGUAGE_CODE obj.pk obj.updated %} <p>This content is cached if the user is not authenticated</p> {% endcache %} {% endwith %} This works great, but now I want to change the condition of the with block to request.user == obj.user. How can I rewrite that code? Thanks! -
Define renderer class dynamically in Django view function
How can I define the renderer class inside the Djanog old api_view function depending on some condition? To have something like this: @api_view(['GET']) def can_render_2_things(request): if some_comdition: renderer_classes = [PDFRenderer] else: renderer_classes = [JSONRenderer] -
How to properly manage django production and development files
How can I properly manage my development files and production files with source control like GitHub (private repo). I am new to Django and while publishing my code to production there are many settings which needs to be changed in order to use it in production but the same setting won't work on my development server. I am stuck here Please guide me how manage. I want my files to be source control like any time I can make my development environment on another pc and anytime I can make my production server on any server. how to manage secret keys, passwords on source control (like GitHub private repo) Also please specify how should an Ideal file structure look like -
Able to save data without filling inlines even when required fields are there in django admin
I have 3 models Course, Course Details and Course Deadlines models.py class Course(models.Model): name=models.CharField(max_length=100) info= models.TextField() class CourseDetails(models.Model): course=models.ForeignKey(Course, on_delete= models.DO_NOTHING) info= models.TextField() class CourseDeadlines(models.Model): course=models.ForeignKey(Course, on_delete= models.DO_NOTHING) date= models.DateTimeField() admin.py class CourseDetailsInline(admin.StackedInline): model=CourseDetails extra=0 max_num=1 can_delete= False class CourseDeadlinesInline(admin.StackedInline): model=CourseDeadlines extra=0 max_num=1 can_delete= False class CoursesAdmin(admin.ModelAdmin): inlines=[CourseDetailsInline,CourseDeadlinesInline] admin.site.register(Course,CoursesAdmin) I am able to save the course without having to fill the inline fields even though they are required fields. -
Django with IIS server restart unexpectedly
I currently developing a Django Project which use IIS as web server. When I make some of the ajax request, the server will restart by itself with unknown reason. I have made some log and pretty sure the restart occurs just before Django run the corresponding function in views.py, but I don't know if the restart occurs before or after the server receive request. Does anyone have some idea on this issue? -
How to use namespace in django
I looked at the official Django documentation(https://docs.djangoproject.com/en/3.2/topics/http/urls/#reversing-namespaced-urls) and the error code and wrote the following. How can I write namespaces to work? views.py: from django.urls import path, include app_name = 'home' urlpatterns = [ path('math/', include('math_note.urls', namespace='math-note')) ] templates: <a href="{% url 'home:math-note' %}">math note</a> Error when running runserver: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Question: How can I use the namespace function? -
Save xlsx file in Desktop using Django
I want to save a excel file in Desktop from my apps, the file path is depends on the user that she/he want to download the file.Give me some idea, Thank You. FileNotFoundError at /Registration/Registration/Report [Errno 2] No such file or directory: '/Users/{username}/Desktop/Registration_Report.xlsx' I got the error above if I call the current username login: import os def registration_report(request): username = os.getlogin() ***excel codes here*** wb.save("/Users/{username}/Desktop/Registration_Report.xlsx") ## path to save the xlsx file ## If I put the exact path to desktop working good and I access the downloaded excel file, This is working but what I want is, the path is depend on the user machine where the file to save. def registration_report(request): ***excel codes here*** wb.save("/Users/myusername/Desktop/Registration_Report.xlsx") ***myusername is the exact machine login username that I use*** -
Is there a way to categorize skills for users to choose their skills in a form
Currently, I am working on a project where I need to get the user's skills through a form. I am facing a problem in categorizing the skills. Sample for categorization So please help me to categorize it in the same way the above picture has. The following code is coded by me using Django, models.py, forms.py -
How to get Total price from two different Size
I have 3 models : class Stock(models.Model): amount_size_1 = models.PositiveIntegerField(default=0) amount_size_2 = models.PositiveIntegerField(default=0) product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="product", related_name="pro") price_size_1 = models.FloatField(default=0,null=True) price_size_2 = models.FloatField(default=0,null=True) class OrderItem(models.Model): product = models.ForeignKey(Stock, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = jmodels.jDateField(auto_now=True) date_ordered = jmodels.jDateField(null=True) quantity = models.IntegerField(default=0, verbose_name='quantity') size = models.IntegerField(default=0, verbose_name='size') class Order(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem, related_name='item') date_ordered = jmodels.jDateField(auto_now=True,null=True) created_on_time = models.TimeField(auto_now_add=True,null=True) def get_cart_total(self): return sum([item.quantity*item.product.price_size_1 for item in self.items.all()]) My problem is that in def get_cart_total how filter for each item by their size I have 3 size (1,2,3), size 1 and 3 price is price_size_1 and size 2 is price_size_2 How can I solve this problem? or make if in Bracket? (in class OrderItem.size only get 3 numbers 1,2or3) -
How to solve Exception Value: 'list' object has no attribute 'lower' in django
This the Traceback: Environment: Request Method: GET Request URL: ipaddressHere/admin/ Django Version: 3.2.4 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authentication.apps.AuthenticationConfig', 'rest_framework', 'rest_framework.authtoken'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_request(request) File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\middleware\common.py", line 48, in process_request host = request.get_host() File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\http\request.py", line 141, in get_host if domain and validate_host(domain, allowed_hosts): File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\http\request.py", line 691, in validate_host return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts) File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\http\request.py", line 691, in <genexpr> return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts) File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\utils\http.py", line 292, in is_same_domain pattern = pattern.lower() Exception Type: AttributeError at /admin/ Exception Value: 'list' object has no attribute 'lower' I dont face this error when I comment ALLOWED_HOSTS so I feel it has to do something with it. Everything was working fine before I did not change anything. This is how my allowed host looks like ALLOWED_HOSTS = [ '127.0.0.1', and other ip adresses in same format ], -
Django linux server image storing
I am developing an application with an image gallery using Django. By the way, shop products also have photos. At the moment, website is been deployed on the linux server. Here is the question: should i upload images to the linux server using ImageField or it is better practise to use separate cloud storage? -
How to Select Multiple Item from a foreign key field in Django
I have a form where I want to display multiple select foreign key field. I want some thing like that here's my Model class jira_Story(models.Model): Jira_ID = models.CharField(max_length=100, blank=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) Developer_Assigned = models.ForeignKey(developer, on_delete=models.CASCADE,blank=True, null=True) I want Developer_assigned field as like that pic. I want to select multiple developer at time. can someone help me with the solution? -
How to create fake dates for objects with fields `DateTimeField(auto_now=True)`?
why I can't change date_created field value? I created this model class Value(SafeDeleteModel): name = models.CharField(max_length=50, blank=True) date_created = models.DateTimeField(auto_now=True, blank=True, null=True) class Meta: get_latest_by = 'date_created' Then for testing purposes, I need to create fake dates, maybe I need to try the mock method or something but I don't know how to do that. However, here when I try to change the date_created and print it back I find out it is not changed # test.py for i in range(1,4): val = Value.objects.create(column=cal3, field_value=str(is_odd(i))) setattr(val,'date_created', '2021-06-17 06:56:57.966476+00:00') val.save() print(val.date_created) I tried val.date_created = '2021-06-17 06:56:57.966476+00:00' instead of setattr using mock mehtod but I don't know how to emplment it properly