Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i send a vuejs array to django rest api
i want to send an array of inputs to my django rest api. I can fill the array with data, but i always got an error message when i tried to send to the rest api. I have already tried to use the ArrayField() option in django but it didnt work. -
ValueError at /category/economy/: Field 'id' expected a number but got 'economy'
I try to add new path and this happen "Field 'id' expected a number but got 'economy'." in traceback the highlighted line is in the views.py file which i mentioned below. category_posts = Post.objects.filter(category=cats) I am sharing my files plz help me to get rid of the issue. urls.py urlpatterns = [ path('',views.allpost,name="allpost"), path('search', views.search, name="search"), path('contact/', views.contact, name="contact"), path('success/', views.successView, name="success"), path('category/<str:cats>/', views.CategoryView, name ="category"), path('<int:blog_id>/',views.detail,name="detail"), ] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) here i used str:cats, yet it shows "Field 'id' expected a number but got 'economy'." views.py def CategoryView(request, cats): # here cats is same which mentioned in dynamic url. category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts}) "category_posts = Post.objects.filter(category=cats)" this line of code shows in traceback models.py from django.db import models class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") title = models.CharField(max_length=255, verbose_name="Title") parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank= True, null=True) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) public_date = models.DateField(null=True) public_time = models.TimeField(null=True,default="") category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category", null=True) image = models.ImageField(upload_to='images/',null=True, blank=True) body = models.TextField() class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['public_date'] def summary(self): return self.body[:100] def pub_date(self): return … -
After installing fobi from https://pypi.org/project/django-fobi/ and try localhost:8000/admin getting error
I followed the https://pypi.org/project/django-fobi/ instalation instructions, and after pip install django-fobi into my venv I set my settings.py as follows ` INSTALLED_APPS = [ 'dose.apps.DoseConfig', 'django.contrib.admin', 'django.contrib.contenttypes', # Used by fobi 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'aiengine', 'fobi', # `django-fobi` themes 'fobi.contrib.themes.bootstrap3', # Bootstrap 3 theme 'fobi.contrib.themes.foundation5', # Foundation 5 theme 'fobi.contrib.themes.simple', # Simple theme # `django-fobi` form elements - fields 'fobi.contrib.plugins.form_elements.fields.boolean', 'fobi.contrib.plugins.form_elements.fields.checkbox_select_multiple', 'fobi.contrib.plugins.form_elements.fields.date', 'fobi.contrib.plugins.form_elements.fields.date_drop_down', 'fobi.contrib.plugins.form_elements.fields.datetime', 'fobi.contrib.plugins.form_elements.fields.decimal', 'fobi.contrib.plugins.form_elements.fields.email', 'fobi.contrib.plugins.form_elements.fields.file', 'fobi.contrib.plugins.form_elements.fields.float', 'fobi.contrib.plugins.form_elements.fields.hidden', 'fobi.contrib.plugins.form_elements.fields.input', 'fobi.contrib.plugins.form_elements.fields.integer', 'fobi.contrib.plugins.form_elements.fields.ip_address', 'fobi.contrib.plugins.form_elements.fields.null_boolean', 'fobi.contrib.plugins.form_elements.fields.password', 'fobi.contrib.plugins.form_elements.fields.radio', 'fobi.contrib.plugins.form_elements.fields.regex', 'fobi.contrib.plugins.form_elements.fields.select', 'fobi.contrib.plugins.form_elements.fields.select_model_object', 'fobi.contrib.plugins.form_elements.fields.select_multiple', 'fobi.contrib.plugins.form_elements.fields.select_multiple_model_objects', 'fobi.contrib.plugins.form_elements.fields.slug', 'fobi.contrib.plugins.form_elements.fields.text', 'fobi.contrib.plugins.form_elements.fields.textarea', 'fobi.contrib.plugins.form_elements.fields.time', 'fobi.contrib.plugins.form_elements.fields.url', # `django-fobi` form elements - content elements 'fobi.contrib.plugins.form_elements.test.dummy', 'easy_thumbnails', # Required by `content_image` plugin 'fobi.contrib.plugins.form_elements.content.content_image', 'fobi.contrib.plugins.form_elements.content.content_image_url', 'fobi.contrib.plugins.form_elements.content.content_text', 'fobi.contrib.plugins.form_elements.content.content_video', # `django-fobi` form handlers 'fobi.contrib.plugins.form_handlers.db_store', 'fobi.contrib.plugins.form_handlers.http_repost', 'fobi.contrib.plugins.form_handlers.mail', 'fobi.contrib.plugins.form_handlers.mail_sender', ] and I edited mysite.urls.py ` urlpatterns = [ path('instruction/', InstructionListView.as_view()), path('dose/', include('dose.urls')), path('admin/', admin.site.urls), # View URLs re_path(r'^fobi/', include('fobi.urls.view')), # Edit URLs re_path(r'^fobi/', include('fobi.urls.edit')), # DB Store plugin URLs re_path(r'^fobi/plugins/form-handlers/db-store/', include('fobi.contrib.plugins.form_handlers.db_store.urls')), ` I get this error on runserver it was all working before installing fobi ` File "C:\Users\viter\base\dosehomev3\dosehome\venv\lib\site-packages\django\contrib\sites\models.py", line 39, in _get_site_by_request SITE_CACHE[host] = self.get(domain__iexact=host) File "C:\Users\viter\base\dosehomev3\dosehome\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\viter\base\dosehomev3\dosehome\venv\lib\site-packages\django\db\models\query.py", line 650, in get raise self.model.DoesNotExist( django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. ` I expected to get … -
Getting Token from Django Model to views
I created a user model in Django i want to know what JWT token is generated for my particular user in the views.py section could you please help class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status=models.IntegerField(default=1) phone=models.IntegerField(blank=True,null=True) otp=models.IntegerField(blank=True,null=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) #locations=models.ManyToManyField(Location) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokensd(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } -
cannot display classes of courses
I am trying to create an educational website using django, so I have two models class and course which have a one-to-many foreignkey relationship between them i.e. one course can have several class but one class can only have one course. But this creates a problem for me. That is, in my course_detail_view I have assigned the model course. So I cannot render classes in my html file. Can anyone help me solve this ? My models.py: class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) students = models.ManyToManyField(User, related_name='courses_joined', blank=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title class Class(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='class/class_videos',null=True, validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, related_name='classes') def __str__(self): return self.title My views.py: class CourseDetailView(LoginRequiredMixin, DetailView): model = Course template_name = 'class/course.html' Thanks in advance! -
Django export to xlsx with lock columns
I have this code for exporting data to CSV. How can I lock some columns in this file? For example: lock 'id' and 'Subsidiary' that the the user won't be able to edit views.py def combinationExport(request): combination = Combination.objects.all() response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = 'attachment; filename="Combination.csv"' writer = csv.writer(response) writer.writerow( [ "id", "Subsidiary", "Department", "Account", "Sub Budget", "Budget Owner", "Sub Budget Owner", ] ) combo = combination.values_list( "id", "subsidiary__name", "department__name", "account__name", "sub_budget__name", "budget_owner__budget_owner__name", "budget_owner__sub_budget_owner__name", ) for q in combo: writer.writerow(q) # print(q) return response TNX -
How to add default value for Date Picker in Django Model Form
Currently I have a date picker in a django model form that works perfectly fine. However, I want to add an initial (default) value to it. Here is my current code : class DatePickerInput(forms.DateInput): input_type = 'date' class PDFClassificationForm(forms.ModelForm): class Meta: model = Documents fields = [ 'id_documenttype', 'dateenvoi',, 'comment'] widgets = { 'dateenvoi' : DatePickerInput(), } I tried adding initial as a parameter to DatePickerInput() like so : widgets = { 'dateenvoi' : DatePickerInput(initial= datetime.now().strftime('%d/%m/%y %H:%M:%S')), } However it was unsuccessful, any suggestions ? -
Django Not Creating Model Objects After Retrieving Data From External Payment API
I created an app for table ordering (basically like an ecommerce website) that has 3 models: class Dish(model.Models): some other fields() class Cart(model.Models): customer = models.ForeignKey(User) session_key = models.CharField(max_length=40) dish = models.ForeignKey(Dish) order = models.ForeignKey(Order) paid = models.CharField(max_length = 3, default = "No") some other fields() class Order(model.Models): customer = models.ForeignKey(User) session_key = models.CharField(max_length=40) some other fields() All the items that are added to the cart have a default field of "No", that turn to "Yes" once the payment has been done. If the user is authenticated, it populates the customer field for the cart item, otherwise it creates a session key with the following function: def create_session(request): session = request.session if not session.session_key: session.create() return session To process the payment, the application uses Square (similar to stripe). The following view takes care of it: from square.client import Client def square_payment(request): # this view receives the necessary data such as order total and token via a POST request. # I have omitted these details for the simplicity of the example if request.method == "POST": #create a client object to handle payment through Square client = Client(access_token= "some access token",environment= "production") body = {} body['amount_money']['amount'] = "some amount" # execute payment … -
How to solve Django app name conflict with external library
I made a big mistake by creating an app inside my Django project called requests that happened a long time ago and the system has already been running for years. now I need to use the Django requests library and it is being imported like import requests as mentioned in the documentation ... and of course whenever I do this import it imports my app instead of the library .. so how to solve this? -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__inventory_app_item.accounting_class_id
So i've been working on a Django-project for a while, and i'm about to finish it. I decided to add a feature to it, and i added a new Foreign key to my model. I made the makemigrations my_app, but when i try to migrate it, this error appears: django.db.utils.IntegrityError: NOT NULL constraint failed: new__inventory_app_item.accounting_class_id This is the model: class AccountingClass(models.Model): name = models.CharField(max_length=150, default="", blank=False) def __str__(self): return self.name and this is the Foreign-Key Reference to it: `accounting_class = models.ForeignKey("AccountingClass", on_delete=models.SET_NULL, default="", blank=False, null=True, help_text="The accounting class of the object")` What's the problem with this? -
Django makemigrations adds a new file to migrations folder, however, migrate command doesn't do anything
I just added a new field to a database model in my django app. When I run makemigrations, I see that a new migration file is created, however, running python manage.py migrate doesn't do anything. (twisto-pU_5F16G-py3.10) ➜ twisto git:(burakhan-ze-204-trverification-serrvisine-gizlilik-politikasi-eklenmesi) python manage.py makemigrations customer Migrations for 'customer': apps/customer/migrations/0221_trupgraderequest_privacy_policy_doc_uuid.py - Add field privacy_policy_doc_uuid to trupgraderequest (twisto-pU_5F16G-py3.10) ➜ twisto git:(burakhan-ze-204-trverification-serrvisine-gizlilik-politikasi-eklenmesi) ✗ python manage.py migrate Operations to perform: Apply all migrations: abtest, account, accounting, admin, api, auth, banking, campaign, card, career, cash, change_requests, collectora, contenttypes, customer, dealerpanel, documents, feedback, gdpr, heureka, homepage, kyc, land, partner, postdeploy, product_category, psp, request, risk, saltedge, scoring, sessions, shopping, spi, support, treehorn Running migrations: No migrations to apply. -
Django, How to Login with Username and email
sometimes error with my code, I am trying to use try and expect but can't work. I want to make login with username and email Please helping to solve problems. View.py def login_attempt(request): if request.method == 'POST' : username = request.POST.get('username') email = request.POST.get('username') password = request.POST.get('password') try: user_obj = User.objects.filter(email = email.lower()).first() except: user_obj = User.objects.filter(username = username.lower()).first() try: user = authenticate(username = username.lower(), password = password ) except: user = authenticate(email = email.lower(), password = password login(request, user); return render(request, 'login.html',context) -
Static Model variable that determines which model fields are displayed in ListView
I am trying to make a generic ListView view that can be populated by the model connected to it. Therefore I have inserted several static variables in my model that are used to populate the view. These are to the bottom of the model definition. class AssignmentAd(models.Model): class StatChoices(models.TextChoices): REGISTERED = "Registered" PENDING = "Pending" CANCELED = "Canceled" class FieldChoices(models.TextChoices): JFS = "JFS" JAVA = "Java" CLOUD = "Cloud" # id = models.CharField(max_length=20) # contact_person = models.ForeignKey(Question, on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=StatChoices.choices, default=StatChoices.PENDING) # period = models.DateTimeField('period') # broker deadline = models.DateField('Deadline') field = models.CharField(max_length=20, choices=FieldChoices.choices, default=FieldChoices.JFS) location = models.CharField(max_length=40) remote = models.IntegerField( default=0, validators=[ MaxValueValidator(100), MinValueValidator(0) ] ) # status_reason # url title = models.CharField(max_length=200) REQUIRED_FIELDS = ['status', 'period', 'title'] # These static values are used to populate the ListView template LIST_HEADLINE = 'assignment ads' SINGLE_ITEM = 'assignment ad' LIST_COLTITLES = ['title', 'field', 'status', 'deadline', 'remote', 'location'] LIST_COLDATA = [title, field, status, deadline, remote, location] I am having my list column headlines populated by reading the LIST_COLTITLES field but I am unable to read the column data for each object. Here is my template and how I tried to do it by reading the LIST_COLDATA. In the view I … -
Django -Gunicorn not serving internationalized app -throwing 'Internal Server Error: /ja/ ' and "KeyError: 'translate' "
My Django app uses internationalization to support English and Japanese languages with Japanese being the default language. The language codes are appended to the app's URLs so all of my URLs either look like this http://127.0.0.1:8000/ja/ or like this http://127.0.0.1:8000/en/ If you navigate to http://127.0.0.1:8000 , my urls.py config automatically appends '/ja/' to the the URL and redirects to http://127.0.0.1:8000/ja/ which I suspect may be a problem but I am not sure. I also have {% translate ' ' %} tags all over the place in my templates for internationalization. Everything works perfectly while running Django's built in server. When I execute this command in the terminal: 'gunicorn Main_Project.wsgi' it seems to run and successfully listen to http://127.0.0.1:8000 which is the same ip address that django's runserver command listens to. But when I navigate to http://127.0.0.1:8000, in the terminal where Gunicorn is running I am getting an "Internal Server Error: /ja/" and a 'KeyError: 'translate'' This is the line in the code that Gunicorn is complaining about: <a href="/{{LANGUAGE_CODE}}/account/myaccount/" title="My Account">{% translate "アカウント" %}</a> But this line works perfectly when running python manage.py runserver, so I am 100% sure there are no syntax errors. So the only thing I can … -
django - force first time login user to reset password change
I want to be able to create a new user via admin panel or via my application for the user to use. When the user login for the first time, the user will be redirected to the password reset page to change their password. After successfully changing the password, they will be redirected to the home page. To do this, I have a field in my User model called is_1st_login which takes a 'Y' (default) and 'N' value. So all I need to do is to write like below: def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None and (user.has_perm('authentication.can_access_web') or user.is_superuser): login(request, user) # redirect 1st time user login to reset password if user.is_1st_login == 'Y': return redirect('user_password_change') return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "account/login2.html", {"form": form, "msg" : msg})` And the after resetting the password, I'll update the field to 'N'. While all this is working as expected, how do I restrict the user from trying to bypass it via changing the url to a valid … -
How to update the property of an instance of a model as foreign key of another model
I have am in the following situation. I have a Django model that includes a link to another class, ex: class Document(models.Model): document = models.FileField(upload_to=user_file_path) origin = models.CharField(max_length=9) date = models.DateField() company = models.ForeignKey(Company, on_delete=models.CASCADE) Company includes a property called status. In another part of the code I am working with a doc of type Document and I want to update the status property of the company within the doc, so I proceed to: doc.company.status = new_value save.doc() or setattr(company, 'status', new_value) save.company() In the first case, the value of doc.company.status is updated, but if I query the company it keeps the old value, and in the second case is the other way around, the value of company.status is updated but doc.company.status keeps the old value. I had always assumed that updating either (doc.company or company) of them had an immediate effect over the other, but now it seems that doc has a copy of company (or some sort of lazy link difficult to foresee) and both remain separate, and both of them have to be updated to change the value. An alternative that seems to work is (saving doc.company instead of doc): doc.company.status = new_value doc.company.save() The new value … -
How do I use a Django variable as the width value in a style tag in HTML?
I'm trying to use a Django variable as the percent width value in a style tag in HTML but it won't work. I've noticed that it won't allow me to use curly braces {} at all in style tags, which doesn't make sense because from what I've seen online it should allow it. I want it to be like this: <div class="progress" style="height: 40px;"> <div class="progress-bar" role="progressbar" style="width:{{ value }}%">{{ value }}%</div> </div> for some reason when I do that this I immediately get an error for using curly braces {{}}: The error is: "property value expected css(css-propertyvalueexpected)" I also tried using this method: {% with "width: "|add:value|add:"%" as percent_style %} <div class="progress-bar" role="progressbar" style=style="{{ percent_style }}">{{ value }}%</div> {% endwith %} but it also did not work... Thanks in advance. -
I am integrating amazon s3 bucket with django rest framework
i am working on a project using django rest framework. i want to create folders in s3 bucket dynamically. like if a user uploads some files a folder should be created on his/her name automatically. Thanks in advance. i was thinking if any customisation can be done in models in upload to field or something else. -
Django UpdateView not saving changes to DB
In my application I'm trying to update an Object with the Class Based View UpdateView and save it to the database. This is my code: models.py: class Toy(models.Model): #Relation list = models.ForeignKey(GiftingList, on_delete=models.DO_NOTHING) donor = models.ForeignKey("auth.User", on_delete=models.DO_NOTHING) #Attribute name = models.CharField(max_length=30, blank=False, help_text="Spielzeugnamen eingeben") description = models.TextField(max_length=200, blank=False, default="", help_text="Spielzeug eingeben") image = models.ImageField(upload_to="upload/images/", blank=False, help_text="Bild hochladen") def __str__(self): return self.name urls.py: urlpatterns = [ ... path("toys/<int:pk>/update/", ToyUpdateView.as_view(), name="ToyUpdate"), ... ] views.py: class FormSubmittedInContextMixin(FormMixin): def form_invalid(self, form): return self.render_to_response(self.get_context_data(form=form, form_submitted=True)) class ToyUpdateView(UpdateView, FormSubmittedInContextMixin): model = Toy form_class = ToyForm template_name = "main/updatetoy.html" success_url = reverse_lazy('toys:GiftingListOverview') forms.py: class ToyForm(forms.ModelForm): class Meta: model = Toy widgets = { #'list': forms.ModelChoiceField(queryset=GiftingList.objects.label(), required=True), 'list': forms.TextInput(attrs={'class': 'form-control'}), 'donor': forms.TextInput(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'description': forms.TextInput(attrs={'class': 'form-control'}), 'image': forms.TextInput(attrs={'class': 'form-control'}), } fields = ('list', 'donor', 'name', 'description', 'image') HTML Template: {% extends "main/base.html" %} {% block title %}Spielzeug bearbeiten{% endblock %} {% block content %} <div class="container"> <h3>Spielzeug {{ toy.name }} bearbeiten</h3> <form action="{% url 'toys:ToyUpdate' toy.id %}" method="post" enctype='multipart/form-data'> {% csrf_token %} {% include 'main/toy_form.html' %} <a href="{% url 'toys:ToyDetail' toy.id %}" class="btn btn-primary">Zurück<a> <button type="submit" class="btn btn-success">Speichern</button> </form> </div> {% endblock %} toy_form.html: <section class="django-forms"> <div class="form-group"> <b>Liste:</b> {{ form.list }} <div class="invalid-feedback"> {{ … -
How to enter data without Django textarea?
I have a form that looks like I am trying to add a product. The description of which will be entered through this form. But I don't know how to insert textarea or inpur here html <div class="col-12"> <div class="mb-2"> <label class="form-label">Текст новости</label> <div id="blog-editor-wrapper"> <div id="blog-editor-container"> <div class="editor"> </div> </div> </div> </div> </div> vievs def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.preview=request.POST.get("preview") obj.date=request.POST.get("date") obj.image=request.POST.get("image") obj.save() models text = models.TextField('Текст статьи') -
django custom model admin get current request in get_urls method
I am trying to implement a django solo kind of custom model admin where each user has his own solo object to change. So the instance id should change when user logs in admin panel. Change view is working fine but after changing the field & save, it is not saving the changes. Below is my custom ModelAdmin code - class DatabaseSessionModelAdmin(admin.ModelAdmin): form = DatabaseSessionForm def get_queryset(self, request): return self.model.objects.filter(user=request.user) def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False def get_urls(self): urls = super(DatabaseSessionModelAdmin, self).get_urls() if not settings.DB_ADMIN_SKIP_OBJECT_LIST_PAGE: return urls try: model_name = self.model._meta.model_name except AttributeError: model_name = self.model._meta.module_name.lower() self.model._meta.verbose_name_plural = self.model._meta.verbose_name url_name_prefix = '%(app_name)s_%(model_name)s' % { 'app_name': self.model._meta.app_label, 'model_name': model_name, } custom_urls = [ re_path(r'^$', self.admin_site.admin_view(self.change_view), # {'object_id': str(self.singleton_instance_id)}, name='%s_change' % url_name_prefix), ] return custom_urls + urls def response_change(self, request, obj): msg = _('%(obj)s was changed successfully.') % { 'obj': force_str(obj)} if '_continue' in request.POST: self.message_user(request, msg + ' ' + _('You may edit it again below.')) return HttpResponseRedirect(request.path) else: self.message_user(request, msg) return HttpResponseRedirect("../../") def change_view(self, request, object_id=None, form_url=None, extra_context=None): object_id = DatabaseSession.objects.filter(user=request.user).first().id if not extra_context: extra_context = dict() extra_context['skip_object_list_page'] = True return super(DatabaseSessionModelAdmin, self).change_view( request, str(object_id), form_url=form_url, extra_context=extra_context, ) def history_view(self, request, object_id, extra_context=None): object_id = … -
What is the django way to print debug messages? [duplicate]
Suppose I have this function in views.py in Django. def test_func(request, username): print("print debug msg in test_func()") # other code return Using print() doesn't look like a good way to print out debug messages because the messages will be printed out even in production mode. How do I write debug messages on Django so that the messages will only be printed out in DEBUG mode? I am using Django 4.1 -
calling a class inside another class function
I am trying to create an educational website using django so I have a class class and a course class. I have tried to use the Many-to-one foreignkey relationship but that doesn't work, I can create classes using foreignkey but that class is not being assigned to that course only. It appears in other courses as well. So how can I make this work? What should I change? My models.py: class Class(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='class/class_videos',null=True, validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) def __str__(self): return self.title class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) students = models.ManyToManyField(User, related_name='courses_joined', blank=True) classes = models.ForeignKey(Class, on_delete=models.CASCADE, null=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title -
Use django admin panel without auth application
I've disabled authentication for Django admin panel as described here. I would like to go further and completely skip django.contrib.auth migrations like users or groups tables. I've tried to remove django.contrib.auth from INSTALLED_APP and then I got error like below: RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Is there any way to use Django admin panel without migrating django.contrib.auth migrations? -
How can i get the user from firebase?
why i can not call to my _authenticate_token function, and also i want to get the user from firebase try: decoded_token = auth.verify_id_token(token) _authenticate_token(decoded_token) #foo_instance = Person.objects.create(first_name='test', last_name='test') users = Person.objects.all() response_object = {'data': serialize("json", users)} except: return JsonResponse({"data": "user token id invalid"}) return JsonResponse(response_object) def _authenticate_token( self, decoded_token ) -> auth.UserRecord: print('authenticateToken...') try: uid = decoded_token.get('uid') print(f'_authenticate_token - uid: {uid}') firebase_user = auth.get_user(uid)