Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Tinymce file tinymce.min.js not found
i am trying to integrate tinymce with a django app but django can't find the tinymce javascript file this is my settings.py : BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' MEDIA_URL = 'media/' STATICFILES_DIRS = [BASE_DIR/"staticfiles"] STATIC_ROOT = BASE_DIR/"static_root" MEDIA_ROOT = BASE_DIR/"media_root" #TinyMce TINYMCE_JS_URL = os.path.join(STATIC_URL, "tinymce/js/tinymce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "tinymce/js/tinymce") TINYMCE_DEFAULT_CONFIG = { 'height' : 300, 'plugins': "image,imagetools,media,codesample,link,code,paste", 'cleanup_on_startup': True, 'menubar': True, 'toolbar': "styleselect |undo redo | bold italic | alignleft aligncenter alignright | link image media codesample code", 'image_caption': True, 'image_advtab': True, 'paste_as_text': True, 'custom_undo_redo_levels': 10, 'file_browser_callback' : "myFileBrowser" } and on localserver logs i have this : [10/Mar/2023 22:48:14] "GET /static/static/tinymce/js/tinymce/tinymce.min.js HTTP/1.1" 404 1980 but i this it should be : [10/Mar/2023 22:48:14] "GET static/tinymce/js/tinymce/tinymce.min.js HTTP/1.1" 404 1980 -
How to style django forms
I am trying to make an interactive from similar to the one shown in this image I am using python django, I am looking to incorporate react if its needed! I have searched youtube for interactive forms and nothing in this similar style shows nor on Google! -
DRF GET serializer: get parent id in a nested relationship (extra fields in a nested manytomany relationship with through model)
Having the following models class House(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=1024, blank=True) zone = models.ForeignKey(Zone, on_delete=models.CASCADE) vehicles = models.ManyToManyField(Vehicle,through="VehicleHousing", through_fields=('house', 'vehicle'),) habitants = models.ManyToManyField(settings.AUTH_USER_MODEL,through="UserHousing", through_fields=('house', 'habitant'),) def __str__(self): return self.name class CustomUser(AbstractUser): username = models.TextField(default=None, blank=True, null=True) email = models.EmailField(_('email address'), unique=True) phone_number = models.CharField(max_length=12,default=None, blank=True, null=True) houses = models.ManyToManyField(House,through="UserHousing", through_fields=('habitant', 'house'),) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class UserHousing(models.Model): register_date = models.DateTimeField(auto_now_add=True, editable=False) habitant = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) house = models.ForeignKey(House, on_delete=models.CASCADE) isAdmin = models.BooleanField(default=False) class Meta: unique_together = [['habitant', 'house']] The user model is a custom user model replacing the base one, of course replaced in the settings.py AUTH_USER_MODEL I got the following serializers to get the data to the view: class UserBasicInfoSerializer(serializers.ModelSerializer): admin = serializers.SerializerMethodField('get_admin') def get_admin(self, obj): admin = UserHousing.objects.get(habitant=obj).isAdmin return admin class Meta: model = get_user_model() fields = ['id', 'email', 'first_name', 'last_name', 'phone_number', 'admin'] class VehicleSerializer(serializers.ModelSerializer): class Meta: model = Vehicle fields = ['id','license_plate','brand','model','hexcolor'] class HouseSerializer(serializers.ModelSerializer): habitants = UserBasicInfoSerializer(many=True, read_only=True) vehicles = VehicleSerializer(many=True, read_only=True) class Meta: model = House fields = ['id','name', 'address', 'vehicles', 'habitants'] class UserFullInfoSerializer(serializers.ModelSerializer): houses = HouseSerializer(many=True, read_only=True) class Meta: model = get_user_model() fields = ['id', 'email', 'first_name', 'last_name', 'phone_number', 'houses'] Ending up with the … -
python-oracledb Executing PLSQL not working
Im trying to execute the example in python-oracledb example. But every time the server reloads I get the following error. django.db.utils.NotSupportedError: Python value of type VariableWrapper not supported. Here is my views.py from django.views.generic import TemplateView from django.db import connection import oracledb class Profile(TemplateView): """blarg""" template_name = 'profile.html' cursor = connection.cursor() out_val = cursor.var(int) cursor.callproc('myproc', [123, out_val]) print(out_val.getvalue()) # will print 246 I can confirm the procedure is created inside a package in the database. -
Change model fields if type is different
I have two services: Job and Server. They are quite similar, but Server also has fields "host" and "port". I need the model to recognize the service type, and if it is Job it must set "host" and "port" fields to None automaticly and save it to db table. Is it possible? I`ve tried to use different types of validators in Serializer, but nothing worked. Here is my model: class Service(models.Model): class ServiceType(models.TextChoices): JOB = 'Job', _('Job') SERVER = 'Server', _('Server') type = models.CharField(max_length=10, choices=ServiceType.choices, default=ServiceType.JOB) code_name = models.CharField(max_length=200) human_name = models.CharField(max_length=200) description = models.CharField(max_length=200) host = models.CharField(max_length=200) port = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(65535)]) def __str__(self): return self.type As you can see, there can be only two types: Server and Job. And I need to automacitally set host and port fields to None, if type == 'Job'. Sounds easy, but I think Im not expirienced enough to find out the solution. Ive also tried to use validator in my Serializer, but it didn`t help: class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = '__all__' def validate(self, data): if data['type'] == 'Job': data['host'] = None data['port'] = None return data I expect to see host and post fields in database equal to … -
Unsure why Django model form many to many field validation failing on is_vaild()
I have the following form and model in my django app: Form: class AdditionalDealSetupForm(ModelForm): required_css_class = "required" lead_underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), label="Lead Underwriter(s):", required=False, widget=forms.SelectMultiple( attrs={"class": "lead_underwriter"} ), ) underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), required=False, label="Underwriter(s):", widget=forms.SelectMultiple(attrs={"class": "underwriter"}), ) class Meta: model = AdditionalDeal fields = [ "cutoff_date", "closing_date", "deal_private", "lead_underwriters", "underwriters", ] Model: class AdditionalDeal(TimestampedSafeDeleteModel): id: PrimaryKeyIDType = models.AutoField(primary_key=True) # Relations deal_setup: ForeignKeyType[t.Optional["DealSetup"]] = models.ForeignKey( "DealSetup", on_delete=models.SET_NULL, null=True, blank=True, related_name="additional_deal_set", ) if t.TYPE_CHECKING: deal_setup_id: ForeignKeyIDType lead_underwriters = models.ManyToManyField( Underwriters, related_name="DealLeadUnderwriter" ) underwriters = models.ManyToManyField(Underwriters, related_name="DealUnderwriter") class Meta: db_table = "Additional_Deal" verbose_name_plural = "Additional Deal" unique_together = ("deal_setup",) So I have a multi select form on the front end that can create new tags/ underwriters which are instances of the Underwriters model. When I try to submit the form the newly returned value from the form that does not exist in the Underwriters model already is failing validation. Right now I am creating the new Underwriter objects before I call is_valid() on the form object. I cant figure out why this is. I tried overriding some of the ModelForm clean_* methods but they are not getting called as I expected to before this failed validation: -
Django SimpleListFilter: ValueError not enough values to unpack (expected 2, got 0)
Context: I'm creating a custom input filter in Django using the SimpleListFilter class. I've followed the steps in here https://hakibenita.com/how-to-add-a-text-filter-to-django-admin, but I'm encountering a ValueError when trying to use the filter. Here is my code: filters.py: from django.contrib import admin from django.db.models import Q class InputFilter(admin.SimpleListFilter): title = 'Language' parameter_name = 'language' template = 'admin/input_filter.html' def lookups(self, request, model_admin): # Dummy, required to show the filter. return ((),) def queryset(self, request, queryset): if self.value(): return queryset.filter(Q(language__icontains=self.value())) def choices(self, changelist): all_choices = super().choices(changelist) query_params = changelist.get_filters_params() if not self.lookup_choices: return [] for lookup, title in self.lookup_choices: query_parts = changelist.get_query_string({self.parameter_name: lookup}).split('&') if query_parts and len(query_parts) >= 2: query = '&'.join([f'{k}={v}' for k, v in query_parts]) choice = { 'query_string': f'?{query}&{query_params}', 'display': title, 'selected': self.value() == lookup, } all_choices.append(choice) return all_choices I get the following error when accessing the admin page: ValueError at /repoman/admin/aws_storage/raw_file/ not enough values to unpack (expected 2, got 0) I'm not sure what is causing this error or how to fix it. Any help would be appreciated! -
CSRF error when making POST request to Django API
I am currently developing an application that has a React JS front end and Python Django backend. After successfully logging in, the backend created the necessary cookies, which includes the CSRF token, however when the front end makes a POST request the API returns an error with: "CSRF Failed: CSRF token missing or incorrect" even though the CSRF token is within the cookies that are passed to the API. I have looked online and the fix is to include the CSRF token in the X-CSRFToken header, which I have successfully tested by manually putting the CSRF token in the front end code when it makes the API call. When I try to use Cookies.get('csrftoken'), or even just console.log(document.cookie), it does not return anything because the domain of the CSRF token is the backend URL and therefore different to the front end domain so it does not let me use it within the frontend code. Is there a way for me to use the CSRF token in the cookie to validate the request within the API or can I somehow access it within the frontend to pass it via the X-CSRFToken header even though it is a different domain? I have … -
Using pyarmor in a django project with celery
I'm using pyarmor to obfuscate my django project, following this steps: pyarmor init --entry=manage.py pyarmor build Running the content in dist/, works fine. But I would like running celery too. It's possible? Do I need put it in init too? -
Django admin, how can I add the FK selector in a StackedInline record
Given the following models : class Person(models.Model): name = models.CharField(max_length=50) family = models.ForeignKey( "Family", related_name="members", on_delete=models.CASCADE ) def __str__(self) -> str: return self.name class Family(models.Model): name = models.CharField(max_length=50) def __str__(self) -> str: return self.name And the following admin settings : class PersonAdmin(admin.StackedInline): model = Person list_display = ("name", "family") extra = 0 class FamilyAdmin(admin.ModelAdmin): model = Family list_display = ("name",) inlines = [PersonAdmin] extra = 0 admin.site.register(Family, FamilyAdmin) I would like to be able, from the Family edit page, to change the family of a person. Say I have Person A belonging to Family 1, I would like to be able to "migrate" this person to another family from the family edit page. Unfortunately, even if I explicitly specify the fields in the PersonAdmin class, the dropdown won't show. Any help or even a simple tips to know where and what to look would be greatly appreciated. I've tried looking for a solution on Django Admin Cookbook, on Google and on SO, but haven't found a solution to this and I'm pretty much a django (admin) noob. -
Django Static File not Updated
I am working on Django 4.1 on Windows locally and found that my static file did not update when I modified it, even the content showed on http://127.0.0.1/static/app_name/styles/css_name.css is the old CSS file. This issue suddenly happened after almost 1 year of development. In setting.py: DEBUG = True STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') And I have already tried the following method: Hard Reload Ctrl+F5 Clear Browser Cache Reboot/Restarting Browser/Server/Computer Run server on another port Open in Incognito Window Use another Computer to Test Ran python manage.py collectstatic/python manage.py collectstatic --clear/python manage.py collectstatic --noinput --clear, in here I found that after I ran this command, the modified static files will change back to the original unmodified version. Add a random tag at the end when loading the static file, /static/app_name/styles/css_name.css?v=aCtZoGSzObVTeNCAbWjPyLpyStrYek6A In setting.py add STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' Add the following in urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, view=cache_control(no_cache=True, must_revalidate=True)(serve)) All of the above methods didn't solve my issue. I saw someone has suggested Restart gunicorn/nginx will help, but seem it is on Linux but not Windows. What can it be? Maybe Django is saving some old static files somewhere and fetches them every time? -
How to let an authenticated user like a blog post in Django, update the like count and change the color of the heart icon
I started building my first Django Project a few days ago and I've been making progress, but for the past two days I've been stuck with the problem stated in the post's title. I can't seem to implement the like functionality in my web application. I'm going to just post the parts of my code that I believe would be helpful in aiding me. so, in my models.py I have - class Post(models.Model): image = models.ImageField() title = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts', default='uncategorized') post = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) in my views.py I have - @login_required def like_post(request, post_id): post = get_object_or_404(Post, pk=post_id) if request.method == 'POST': if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 else: post.likes.add(request.user) post.like_count += 1 like = Like(user=request.user, post=post) like.save() post.save() return JsonResponse({'like_count': post.like_count}) else: return HttpResponseBadRequest() in my urls.py I have - path('like_post/<int:post_id>/', views.like_post, name='like_post') in my post_list.html I have - <form method="POST" action="{% url 'article:like_post' post.pk %}"> {% csrf_token %} <button class="like-button" data-post-id="{{ post.id }}"><i class="fas fa-heart{% if post.likes.filter(id=request.user.id).exists %} liked{% endif %}"></i>{{ post.like_count }}</button> {% endif %} <button class="comment-button"><i class="fa-solid fa-comment"></i>5 comments</button> </form> underneath the … -
django "copyOnWrite" for default model instances
Suppose I have a django application that provides Exercises. Those exercises have sub-categories and principles they belong to. Each Exercise belongs to one or no user. Simplyfied, they look like that: model Category(models.Model): owner = models.ForeignKey(AUTH_USER_MODEL, null=True, default=None) name = models.TextField() model SubCategory(models.Model): name = models.TextField() category = models.ForeignKey(Category, null=False) model Exercise(models.Model): owner = models.ForeignKey(AUTH_USER_MODEL, null=True, default=None) sub_categories = models.ManyToManyField(SubCategory) principles = models.ManyToManyField(Principles) # some other fields # ... What I want, is provide defaults (owner = None) for newly registered users. This would mean copying all principles, categories, subcategories and exercises upon the users registration. In addition, if I want to add a new exercise as default, I have to copy it for every user. I have already implemented the logic for copying everything (exchanging the foreign keys, etc.) This means that every user operates on their own set of data. No special cases except for the creation of new defaults. However, suppose I have 500 users and 100 default exercises, this amounts to 50k exercises alone. (Not to speak about the ~10 categories, with ~20 sub-categories each and ~120 principles) Seems not to scale too well. My second approach is some sort of "copy on write", where I … -
DJango forms that allow you to change the database of a specific user
I'm creating a Django social network application. My function intakes the request from a logged in user and changed their respective details based on the input of their forms. Forms.py class ProfileForm(forms.ModelForm): class Meta: model = AppUser fields = ['bio','profileimg'] Model.py class AppUser(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blank-profile-picture.png') def __str__(self): return self.user.username settings.html <form id="profile_form" method="post" action="/home/" enctype="multipart/form-data"> {% csrf_token %} {{ profile_form.as_p }} <input type="submit" name="submit" value="submit" /> </form> This is my current views code: `def settings(request): user_profile = AppUser.objects.get(user=request.user) if request.method == 'POST': profile_form = ProfileForm(request.POST or None,request.FILES or None, instance=user_profile) if profile_form.is_valid(): profile_form.save() else: return HttpResponse('Form is invalid') else: profile_form = ProfileForm(instance=user_profile) return render(request, 'settings.html', {'profile_form': profile_form})` I tried running the code but nothing happens in the database -
Django and celery tasks - how to display celery progress when redirecting
Hi I have a broad question about using celery, redis and django (along with celery-progress). I have a django cbv with a form. Upon a post request this starts some celery processes and I use a modified version of celery-progress to update the page with a progress bar for each task. I'm struggling to find the best way to do this in terms of redirection of the request. I have tried two ways: 1. class MyView(FilterView) template_name = '/path/to/template1.html' # code to create form in django-tables2 def post(self, request, *args, **kwargs): self.context = {'server': SERVER} submit = request.POST.get('submit', None) if submit: ids = request.POST.getlist('report_form') # get queryset from selected IDs qs = MyModel.objects.filter(id__in=ids) # create empty dictionary to store id and celery task task_dict = {} # loop through queryset for obj in qs: # execute report creator method (celery task) task = self.celery_create_reports(id=obj.id, user_id=request.user.id) # add obj as key and task id as value to dict task_dict[obj] = task.id logger.info(task.id) logger.info(f"task_dict={task_dict}") # add dict to context context = {'task_dict': task_dict,} # direct to different template template_name = '/path/to/template2.html' return render(request, template_name, context) return render(request, self.template_name, self.context) def celery_create_reports(self, id, user_id): """ """ # execute task return download_technical_reports.delay(id=id, user_id=user_id) ^ … -
cumulative sum on jsonfield dict - django - postgresql
I have a fixed set of product_ids (eg 0, 1, 2, 3) My shoppingcart model has a jsonfield containing a dict indicating how many products it has of each product_id: from django.db import models class ShoppingCart(models.Model): stats = models.JSONField() With for one object stats may be: stats = { "0": 4, # has 4 products of id 0 "3": 1, # has 1 product of id 3 } And another object my have: stats = { "0": 1, # has 1 product of id 0 "1": 1 # has 1 product of id 1 } Now I would like to calculate how many products there are in total of each product id, preferably using database functions on the jsonfield in django. For this example, the result should be: counts = { "0": 5, "1": 1, "2": 0, "3": 1 } Is there an efficient way of calculating this? Don't really know how to tackle this without looping over all objects. -
Django rest framework permission by custom role
I using Django Rest Framework and I have custom User model where is column Role and Hash Model.py class User(AbstractUser): Role = models.CharField() Hash = models.CharField() Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'Role', 'Hash','is_staff') View.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated] this working fine! And my question is possible create view which show fields according by Role? For example... If user with admin role login then see everything.. fields = ('id', 'username', 'first_name', 'last_name', 'Role', 'Hash','is_staff') But if login user with role for example mamager then he see just this. fields = ('id', 'username', 'first_name', 'last_name', 'Role','is_staff') -
zsh: command not found: python | I just want my python files to run again
I was messing around with Django for a task on my bootcamp and now my VSCode won't run my python files using the run button in the top right. Here's what I see in my IDE: garethmorton@MacBook-Pro T28 2D Lists % python -u "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" zsh: command not found: python garethmorton@MacBook-Pro T28 2D Lists % If I right click and select run Python file in terminal my code runs and I get this: /usr/local/bin/python3 "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" garethmorton@MacBook-Pro T28 2D Lists % /usr/local/bin/python3 "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" How do I fix the file path so that I can just run the code like I used to? thanks I have tried a few things I was told to do but to be honest I don't understand it enough to explain. I would love to just be able to delete the IDE and reinstall. By the way I'm on mac so I'm not sure if that makes things more complicated I definitely have the python extension installed.. everything should be installed and ready because ive been running python code for months on my bootcamp -
Does indentation matter in django?
{% if object.name== '' %} {% block name %}{{ object.name}}{% endblock name %} {% else %} {% block name %} {{ object.alternate_name}} {% endblock name %} {% endif %} I have this code in Django and for some reason, I get the error that the block name has been repeated twice and that seems impossible because they're inside an if-else statement. However, I realized my indentation looks like it did above. I'm not sure whats causing this. -
Ckeditor - RichTextField in Template doesn't work - Django
I am trying to display the RichTextField in a Django Template. In the Admin Panel it works but not in the template. My Template called create.html: {% block main %} <div class="blocker" style="height: 100px;"></div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Absenden</button> </form> {% endblock %} Forms.py: class Create(forms.ModelForm): content = RichTextField() title = forms.CharField(label='title', max_length=100) class Meta: model = Post fields = ['title', 'content'] Views.py def create(request): if request.method == 'POST': form = Create(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] Post(title=title, content=content).save() return redirect("../blog") else: form = Create() return render(request, 'create.html', {'form': form}) Thanks for answering :D I tried different things in the forms. -
Task not executed in Django's Celery
Since I am not an English speaker, I use translation tools to write my text. Please help me. Task not executed Here are the execution environment and messages Local PC OS windows 10 Python 3.8 DB Server CentOS 7.3 Redis 4.0.6 psql (PostgreSQL) 10.4 pip Package (relevant parts only) Package Version celery 5.2.7 Django 3.2 django-celery-results 2.4.0 django-redis 5.2.0 redis 4.1.1 *PROJECT\prj\settings.py CELERY_BROKER_URL = 'redis://:' + REDIS_PASSWORD + '@' + REDIS_HOST + ':6379/1' CELERY_RESULT_BACKEND = 'django-db' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TIMEZONE = 'Asia/Tokyo' CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 PROJECT\prj_init_.py from .celery import app as celery_app __all__ = ('celery_app',) PROJECT\prj\celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prj.settings') app = Celery('prj') app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') PROJECT\common\task.py from celery import shared_task @shared_task def load_croeds_csv(csv_file): print("start") print("end") return "ok" PROJECT\manegements\view.py class ProhibitedAreaCsvRegView(ContextRootStaff, FormView): template_name = 'manage/prohibited_area_csv.html' form_class = ProhibitedAreaCsvForm def get_context_data(self, **kwargs): context = super(ProhibitedAreaCsvRegView, self).get_context_data(**kwargs) title = "" context.update({ 'title': title, 'form': self.form_class() }) return context def form_valid(self, form): context = self.get_context_data(form=form) csv_file = form.cleaned_data["csv_file"] temp_path = save_csv_file(csv_file) result = load_croeds_csv.delay(temp_path) print(result.state) context.update({ 'result': result }) return self.render_to_response(context=context) (venv) PROJECT>celery -A prj worker -l info -------------- celery@HP1-USER10 v5.2.7 (dawn-chorus) --- … -
Django model unique constraint based on existing model data?
Is it possible to make reference to existing model data, as part of a Django unique constraint check? For example, class MyModel(models.Model): .... my_field = models.IntField(...) class Meta: constraints = [ models.CheckConstraint( check=models.Q(my_field__gte=MyModel.objects.all().last().my_field, name="example_constraint" ] In this pseudocode example, I query MyModel, fetching the latest record, and use the value of it's 'my_field' property as part of the constraint, when adding a new MyModel. -
How to change string representation in django
I have model with a str function def __str__(self): return f"{self.first_name} {self.last_name}" //output for example foo bar Now i a specific form with a dropdown menu filled with the model above. In the dropdown menu the options are showed as the str from the model (sow foo bar). In this model however i want to show only the lastname. How can ik change the str function for just this form ? -
Why django showing 'function' object has no attribute 'objects'?
'function' object has no attribute 'objects' is being shown when I try to fetch objects from database I was following code with harry playlist on django ,and trying to fetch product from database my problem.I have created 3 products in admin panel. I saw some solutions to my problem ,where the problem was solved by changing the function name. But my problem seems to be different. this is my models.py enter image description here function in view.py where I make the call....error showing on the line7 enter image description here trying to render it in html enter image description here -
How do I stop the camera after QR code is scanned?
I am using instascan.min.js for my QR scanner. According to the documentation, I simply need to add in scanner.stop() to my script to terminate the camera session once it has scanned a QR code. I am not sure where in the javascript code I can add that line or am I supposed to write another function? Have been stuck on this for quite some time. Hope to seek any assistance. Thank you! <script> var app = new Vue({ el: '#app2', data: { scanner: null, activeCameraId: null, cameras: [], scans: [] }, mounted: function () { var self = this; self.scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5}); self.scanner.addListener('scan', function (content, image) { self.scans.unshift({ date: +(Date.now()), content: content }); }); Instascan.Camera.getCameras().then(function (cameras) { self.cameras = cameras; if (cameras.length > 0) { self.activeCameraId = cameras[0].id; self.scanner.start(cameras[0]); } else { console.error('There is no camera.'); } }).catch(function (e) { console.error(e); }); }, methods: { formatName: function (name) { return name || '(unknown)'; }, selectCamera: function (camera) { this.activeCameraId = camera.id; this.scanner.start(camera); this.scanner.stop(camera) } } }); </script>