Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
xhtml2pdf using images not working without error
I tried use an image for a signature in xhtml2pdf but it doesn't load the image. I see no error in the console html <img src="{{signature}}" class="signature"> python def generate_pdf(response,property): BASE_DIR = path.dirname(path.dirname(path.abspath(__file__))) URL = "http://127.0.0.1:8000"+'/static'+property.agent.signature.url print(URL) template = get_template("main/pdftabo.html") context = { "address": f'{property.street} {property.building_number} {property.city}', "owners": property.owners.all(), "loan": property.loan, "plot": property.plot, "signature":"http://127.0.0.1:8000"+'/static'+property.agent.signature.url, "date":date.today(), } html = template.render(context) filepath = join('static',f'media/{property.block}{property.lot}.pdf') write_to_file = open(filepath, "w+b") result = pisa.CreatePDF(html,dest=write_to_file) write_to_file.close() with open(join('static',f'media/{property.block}{property.lot}.pdf') , 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') #response = HttpResponse(html) response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response pdf.closed -
Error while runserver in Django: UnicodeDecode: 'utf-8' codec can't decode byte 0-xcf in position 2: invalid continuation byte
screenshot I'm trying to "runserver" for "manage.py' in my virtual environment of Django and I get that exception. Can't type or select in the command window afterwards, so screenshot of the full log added. Windows 7, Django 3.2.5, Python 3.8.9 -
Is there any possible way to create custom text editor
My Goal: is to create a text editor in a website like this. But I really have no idea if its possible and even if it is, how to achieve it. -
How to get name input type submit modelform in Django
I am facing a problem. Please help me templates.html <form action="" method="POST">{% csrf_token %} {{Form.as_p}} <input type="submit" name="Save" value="Save"> <input type="submit" name="Delete" value="Delete"> </form> view.py Class-based views: def post(self,request,text_id): try: text_data = Text.objects.get(pk=text_id) a = FormText(request.POST,instance=text_data) except: a = FormText(request.POST) if request.POST.get('name') =='Delete': a.delete() else: try: a.save() except: return HttpResponse('no ok') -
How to create logout view for djoser with JWT authentication?
I am working Django rest framework with djoser. I can't able to find way to remove the token in JWT(Djoser) and I need to store in old JWT. Can you please help me to logout the user in JWT authentication in Djoser? I want to login by either email or username in Djoser(JWT). Can you please give me solution for that? Answer will be appreciate. -
Integration dropzone.js with django has been an error "status of 405 (Method Not Allowed)"
This project I have been learning from the youtube channel. I watch it carefully and coding at the same instructor but It does not work when dropzone.js integrate with Django. I try to upload files to form but It cost an error "status of 405 (Method Not Allowed)" in the console.log. I can not figure it out. How I can fix it. This is my upload.js const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value Dropzone.autoDiscover = false const myDropzone = new Dropzone('#my-dropzone', { url: '/reports/upload/', init: function(){ this.on('sending', function(file, xhr, formData){ console.log('sending') formData.append('csrfmiddlewaretoken', csrf) console.log(csrf) }) }, maxFiles: 3, maxFilesize: 3, acceptedFiles: '.csv' }) This is my Html file {% block content %} <h5>Upload your sale file</h5> <form id="my-dropzone" class="dropzone dz" > {% csrf_token %} <div class="fallback"> <input name="file" type="file" multiple /> </div> </form> {% endblock content %} This is views.py file def csv_upload_view(request): print("file has been sending") return HttpResponse -
Python or Django library to convert html to an image or pdf
So I have two main issues: Finding a library that can convert an html file to an image and pdf (two separate libraries works too) Perform the conversion without exposing the html template in a URL What I've tried so far: I tried using imgkit but from my research, it's incompatible with my docker image: (python:3.7.11-alpine3.13). This was the error I was getting: OSError: wkhtmltoimage exited with non-zero code -11. error: QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root I tried using django's render_to_string, to generate a string which can be saved as an html file containing the rendered context data. However, for iterations were not rendered in the string output of render_to_string Currently the only way for me to generate a valid html page with all the passed context data is by using render. However this implementation would not work because I can only access the html body via a URL, which in my case is a no-no for security resasons. Any help is greatly appreciated. Thanks! -
How can I know which buildpack is appropriate for my application when deploying to heroku
I have been getting this error: ----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed and when I open the logs I saw this: Build failed -- check your build output: https://dashboard.heroku.com/apps/81b6ebcd-5768-4100-9a51-9fc90a49e4b4/activity/builds/1f1fc4ef-ad12-42d7-bb60-9937f45e0d36 And also when I tried to add the python buildpack directly to my CLI, I go this error: Error: Missing required flag: » -a, --app APP app to run command against » See more help with --help -
Why Django REST Framework (DRF) folder structure is different than Django Turorial?
If you follow the Django Tutorial you'll run theses commands: django-admin startproject mysite # Change into the outer mysite directory cd mysite python manage.py startapp polls and you'll get this folder structure mysite/ ├── manage.py │ ├── mysite/ │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ └── pools/ ├── migrations/ │ └── __init__.py ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py └── views.py But if you follow Django REST Framework and you'll run these commands: Note: I replaced the directory names to match, for better comparison # Create the project directory mkdir mysite cd mysite # Set up a new project with a single application django-admin startproject mysite . # Note the trailing '.' character cd mysite django-admin startapp polls cd .. and you'll get this folder structure mysite/ ├── manage.py │ └── mysite/ ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py ├── wsgi.py │ └── polls/ ├── migrations/ │ └── __init__.py ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py └── views.py This is DFR's explanation: It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with … -
Django view - objects are created but not present in a DB
I have a DRF view that imports Product objects in the database. The problem is that while the transaction is alive, everything looks correct. The objects created have their ids (so they have been stored in a DB). The problem is that after the view returns a response, those objects are not present in the database anymore. get file (binary from request) store it in /tmp/product_imports/ call ImportService.import_csv(new_filepath) the method returns a number of products imported return a response from the view Everything looks good, the view returns a number (2 in my case as 3 from 5 products aren't valid). But when I check the DB, it's not there. @action(methods=['post'], detail=False) def import_csv(self, request, pk=None) -> Response: csv_file = request.FILES['file'] csv_import_files_dir = os.path.join('/tmp/project_imports/') csv_file_path = os.path.join(csv_import_files_dir, str(uuid.uuid4())) os.makedirs(csv_import_files_dir, exist_ok=True) with open(csv_file_path, 'wb') as f: f.write(csv_file.read()) count = product_services.imports.ImportService.import_csv(csv_file_path, request.user) return Response({'imported': count}) Main methods from ImportService @classmethod def import_csv(cls, filepath: str, created_by: User, delete_file=True) -> int: """imports products supplier_sku already exists ? skip product : add product """ cls.validate_csv(filepath) products_count = 0 with open(filepath) as f: reader = csv.DictReader(f) for row in reader: if not all([row.get(field, None) is not None for field in ['title', 'sku']]): continue row['title'] = row['title'][:99] … -
get() returned more than one Designated -- it returned 4
I am a student who is learning Janggo. You tried to insert the designated_code on Views.py, but the following error occurs: I don't know how to solve it at all. How can we solve this? The element.designed_code part of join_create seems to be the problem. I'd be really happy if you could help me solve the problem. I know that there are 4 products in the designated code, but I want to add the designated code that corresponds to the value of the selected value code. Error: get() returned more than one Designated -- it returned 4! Models.py class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = ['value_code'] class Designated(models.Model): designated_code = models.AutoField(primary_key=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') price = models.IntegerField() rep_price = models.BooleanField(default=True) class Meta: ordering = ['designated_code'] def __str__(self): return str(self.designated_code) class Element(models.Model): element_code = models.AutoField(primary_key=True) designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code') value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True) class Meta: ordering = ['element_code'] def __str__(self): return str(self.element_code) class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = models.DateTimeField(auto_now_add=True) def __str__(self): return … -
django user update form not updating
I have a detailed user view that has a button for user update. The user update form is inside a modal, for that I am using a FormView ModelForm and a TbUser. I dont get how the form validation works but the fields are correct. When I update something for a user, I get an error, TbUser with username already exists, which means the code does not update the user but tries to add a new one. Also, I want to redirect to user-detail page after submit. How can I redirect to user-detail if the form is invalid sometimes and not displaying errors? Why the user is not updated? Why the form is invalid? views.py class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, FormView): form_class = UserUpdateForm template_name = 'users/modals/user_update_modal.html' success_message = "User updated successfully." def get_form_kwargs(self): kw = super().get_form_kwargs() kw['request'] = self.request return kw def form_valid(self, form): obj = form.save(commit=False) print(obj.username) print('valid') TbUser.objects.filter(id=self.request.user.id).update(username=obj.username, real_name=obj.real_name, email=obj.email, cellphone=obj.cellphone, department=obj.department, role=obj.role) def form_invalid(self, form): messages.error(self.request, form.errors) # Where to redirect here? I want to def get_success_url(self): return reverse('user-detail', kwargs={'pk': self.formclass}) forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request if request.user.customer: self.fields['department'].queryset = TbDepartment.objects.filter( customer=request.user.customer) self.fields['role'].queryset = TbRole.objects.filter( customer=request.user.customer) class … -
Validating complex relationships in Django
I am developing a Django application that helps teachers' observation of students during lessons. I have defined models for Lesson and Student, and a FocusGroup model for the students to be observed during a given Lesson, The FocusGroup object has fields for observing Student behavior during a Lesson. A sample of Students are observed during the said Lesson, and the observations are to be registered in FocusGroupfields. As part of the teacher’s preparation for the givenLesson, he assigns that Lessonto a number of FocusGroupinstances (representingStudents) Now, the application needs to ensure, that the same Studentis assigned at most once to a givenLesson`. I do this in my template already, but I want to assure uniqueness on the server side as well. The diagram should illustrate this: My question is how I should assure the Lesson is assigned the same Student at most once. Should I do that in the FocusGroup model or in the receiving View? And how should I get this relationship assured safely in Django? My present implementation checks for FocusGroup-Lesson uniqueness, but with new FocusGroup instances generated, there is a chance that the same Student is represented by more than one of the FocusGroup instances assigned to … -
How to charge user for overdue books
1st Issue) I want to charge user for overdue books and I tried in model when bookissue instance created by overriding save() method but it is not that successful... In this case, is it a good practice to overriding save() method in BookIssue model to make charge user or in BookReturn model (I have bookreturn model) - do I need to create a separate table to do it? 2dn Issue) I tried to decrease a quantity by 1 once book issued by overriding save() method and worked well but once tried to increase quantity by 1 when issue book returned it did not work how can also implement it Models.py def get_expiry_date(): return date.today() + timedelta(days=10) class BookIssue(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) issue_date = models.DateField(auto_now_add=True) return_date = models.DateField(default=get_expiry_date) quantity = models.IntegerField(default=0) charge_amount = models.IntegerField(default=0) def __str__(self): return str(self.book) def save(self, *args, **kwargs): if not self.pk: self.book.quantity = self.book.quantity - 1 self.book.save() overdue_rate = 1.50 ####($1.50 per day) overdue_days = self.book.return_date > self.book.issue_date - timedelta(days=10) if overdue_days: self.book.charge_amount = overdue_days * 10 overdue_rate * ((date.today() - self.book.return_date) / 1).days self.book.save() super().save(*args, **kwargs) -
launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
^ SyntaxError: invalid syntax launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax django-admin wont run cause of the ABOVE ERROR -
DRF: Set language while testing
I have a serializer with a DateField that is localized according to the user's language settings. I would like to write a test and verify that the formatting is working correctly but I couldn't figure out how to set the reuqest language when using APIClient. That's how my test looks like: self.api_client = APIClient() # .... url = reverse("view_name", kwargs={...}) self.api_client.force_authenticate(user=self.user) response = self.api_client.get(url, format="json", follow=True) self.assertEqual(response.status_code, status.HTTP_200_OK) # asserts This way the test successfully works for my default language setting. How can I explicitly set the language code for this request. -
In Django how to disallow users to view other users page/results
I am working on a questionnaire and reporting site. The users fill out some questionnaire forms and they get a button on the results site that shows the user his own results. My problem is that I'm using the user_name_id in the url to show the right page (for example localhost:8000/mpa/7) to the user and I don't know how to limit the request.user to allow to see just his results. Now if a logged in user wants he can change the id in the url and can view other users results. views.py @login_required def main(request): gdpr_new = Gdpr_new.objects.filter(user_name=request.user) ... context = { 'gdpr_new': gdpr_new, ... } return render(request, 'stressz/main.html', context) urls.py app_name = 'stressz' urlpatterns = [ path('<int:user_name_id>/', views.results, name='results'), path('project_details/<int:projekt_id>/', views.project_details, name='project_details'), path('sum/<int:user_name_id>/', views.individual_sum, name='individual_sum'), path('main', views.main, name='main'), -
Marking only one answer as accepted
I am building simple Q & A site like Stack Overflow, and I am building marking a answer as accepted but when I implement than it is marking every answer as accepted. I mean User can accept every answer but I don't want this. I am trying to make - user can mark only one accepted answer. models.py class Answer(models.Model): answer_user = models.ForeignKey(User,on_delete=models.CASCADE) body = models.CharField(max_length=30,null=True) accepted = models.BooleanField(default=False) views.py def mark_accepted(request, question_id): post = get_object_or_404(Answer, pk=question_id) if request.GET.get('submit') == 'accept': if post.accepted == True: post.accepted = False else: post.accepted = True return JsonResponse({'action':'accept'}) template.html {% if data.accepted %} <button name='submit' type='submit' value="like"><i class=" fas fa-correct fa-6x " ></i></button> {% else %} <button name='submit' type='submit' value="like"><i class=" fal fa-correct fa-6x "></i></button> {% endif %} <script> $('.likeForm').submit(function (e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: thisElement.attr('action'), data: { 'submit': 'accept', }, dataType: 'json', method: 'get', if (response.action == 'accept') { accept ++ $(`#id_likes${thisElement.attr('data-pk')}`).html(`<button name='submit' type='submit' value="like"><i class=" fas fa-correct fa-6x "></i></button>`) // Followed $(`#followed_likes${thisElement.attr('data-pk')}`).html(`<button name='submit' type='submit' value="like"><i class=" fas fa-correct fa-6x "></i></button>`) } </script> -
Doesn't see my path in urls.py, page not found
I go to "http://127.0.0.1:8000/api/v1/personalities/?fio=ti" and see "Page not found". And the same page shows this path: api/v1/ personalities/ (?P<fio>.+)/$ Why doesn't it work? my main urls.py: path('personalities/', include('api.v1.personalities.urls')) personalities.urls.py: re_path('(?P<fio>.+)/$', PersonalitiesFilterView.as_view()) I followed the documentation from the django_filters website https://www.django-rest-framework.org/api-guide/filtering/ -
Django: multiple user types with abstract base class
I want to create multiple user types and roles depending on the user type while making the base user model abstract I tried something like this:- class CustomAccountManager(BaseUserManager): ..... class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=150, unique=True) email = models.EmailField(_('email address'), unique=True) firstname = models.CharField(max_length=150, blank=True, null=True) .... class Meta: abstract = true class Client(User): location = models.BooleanField(_(""), default=True) history = models.BooleanField( _(""), default=True) ip = models.BooleanField(_(""), default=True) def __str__(self): return self.username class Vendor(User): Storesmtn = models.ImageField( upload_to="Images", max_length=100000, default="default/default.png") Storesmtn = models.ImageField( upload_to="Images", max_length=100000, default="default/default.png") Storesmtn = models.CharField(max_length=220, blank=False, unique=True) when I migrate the following error appears:- users.Client.groups: (fields.E304) Reverse accessor for 'users.Client.groups' clashes with reverse accessor for 'users.Vendor.groups'. HINT: Add or change a related_name argument to the definition for 'users.Client.groups' or 'users.Vendor.groups'. users.Client.user_permissions: (fields.E304) Reverse accessor for 'users.Client.user_permissions' clashes with reverse accessor for 'users.Vendor.user_permissions'. HINT: Add or change a related_name argument to the definition for 'users.Client.user_permissions' or 'users.Vendor.user_permissions'. users.Vendor.groups: (fields.E304) Reverse accessor for 'users.Vendor.groups' clashes with reverse accessor for 'users.Client.groups'. HINT: Add or change a related_name argument to the definition for 'users.Vendor.groups' or 'users.Client.groups'. users.Vendor.user_permissions: (fields.E304) Reverse accessor for 'users.Vendor.user_permissions' clashes with reverse accessor for 'users.Client.user_permissions'. HINT: Add or change a related_name argument to the definition for 'users.Vendor.user_permissions' or … -
is_superuser flag is not working correctly once loggin and not redirecting to a custom admin dashboard
Once trying to login to the system with a superuser's credentials it is not working properly and redirecting home page instead of custom admin page. The system is treating both superuser and a normal user equally in views but is_superuser flag is working when I use in templates for ex, showing different links in navbar and I am using signals to create user instance. Views.py def custom_user_login(request): if request.method == "POST": username = request.POST.get("username", "") password = request.POST.get("password", "") user = authenticate(request, username=username, password=password) if request.user.is_superuser: login(request, user) return redirect("admin_page") else: login(request, user) return redirect("home") else: form = LoginForm() return render(request, "registration/login.html", {"form": form}) Models.py class User(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=250) id_number = models.CharField(max_length=50) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def post_user_created_signal(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(post_user_created_signal, sender=User) -
Django annotate Multiple Sum with one Many to Many field
Lets take this models: class Computer(models.Model): name = models.CharField(max_length=100, null=False, blank=False) cpu = models.PositiveIntegerField(null=False, blank=False) ram = models.PositiveBigIntegerField(null=False, blank=False) customer = models.ForeignKey( Customer, related_name='Computers', on_delete=models.SET_NULL, null=True, blank=True ) class Disk(models.Model): computer = models.ForeignKey( Computer, related_name='Disks', on_delete=models.CASCADE, null=False, blank=False ) size = models.PositiveBigIntegerField(null=False, blank=False) class Customer(models.Model): name = models.CharField(max_length=255, blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField( blank=False, null=False, default=False) I want list, by customer, the total number of CPU, RAM, and disk size (with the number of computer for each customer). something like this: {'customer': ACME_Corp., 'cpu__sum': 72, 'ram__sum': 10737418240, 'computer__sum': 10, 'disks__sum': 10000000000000} I tried something like that: Computer.values('customer').annotate(Sum('cpu'), Sum('ram'), Sum('Disks__size'),computer__sum=Count('computer_id')) The problem is: If a computer has multiple Disk, I am going to add his cpu (RAM and count) as many time as his number of disk for example if we have 2 computers with 1 cpu each, but one of them has two disks attached, the cpu total will not be 2, but 3... Any help will be appreciated, thank you !! -
hls.js audio track selection controls missing
I'm using hls.js to playback a m4s encoded http-live-stream. The master.m3u8 file references multiple audio tracks and also references multiple subtitles for my video. I noticed that subtitle track selection is working fine but audio track selection is simply not available at the player controls at all, why that?. I'm using hls.js like so: <script src="{% static 'js/hls.js' %}"></script> <video id="video"></video> <script> if(Hls.isSupported()) { var video = document.getElementById('video'); var hls = new Hls(); hls.loadSource('https://example.com/master.m3u8'); hls.attachMedia(video); hls.on(Hls.Events.MANIFEST_PARSED,function() { video.play(); video.controls = true }); } </script> Is there a way to have these controls added? To me it seems that the player at least supports it. If I take a closer look at the hls.js demo resources right here: https://hls-js.netlify.app/demo/ At the very bottom of the page it shows "Audio-tracks". Using my m3u8 file at the demo page also allows me the change the audio track on-the-fly but its basically outside the player. Thanks in advance -
Why mongoDB is being used in django project
As we know we can build great application with django using postgresql database or additional scalability and feature, sometime we use redis I have notice some people using mongodb in their django project. My question is, what is the case and what specific purpose they are using mongoDB in their django project. Why can't those feature can't be achieved by postgresql or redis? -
Python SMTP - 'linesep' is an invalid keyword argument for encode()
I'm getting the following error in my Django project: 'linesep' is an invalid keyword argument for encode() Python version 3.8.2 and Django version 3.2.4. Here is my code. I'm getting the error when sendmail is being executed. try: sender = settings.SMTP_HOST_USER message = html_message msg = MIMEText(message, 'html') msg['Subject'] = subject msg['From'] = sender msg['To'] = recipient server = smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) server.login(settings.SMTP_HOST_USER, settings.SMTP_HOST_PASSWORD) server.sendmail(sender, recipient, msg.as_string()) server.quit() return True except Exception as exp: print(str(exp)) return False