Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: print latest download date and how many new entry since last download
In my app I've created a working function to dowload all the user information in my database. In my html page I'd like also to add the date of the latest time that the csv file was downloaded and how many new profile where added since the last download. I've thought to use the iformation stored in the name file to do so but I'm getting this error name 'file_name' is not defined account.views @login_required def download_csv(request): response = HttpResponse(content_type='text/csv') profile_total = Information.objects.all().count() profile_csv_date_donwload = str(datetime.today().strftime("%d-%m-%Y")) file_naname = + profile_csv_date_donwload + str(profile_total) +'.csv' response['Content-Disposition'] = 'attachment; filename=' + file_naname writer = csv.writer(response, delimiter=';') info = Information.objects.all() writer.writerow(['first_name', 'last_name', 'gender', 'birthdate']) for i in info: writer.writerow([i.first_name, i.last_name, i.gender, i.birthdate]) return response donwload.views from account.views import download_csv def download_page(request): profile_total = Information.objects.all().count() latest_d_csv = file_name[0:10] latest_n_csv = file_name[11:] new_profile = profile_total - int(latest_n_csv) context = { 'profile_total': profile_total, 'latest_d_csv': latest_d_csv 'latest_n_csv': latest_n_csv 'new_profile': new_profile } return render(request, 'page/download.html', context) html <div class="col-md-8"> <div class="row gutters-sm"> <div class="col-sm-6 mb-3"> <div class="card h-100"> <div class="card-body"> <h6 class="d-flex align-items-center mb-3">Profile CSV</h6> <br/> <small>Profile in Database: {{ profile_total }}</small> <br/> <small>Latest Download: {{ latest_d_csv}}</small> <br/> <small>New Profile: {{ new_profile }}</small> </div> </div> </div> -
How to solve Tkinter window ıs not responsing problem
I am using Tkinker for creating a progress bar in my Django project. Firstly I try to use Celery but I cannot do it so I looked for other alternatives and I found that. I implement Tkinker to my project and it works but after the window opens and the code is running but the window stops working. say not response. Like that: How can I work this? And this is my code: class myFunction(): def __init__(self, user, password, url, port, db_password, username): self.zaman = datetime.now().strftime("%Y-%m-%d") ... self.download_all(user, password, url, port, db_password) ... def download_all(self, user, password, url, port, db_password): # creating tkinter window root = Tk() # Progress bar widget progress = Progressbar(root, orient=HORIZONTAL, length=100, mode='determinate') root.title("Sending") root.attributes("-topmost", True) w = root.winfo_reqwidth() h = root.winfo_reqheight() ws = root.winfo_screenwidth() hs = root.winfo_screenheight() x = (ws / 2) - (w / 2) y = (hs / 2) - (h / 2) root.geometry('+%d+%d' % (x, y)) try: sys.path.append('../') ... bar = Bar('Processing', max=len(scans)) # try download and save scans into each folder the belong to pb_length = len(scans) print("------pb length-----------") print(pb_length) pb_value = 100/pb_length print("------pb val-----------") print(pb_value) for s in scans: progress['value'] = pb_value root.update_idletasks() bar.next() scanner.scan_name = s['name'] scanner.scan_id = s['id'] … -
'Canvas' object has no attribute '_committed'
I'm trying to save the canvas object to my django model field file but it says "'Canvas' object has no attribute '_committed'". p.setTitle(f"{patient.first_name} {patient.last_name}'s Report") p.showPage() p.save() pdf:bytes =buffer.getvalue() buffer.close() response.write(pdf) r = Result.objects.filter(score="12").update_or_create(file=p) Can anyone help me out with this issue? -
Adding Drop Down List to forms.ModelForm
When I was using the Crispy formatting, I was getting a dropdown list for the Room Type field . After designing my own bespoke form layout, I am struggling to get the dropdown list back. Could anyone point me in the right direction? class HotelSearchForm(forms.ModelForm): class Meta: model = RoomType fields = ['room_type', 'price'] widgets = {'price': forms.TextInput(attrs={'type':'range','class':'form-range slider', 'step': '5', 'min': '5', 'max': '500'}) ,'room_type': forms.TextInput(attrs={'class':'form-control form-control-lg select'})} Room_Type = ( ('Single','Single'), ('Double','Double'), ('Family','Family'), ('Dormitory','Dormitory'), ('F.Dormitory','Female Dormitory'), ) class RoomType(models.Model): room_type = models.CharField(max_length=60, null=False, choices=Room_Type) -
Django query optimizations
Is there a better way to do something like this with Django? Looking to get a dic where each key is a 'user_type' and the corresponding value is the count of records for that 'user_type'. For example: {1: 200, 2: 300} stuff_qs = Model.objects.all() user_type_count = stuff_qs.values( 'user_type' ).annotate(count=Count('id')).order_by() dic_counts = {d['user_type']: d['count'] for d in user_type_count} I don't really want to do anything with stuff_qs, as I need to get multiple different types of dic_counts from the same qs. -
How to filter products from the database when overriding queryset in django restframework
I'm stuck, not knowing how to go about this anymore. I want to filter products using a particular field called product_class. The programme below keeps returning all the products in the database rather than returning only those that have common rpduct_class. models.py class Product(models.Model): categories = models.ManyToManyField(Category) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="product_owner") name = models.CharField(max_length=150) image = models.ImageField(upload_to="images/products/") slug = models.SlugField(max_length=255, blank=True, null=True) brand = models.CharField(max_length=255, default="brand") product_class = models.CharField(max_length=50) createdAt = models.DateTimeField(auto_now_add=False) class Meta: ordering = ("-createdAt",) def __str__(self): return self.name serializers.py class product_serializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'categories', 'created_by', 'name', 'image','slug', 'brand','product_class') views.py class product_class_view(generics.ListAPIView): serializer_class = product_serializer permission_classes = (permissions.AllowAny, ) def get_queryset(self, *args, **kwargs): queryset = Product.objects.all() product_class = self.request.query_params.get('product_class') if product_class is not None: queryset = queryset.filter(Product__product_class=product_class) return queryset urls.py path('products/<product_class>', views.product_class_view.as_view(), name="product_class") Please I want to know how to make the code filter products based on product_class. The product_class is a field in the product model. -
Django and opencv how to save a file?
I have a question and I need help. I get this error: numpy.ndarray' object has no attribute 'save How can I save a file? Code below. def filter2(request, id): image = Images.objects.all() if request.method == 'POST': for x in image: img_main = cv2.imread(x.images.path, flags=cv2.IMREAD_COLOR) kernel = np.array([[0, -1, 0], [-1, 5,-1], [0, -1, 0]]) sharpened =cv2.filter2D(src=img_main, ddepth=-1, kernel=kernel) sharpened.save() return redirect("gallery") -
In a multi-domain Django site, what are the pros/cons of routing domains using middleware VS running separate instance per domain
In a Django site with multiple domains, what are the performance implications of using a single Django instance (with middleware handling requests) vs having multiple django instances (one per domain)? Details: I have a site built on a single monolithic Django codebase that uses six different subdomains (admin, event registration, two different user portals, api.example.com, sso.example.com). Currently I have each site running on its own socket, and using separate UWSGI confs (one for each domain under emperor) to manage workers. I'm wondering if it would make more sense to instead have a single UWSGI config, and route each request using this middleware (basically setting request.urlconf at runtime). Would this in any way improve performance? -
The form does not appear even though I added to the views
views.py class LogReply(LoginRequiredMixin,UpdateView): model = LogItem ## fields = ['handler','status','comment'] form_class = LogItemForm template_name = 'log/logitem_detail.html' def get_success_url(self): return reverse('log_view',self.object.id) forms.py class LogItemForm(forms.ModelForm): class Meta: model = LogItem fields = ['handler','status','comment'] widgets = { 'comment':forms.Textarea(attrs={ 'class':'form-control', 'placeholder':'請在此輸入處理情形...'}, ), } logitem_detail.html {% extends 'base.html' %} {% block content %} <div class="card"> <div class="card-header"> <div class="h3">{{ object.subject }}</div> </div> <div class="card-body"> <div class="card-text"> {{ object.description|linebreaks }} </div> </div> <div class="card-footer card-text d-flex justify-content-between text-muted"> <small title="Reporter"><i class="fas fa-user"></i> {{ object.reporter }} <i class="fas fa-phone"></i> {{ logitem.phone }}</small> <small><i class="far fa-clock"></i> {{ object.ctime }}</small> </div> </div> <hr> <div class="card mt-3"> {% if form %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="card-header d-flex justify-content-between"> <div class="h3">Situation</div> <div>{{ form.status }}</div> </div> <div class="card-body">{{ form.comment }}</div> <div class="card-footer card-text d-flex justify-content-between text-muted"> <small title="handler"><i class="fas fa-user-md"></i> {{ form.handler }}</small> <input type="submit" value="Submit" class="btn btn-sm btn-primary"> <small><i class="far fa-clock"></i> {{ object.utime }}</small> </div> </form> {% else %} <div class="card-header d-flex justify-content-between"> <div class="h3">Situation</div> <div> <span class="badge badge-{{ logitem.get_status_class }}"> {{ object.get_status_display }} </span> </div> </div> <div class="card-body">{{ object.comment|linebreaks }}</div> <div class="card-footer card-text d-flex justify-content-between text-muted"> <small title="handler"><i class="fas fa-user-md"></i> {{ object.handler }}</small> <small><i class="far fa-clock"></i> {{ object.utime }}</small> </div> {% endif %} </div> {% endblock … -
Django-React Upload Image Issue
I'm trying to upload image from react to database [django] I got errors GET http://localhost:3000/images/Koala.jpg 404 (Not Found) and images not shown on the page. but it is found in my backend static files. This my view: @api_view(['POST']) def uploadImage(request): data = request.data product_id = data['product_id'] product = Product.objects.get(id=product_id) product.imageSrc = request.FILES.get('imageSrc') product.save() return Response('Image was uploaded') this is my url of the view: path('upload/', views.uploadImage, name="image-upload"), and this is my react function to handle image upload: const uploadFileHandler = async (e) => { const file = e.target.files[0] const formData = new FormData() formData.append('imageSrc', file) formData.append('product_id', productId) setUploading(true) try { const config = { headers: { 'Content-Type': 'multipart/form-data' } } const { data } = await axios.post('/api/products/upload/', formData, config) setImageSrc(data) setUploading(false) } catch (error) { setUploading(false) } } and this my HTML Code <div id='imageSrc'> <h6>upload picture</h6> <input value={imageSrc} onChange={(e) => setImageSrc(e.target.value)} > </input> <input id='image-file' type='file' custom= 'true' label='Choose File' onChange={uploadFileHandler} > </input> {uploading && <Loader />} </div> -
Many to many field or foreign key for reports table
I have users who can be reported and I need to save information of the report. So my user report model looks like this class UserReportLog(models.Model): reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) reported_at = models.DateTimeField(auto_now_add=True) should I add another foreign key to the user who was reported ? which will make it class UserReportLog(models.Model): reported_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) reported_at = models.DateTimeField(auto_now_add=True) Currently there's a many to many field in the user model userReportBy = models.ManyToManyField( UserReportLog, related_name="userReported", blank=True ) I'm not sure which is the best practice -
Unable to push css in heroku service
What I am doing ? I am trying to deploy a django web application on heroku server. Problem I am not able to push css files in heroku server using git push heroku main . When I remove css file from static folder, then everything is going well. remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'CSS/style.css' failed! remote: Traceback (most recent call last): remote: File "/tmp/build_31834d76/manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'CSS/images/mobile-app.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f8a24943cd0>. remote: The CSS file 'CSS/style.css' references a file which could not be found: remote: CSS/images/mobile-app.png remote: Please check the URL references in this CSS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! … -
Django UpdateView not populating form
I've been stuck on this problem for hours, looking through Django documentation and adjusting my code hasn't helped. I have manually coded a HTML form (for styling reasons). Everything works fine until I try to edit an object via this form. I'm using a standard UpdateView with no additions but for some reason the form is not populating the data in the object. class RPLogbookEditEntry(LoginRequiredMixin, UpdateView): login_url = 'ihq-login' template_name = 'internethq/ihq-rplogbookform.html' model = RPLogbookEntry fields = ['entry_date', 'rpa_code', 'rpa_icao_code','rpa_registration', 'user_role', 'crew', 'crew_role', 'launch_location', 'recovery_location', 'remarks', 'vlos', 'evlos1', 'evlos2', 'bvlos', 'ft_day', 'ft_night', 'remarks', 'no_of_landings_day', 'no_of_landings_night'] def form_valid(self, form): form.instance.user = self.request.user form.instance.rpa = RPA.objects.get(rpa_code=form.cleaned_data['rpa_code']) return super().form_valid(form) def form_invalid(self, form): return super().form_invalid(form) def get_success_url(self): return reverse('ihq-rplogbook-list') + '?month=' + str(self.object.entry_date.month) + '&year=' + str(self.object.entry_date.year) Basically my question is - shouldn't this UpdateView populate my form automatically? -
super() function in __init__ in Meta Class inside Form
Could someone help me understand what is exactly going on here?: class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags'] widgets = { 'tags': forms.CheckboxSelectMultiple(), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for item in self.fields: self.fields[item].widget.attrs['class'] = 'input' I don't know how arguments in self.fields are being passed to init function. Upon my understanding under *args i will receive 'title' and under **kwargs i will receive 'class' : 'input' and for loop will go through oll of the items in fields list and will update 'class' attribute for all of the items. Is that correct? -
how to retrieve data using uuid in drf
halo guys i wan to retrieve a particular object using DRF RETRIEVEAPIVIEW using UUID as my pk but i'm getting { "detail": "Not found." } error below is my APIVIEW and url class RetrieveProfile(generics.RetrieveAPIView): lookup_field = 'id' serializer_class = UserProfileSerializer permission_classes = [IsAuthenticatedOrReadOnly] queryset = UserProfile.objects.all() path('<uuid:id>/display',RetrieveProfile.as_view(), name="display-profile"), any help on how to solve this ? -
How to show my reset password page in React using Django Rest Framework and Dj-rest-auth
I have an app that has a React front end and a Django api backend. I'm trying to get the password reset page to work but I can't work out how to set up the urls/routing. I had it working locally, but I think that was because the ports for the frontend and backend are different locally, so they were essentially different domains. My Django url patterns includes: path('api/v1/dj-rest-auth/password/reset/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm') I have a catchall url in my Django urls to make the rest of the frontend work. My React Router includes: <Route path="/api/v1/dj-rest-auth/password/reset/confirm/:uid/:token/" component={ResetPassword} /> My React password reset page contains: let url = process.env.REACT_APP_API_PATH + '/api/v1/dj-rest-auth/password/reset/confirm/' + this.props.match.params.uid + '/' + this.props.match.params.token + '/'; let headers = {token: this.props.match.params.token, uid: this.props.match.params.uid, new_password1: this.state.newPassword, new_password2: this.state.newPasswordConf } axios .post(url, headers) This takes the token and uid from the password reset link then sends them, along with the user's new password to the password reset endpoint. The dilemma seems to be, I need to access the reset link via React to be able to get the token and uid, but then I need to access the same link as a call to the API to be able to reset the … -
How to learn python and django
Hay I want to learn python but I don't know where to find a good resource I have C++ experience but I want to be a server side developer where can I find a good python and django resources -
Python Django, cannot save the main urls.py file without running into errors
So I was following Mosh's course for beginners on django and it was going pretty well but then, when I had to map URLs to Views I started having problems. The minute I am stack in is minute 30:43 and here is the link of the course: https://www.youtube.com/watch?v=rHux0gMZ3Eg I couldn't continue the course without getting errors, I tried to modify the main urls.py file but when I saved the file instead of redeploying I could have seen from the terminal that it ran into errors instead, the list is so long but here there is a link to a free text hosting service where I putted the errors: https://droptext.cc/5hib9 -
Django generic ListView, refering to each items in the object_list
I want to know the amount of trainees for each training in the ListView adding a context. I've search for how to reference each item in the ListView in order to perform a further query on each one. If anyone know a more efective way, i'll be grateful class TrainingsView(ListView): model = NewHireTraining template_name = 'nht/trainings.html' context_object_name = 'trainings' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['headcount'] = Trainee.objects.filter(new_hire_training = self.SOMETHING).count() return context Adding NewHireTraining and Trainee models: class NewHireTraining(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) program = models.ForeignKey(Program, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) trainer = models.ForeignKey(Trainer, on_delete=models.RESTRICT) start_date = models.DateField() nesting_date = models.DateField() production_date = models.DateField() def __str__(self): return str(self.program) + ' ' + str(self.project) + ' ' + str(self.start_date) class Trainee(models.Model): first_name = models.CharField(max_length=55) last_name = models.CharField(max_length=55) employee_number = models.IntegerField() hire_date = models.DateField() is_term = models.BooleanField(default=False) new_hire_training = models.ForeignKey(NewHireTraining, on_delete=models.CASCADE, default="") def __str__(self): return self.first_name + ' ' + self.last_name -
Display the results of a prefetch_related queryset in a Django template
I'm trying to display a list of objects in a Django template. This list of objects relies on a queryset in which I've used the prefetch_related method to fetch a many to many field. My queryset is queryset = Photo.object.prefetch_related('taggeditem_set__tag').all() The TaggedItem is linked to a photo with a many to many field, and it's also linked to a tag with a one to many field (the Tag contains the name, and this is what I want to display). I then convert this to a list and send it to a view. I would like to display the name of all photos and the name of every tag associated to a photo. However, I cannot found a way to list the associated tags. Is this achievable only in the template or do I have to implement a specific logic in the view? It seems I cannot access photo.taggeditem_set__tag elements in my template. <html> <body> <ul> {% for photo in photos %} <li>{{ photo.name }}, <LIST OF ASSOCIATED TAGS HERE> {% endfor %} </ul> </body> </html> -
Django - How to unit test view managing M2M relationship
I have a view that implements a m2m relationship, and I would like to unit test it, which I did not manage yet. The view seems working with the page I defined, but any suggestion is also welcome. The context is the following: I would like to manage users' groups in a Django app, and, of course, as I need additional fields, I built a model dedicated to user's management in my app. I defined a page with to multiple select boxes, one for the list of users, the other one with users selected to be part of the group. Inbetween are action icons to move users from one group to the others. At the stage, there is no control if a users shall not belong to more than one group, all users that do not belong to the current group are displayed (I assume it's just a question of filtering data). My page currently looks like this (btw, if you have any suggestion to make titles displayed above the selection boxes, I would also appreciate, even if it's not the topic here. I would like to unit test the contain of each group and, later on, the impact of … -
When i run migrate command. AttributeError: 'Model' object has no attribute '_meta'
When i run the following command python manage.py makemigrations I am using Django version 3.0.3 and python 3.8 I am learning django from documentation but it could not run makemigrations comman python manage.py makemigrations polls Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\sergio\Documents\Django-Project\2. AdvanceView\mysite\polls\models.py", line 8, in <module> class Question(models.Model): File "C:\Users\sergio\Documents\Django-Project\2. AdvanceView\mysite\polls\models.py", line 9, in Question question_text = models.Model(max_length=200) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\db\models\base.py", line 408, in __init__ opts = self._meta AttributeError: 'Model' object has no attribute '_meta' -
How to design ArrayField in django rest framework?
I am making API for cook book with Django Rest Framework. I don't know how to design ingredients model to make data to be like this: { "id": 1, "name": "spaghetti", "recipe": "recipe", "ingredients": [ [{name:'pasta',amount:100},{name:'tomato',amount:200},{...}] ], } My model: class Meal(models.Model): name = models.TextField() recipe = models.TextField() ingredients = ? Also how to serialize this field? -
django: M2M annotate Count is slow
When I run Count with annotate from an object that has m2m associated with it as shown below It is slow for some reason. And the same table is being accessed twice, and the second query is taking a long time. What could be causing this and how can I fix it? Also, I want to do order_by on this count, but doing order_by makes the speed even worse. # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) is_actress = models.BooleanField(default=False) class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True, db_index=True) # This is slow. Tag.objects.annotate(count=Count("video")) -
Which cloud server for django, sqlite, cron job equivalent [closed]
I am looking for a Python cloud service provider that offers sqlite (reading and writing) support, as well as django and supports a scheduler library like APschedule or cron job or similar. Preferably more than only one job. Would like to start with a free version. It's a website that is accessed just by myself and contains not too many data. AWS, Azure, google, heroko do not offer all these requirements combined, I suppose?! Can you recommend a free provider? Thanks