Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django url redirecting not working. it appending end of requested url
i try Django 3xx with Django rest redirect to URl but its not working and i also try but not working yet views.py def redirect_shortner(request): return redirect('www.google.com') url.py urlpatterns = [ path('', redirect_shortner, name='redirect_shortner'),] so it seems perfect but.. -
I have just start study django ,i have start a small shop project ,in my product app, to enter the command makemigration i have an error occured [closed]
'how can i solve this ???? File "C:\Users\jaison varghese\AppData\Local \Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 118, in create cls = getattr(mod, cls_name) AttributeError: module 'products.apps' has no attribute 'productsconfig' During handling of the above exception, another exception occurred: 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:\Users\jaison varghese\AppData\Loca \Programs\Python\Python38\lib\site-packages\django\ core\management\__init__.py", line 401, in execute_ from_command_line utility.execute() File "C:\Users\jaison varghese\AppData\ Local\Programs\Python\Python38\lib\site-packages\ django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\jaison varghese\AppData\Local\ Programs\Python\Python38\lib\site-packages\django\ __init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\jaison varghese\AppData\Local \Programs\Python\Python38\lib\site-packages\django\ apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\jaison varghese\AppData\Local\ Programs\Python\Python38\lib\site-packages\django\ apps\config.py", line 132, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'products.apps' does not contain a class 'productsconfig'. Choices are: 'ProductsConfig'. -
Django Test Object created is empty
I am trying to follow instructions from the Django documentation: https://docs.djangoproject.com/en/3.2/topics/testing/overview/ However when I try to create the object for the test. The object is empty?? This is my code: from django.test import TestCase, Client from django.urls import reverse from .models import ShortURL from .views import generate_shortURL, redirect, home from datetime import datetime url = "https://stackoverflow.com/" time = datetime.now() class TestURLShortener(TestCase): def setup(self): self.client = Client() obj= ShortURL.objects.create(original_url=url, short_url='zqSkSQ', time_date_created=time, count=2) obj.save() def test_creating_short_URL_POST(self): """ Test to create short Urls """ short_url_from_db = ShortURL.objects.all() print(f'short_url_from_db : {short_url_from_db}') response = self.client.post(reverse('generate_shortURL'), data={'original_url': url}) generated_short_url = response.context["chars"] self.assertEquals(generated_short_url, 'afasdf') This is the results when I run the test: short_url_from_db prints out this <QuerySet []> instead of the object I wanted it to print out from the setup function. How can I get the object I created to use in this test? -
Django is not displaying image
I am trying to build an e-commerce website using python's Django framework as part of a practice project. However, I am not being able to display my product's image on my landing page. Django version: 3.2.4 models.py: class Listing(models.Model): title = models.CharField(max_length=100) price = models.FloatField() description = models.TextField() image = models.ImageField(upload_to="auctions/images/", default="") settings.py: STATIC_URL = '/static/' # Managing media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py: from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("auctions.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def index(request): listings = Listing.objects.all() return render(request, 'auctions/index.html', { "listings": listings }) index.html {% extends "auctions/layout.html" %} {% load static %} {% block body %} <h2>Active Listings</h2> {% for listing in listings %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{% static listing.image %}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ listing.title }}</h5> <p class="card-text">{{ listing.description }}</p> <p class="card-text">Price - {{ listing.price }}</p> <a href="#" class="btn btn-primary">Bid</a> </div> </div> {% endfor %} {% endblock %} I am only getting the alt attribute for the img tag. -
How to keep some data in django testing?
As you know django give you clear database in testing, but I have a ready() method that create some data for me and I need to query these data in my tests. class YourAppConfig(AppConfig): default_auto_field = 'django.db.models.AutoField' name = 'Functions.MyAppsConfig' def ready(self): from django.contrib.auth.models import Permission from django import apps from django.contrib.contenttypes.models import ContentType try: Permission.objects.get_or_create(....) MyOtherModel.objects.get_or_create(....) except: pass class TestRules(APITestCase): def test_my_model(self): .... x = MyOtherModel.objects.filter(....).first() # x = None # <=========== problem is here ========= I need to see the data that I created in the ready method .... -
django deployment on Heroku KeyError: 'MAILGUN_API_KEY'
I m using cookie cutter but did not select Heroku deployment in selection list when creating app. but now, I want it on Heroku. I've this error: File "/app/.heroku/python/lib/python3.8/os.py", line 675, in __getitem__ remote: raise KeyError(key) from None remote: KeyError: 'MAILGUN_API_KEY' remote: During handling of the above exception, another exception occurred: Traceback (most recent call last): remote: File "manage.py", line 31, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 231, in fetch_command remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 991, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 783, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/tmp/build_3a322b24/config/settings/production.py", line 132, in <module> remote: "MAILGUN_API_KEY": env("MAILGUN_API_KEY"), remote: File "/app/.heroku/python/lib/python3.8/site-packages/environ/environ.py", line 123, in __call__ … -
How can I add a Bootstrap modal that contains a model form into another Django model form?
I have a model form "NewJobEntryForm" which creates a new JobEntry, and in that JobEntry form, users can select ServiceItemStats objects that will be associated by a many-to-many relationship. I would like to enable the user to create new ServiceItemStats objects if they need to, without leaving the JobEntry form. For this, I would like to use a Bootstrap modal that would hold a "NewServiceItemStatsForm", but I am not sure how to go about doing this. Any help would be appreciated. My code is: Models.py class JobEntry(models.Model): # PK: id - automatically assigned by Django. job_entry_date_time = models.DateTimeField(default=timezone.now) job_date = models.DateField(blank=True, null=True) job_checked_in = models.BooleanField() job_checked_out = models.BooleanField(default=False) job_priority = models.IntegerField() job_time_estimation = models.IntegerField(blank=True, null=True) job_comments = models.TextField(max_length=200, blank=True, null=True) job_parts_instock = models.BooleanField(default=False) job_started = models.BooleanField(default=False) job_finished = models.BooleanField(default=False) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) #One-to-one relationship customer = models.ForeignKey(Customer, on_delete=models.CASCADE) #One-to-one relationship serviceBay = models.ForeignKey(ServiceBay, on_delete=models.CASCADE, blank=True, null=True) #One-to-one relationship serviceItemStats = models.ManyToManyField(ServiceItemStats, blank=True) #Many-to-many relationship class ServiceItemStats(models.Model): service_stats_name = models.CharField(primary_key=True, max_length=20) service_stats_estimate_duration = models.IntegerField() # Many-to-many relationship with JobEntry. def __str__(self): return self.service_stats_name Forms.py class NewJobEntryForm(ModelForm): class Meta: model = JobEntry fields = ['vehicle', 'customer', 'job_date', 'job_checked_in', 'job_priority', 'job_comments', 'job_parts_instock', 'serviceItemStats'] widgets = { 'job_date' : forms.DateInput(format=('%m/%d/%Y'), attrs={'class':'form-control', 'placeholder':'Select a … -
Passing an Object into Include Template Tag Django
I am developing a website in django and I have encountered a problem. I am using an 'include' template tag and I am trying to pass an object into the tag. But whenever I pass it in, it is passing in the dunder str method of the object. {% include 'function/comment' object=answer %} 'answer' is the object I want to pass in (fyi it is a model object) Instead of passing 'answer' as an object it is passing the dunder str method. Is there a way to solve this? Thanks in advance. -
Change sensitive info to ******* in Django admin change view
I have a following question. For example I have a admin class in Django: @admin.register(models.MyModel) class MyAdmin(admin.ModelAdmin): list_display = (‘field1’, ‘field2’, ‘field3’) fields = (‘field1’, ‘field2’, ‘field3’, ‘key’) … As you can see change view of admin has ‘key’ fields which contains sensitive information that I don’t want to show to anyone in change view . Question is – is it possible to change ‘key’ displayed data to ‘*******’ in admin change view page in case ‘key’ has some data and to ‘-’ if it does not? How to do it in List view - i know Thank you. -
How to make sure that both column values exists only once in database table?
I have a table which stores the hash tags as a many to many relation ship Tags Table userID - Foreign key tags - foreign key I have used Unique constraint which I think is a foolish one. Here I want to ensure that a user uses the tag a user uses each tag only once in that table. What query will suit this scenario? So the desired output is like a user uses only one tag The database I use is PostgreSQL. Since I use Django where I have the code below user = models.ForeignKey("User",unique=True) userTags = models.ForeignKey("Tags",unique=True) which has a meaning of that user column is foreign key reference from User table and it's a unique column UserTags column is a foreign key reference from Tags table and that column is unique -
Save extra fields in user registration by dj_rest_auth
I've been on dj_rest_auth on this project. Trying to add extra fields to the custom user model but it only saves the email and password. I think I have everything right but nothings working. Heres my user model class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField('email address', unique=True) USERNAME_FIELD = 'email' first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) phone = models.CharField(max_length=30, blank=True) REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email serializers.py class UserSerializer(serializers.ModelSerializer): phone = serializers.CharField(max_length=30, allow_blank=True) first_name = serializers.CharField(max_length=30, allow_blank=True) last_name = serializers.CharField(max_length=30, allow_blank=True) class Meta: model = CustomUser fields = … -
POSTMAN Curd ClassbasedView
Django Postman Curd Serializer Getting Null Value while creating a student in POSTMAN models.py from django.db import models class Student(models.Model): GENDERS = ( ('f','Female'), ('m','Male') ) name = models.CharField(max_length=100) roll = models.IntegerField(unique = True) email = models.EmailField(max_length=100) gender = models.CharField(max_length=1, choices = GENDERS) percentage = models.FloatField() institute = models.ForeignKey('Institute',on_delete = models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Institute(models.Model): TYPES = ( ('h', 'HighSchool'), ('c','College') ) name = models.CharField(max_length=200) type_of_institute = models.CharField(max_length=1, choices= TYPES) def __str__(self): return self.name My doubt is after creating a student in the postman after giving the value for institute i am getting null. why i am getting a null though i am giving the value for it Please click on the image for more details about error [checkmark]:https://i.stack.imgur.com/DLZ4H.jpg -
ModuleNotFoundError: No module named (projectname.appname)
models.py from django.db import models class Dhiraj(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=100) password=models.CharField(max_length=100) forms.py from django.forms import fields from .models import Dhiraj class StudentRegistation(forms.ModelForm): class Meta: models=Dhiraj fields=['name','email','password'] admin.py from django.contrib import admin from .models import Dhiraj @admin.register(Dhiraj) class DhirajAdmin(admin.ModelAdmin): list_display=('id','name','email','password') views.py from crudproject1.enroll.forms import StudentRegistation from django.shortcuts import render from .forms import StudentRegistation def add_show(request): if request.method=='POST': fm=StudentRegistation(request.post) else: fm=StudentRegistation(request.post) context={ 'fm':fm } return render(request,'enroll/addandshow.html') urls.py from django.contrib import admin from django.urls import path from enroll import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.add_show, name="addandshow") ] error message Exception in thread django-main-thread: File "C:\Users\Dhiraj Subedi\Desktop\dhiraj\crudproject1\crudproject1\urls.py", line 18, in from enroll import views File "C:\Users\Dhiraj Subedi\Desktop\dhiraj\crudproject1\enroll\views.py", line 1, in from crudproject1.enroll.forms import StudentRegistation ModuleNotFoundError: No module named 'crudproject1.enroll' I am creating a Django application and I am facing this issue can you please help ` -
Getting 403 Forbidden when trying to upload file to AWS S3 with presigned post using Boto3 (Django + Javascript)
I've tried researching other threads here on SO and other forums, but still can't overcome this issue. I'm generating a presigned post to S3 and trying to upload a file to it using these headers, but getting a 403: Forbidden. Permissions The IAM user loaded in with Boto3 has permissions to list, read and write to S3. CORS CORS from all origins and all headers are allowed The code The code is based on Python in Django as well as Javascript. This is the logic: First the file is retrieved from the HTML, and used to call a function for retrieving the signed URL. (function () { document.getElementById("file-input").onchange = function () { let files = document.getElementById("file-input").files; let file = files[0]; Object.defineProperty(file, "name", { writeable: true, value: `${uuidv4()}.pdf` }) if (!file) { return alert("No file selected"); } getSignedRequest(file); } })(); Then a GET request is sent to retrieve the signed URL, using a Django view (described in the next section after this one) function getSignedRequest(file) { var xhr = new XMLHttpRequest(); xhr.open("GET", "/sign_s3?file_name=" + file.name + "&file_type=" + file.type) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { let response = JSON.parse(xhr.responseText) uploadFile(file, response.data, response.url) … -
Stripe Error on request.META["HTTP_STRIPE_SIGNATURE"]
I'm using Django and implemented my payments with Stripe the server shows Traceback (most recent call last): File "/home/ali/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ali/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ali/.local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ali/digitalstore/payment/views.py", line 120, in stripe_webhook sig_header = request.META["HTTP_STRIPE_SIGNATURE"] KeyError: 'HTTP_STRIPE_SIGNATURE' which using request.META.get("HTTP_STRIPE_SIGNATURE") cause the Unable to extract timestamp and signatures from header error on server it's my stripe_webhook @csrf_exempt def stripe_webhook(request): payload = request.body # payload = request.body.decode("utf-8") sig_header = request.META["HTTP_STRIPE_SIGNATURE"] event = None try: event = stripe.Webhook.construct_event(payload, sig_header, settings.STRIPE_WEBHOOK_SECRET) except ValueError as e: # Invalid payload print("#ERR: stripe invalid payload : ", e) return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature print("#ERR: stripe invalid Signature : ", e) return HttpResponse(status=400) if event["type"] == "checkout.session.completed": session = event["data"]["object"] # send the email to the user get the email from session and product id print(">> session :: ", session) I'm wondering what if i remove the check for except stripe.error.SignatureVerificationError as e: # Invalid signature print("#ERR: stripe invalid Signature : ", e) return HttpResponse(status=400) and just allow it.(i have no idea would that cause security risks??) -
How to override the generate_filename function of a file name field in the parent class?
I have an abstract class BaseFile and a descendant SeamlessFile. In SeamlessFile, I override the generate_filename method of the BaseFile. Everything works flawlessly. Now if I want a descendant of SeamlessFile, and I want to override only the generate_filename method, this doesn't work, because my wild guess is that generate_filename associated with the actual_file is the one of SeamlessFile. It's ok I understand the problem, but I dont know how to solve it: how to override the generate_filename function of the parent (it's not only override, it's "make the actual_file model use the new function")? class BaseFile(UidMixin, BaseModel): __metaclass__ = ABCMeta upload_directory = "" def generate_filename(self, filename): return "uploads/" class SeamlessFile(BaseFile): def generate_filename(self, filename): return os.path.join("seam/", basename(filename)) actual_file = models.FileField( default=None, null=True, blank=True, upload_to=generate_filename, ) class FrontEndAuditFile(SeamlessFile): def generate_filename(self, filename): print("FrontEndAuditFile -> generate_filename") return os.path.join("fro/", basename(filename)) -
Python dict comprehension on a Django Queryset
In my project i have a Django ORM query for manage some data: var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val" ) well, my query return an Queryset object containing data i need. My problem is that the var_val is a string representation of a dict and i, instead of that value (for example '[54321, 98]') i would convert it using my conversion function def decode_value(original value): ... return <converted value> i would call directly my decode_value function in my queryset creation like this: var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", decode_value(var_val) ) but i get an error: var_val is not defined so i thinked about create using a python dict comprehension a dedicated dict stating from my queryset with all queryset field and var_val field converted but i don't know how achieve this. Can somaone help me about dinamicaly value editing in django ORM queryset object creation or in a dict comprehension from a Queryset object? So many thanks in advance -
Set different size for each columns in Reportlab
I am using Reportlab in python. Now I am trying to customize each column width. Because some of the columns need small width rather than other columns. Is there any way to make each column customizable? Currently from the picture, I would like to increase the width of the Partname column width and set small width for tax, Style p, etc. views.py columns = [ {'title': 'Part No', 'field': 'partno'}, {'title': 'Part Name', 'field': 'partname'}, {'title': 'Style P', 'field': 'style'}, {'title': 'Standard P', 'field': 'standardpack'}, {'title': 'Unit Per Car', 'field': 'unit'}, {'title': 'Quantity PCS', 'field': 'quantity'}, {'title': 'Tax', 'field': 'tax'}, {'title': 'Unit Price', 'field': 'price'}, {'title': 'Amount', 'field': 'amount'}, ] table_data = [[col['title'] for col in columns]] table_row = [str(tr.part.partno),tr.part.partname, tr.part.stylepack, tr.part.standardpack,tr.part.unit, tr.quantity, tr.part.tax, tr.part.price, tr.amount] table_data.append(table_row) table = Table(table_data, repeatRows=1, colWidths=[150,150]) table.setStyle(TableStyle([ ('BOX', (0, 0), (-1, -1), 0.20, colors.dimgrey), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, -1), 10), ])) elements.append(table) -
how to set value to Foreign key filed before Perform create in django rest framework
I have two serializers like this : class MeetingLocationSerializer(serializers.ModelSerializer): class Meta: model = MeetingLocation fields = '__all__' class MeetingtSerializer(serializers.ModelSerializer): location = MeetingLocationSerializer() photos = MeetingPhotoSerializer(many = True) class Meta: model = Meeting fields = ['id','title','description','date_time','time_zone','host','is_private','is_virtual','url','photos','location'] and this is my modelviewsets : class MeetingListViewSet(viewsets.ModelViewSet): queryset = Meeting.objects.all() serializer_class = MeetingtSerializer class MeetingPhotoViewSet(viewsets.ModelViewSet): queryset = MeetingPhoto.objects.all() serializer_class = MeetingPhotoSerializer def retrieve(self, request, *args, **kwargs): param = kwargs photos = MeetingPhoto.objects.filter(meeting=param['pk']) serializer = MeetingPhotoSerializer(photos, many =True) return Response(serializer.data) when i want to post data to MeetingListViewSet and save it , the meeting filed in nested location serializer needs value which is the meeting that i am trying to create and it is not created yet! what should i do? -
How to find objects with the most similar fields?
This is the model I have defined: class Book(models.Model): authors = models.ManyToManyField(to='Author') category = models.ForeignKey(to='Category') tags = models.ManyToManyField(to='tags') # some other fields How can I find ten books that are most similar in these three fields (authors, category, tags) to a specific object? -
Django Signals to trigger VersatileImageFieldWarmer on migrations
I have some post_save signals to "create new images immediately after model instances are saved" just as stated on django-versatileimagefield docs. Example: @receiver(models.signals.post_save, sender=VendorImage) def warm_vendor_images(sender, instance, **kwargs): warmer = VersatileImageFieldWarmer( instance_or_queryset=instance, rendition_key_set=settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS['default'], image_attr='image', verbose=True ) warmer.warm() This works fine when I upload images and even when creating my fixtures. However, I have two models that are populated in the migrations using RunPython. Example: eventCategories = { "Poolparty": 'Poolparty.png', ... } ... def AddEventCategories(apps, schema_editor): model = apps.get_model('sp_event', 'EventCategory') for key in eventCategories: imagePath = upload_to + eventCategories[key] model.objects.create(name=key, image=imagePath) ... migrations.RunPython(AddEventCategories) I was wondering if the create() method calls save() to trigger the signal, but to be sure 100% sure, I called save() after creating the instances: the signal wasn't triggered as well. Using the VersatileImageFieldWarmer in the migration also results in an error regarding the image path... How can I ensure my sized images are created upon the instances creation during the migration process? -
How to view a model from new app in django admin?
Working with telegram bot with admin on django. There are was 7 apps in project. I create new app,register models in admin.py in app, write app in settings.py, make migrations and migrat, restart supervisor,under that all working, but nothing. Admin path was created with django-admin-tools. I was return all to standart django admin, but models in admin not view. Dont know what can make more. setting.py(without selery): INSTALLED_APPS = [ 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'mptt', "django_cron", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'django.contrib.humanize', 'cache_model', 'preferences', 'public_model', 'sort_model', 'users', 'server_resources', 'application.telegram', 'application.request', 'application.trucks', 'application.sales', 'application.parsings', 'application.docs', 'application.rating', 'application.check', 'application.subscription', 'application.emirates' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'application.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.request', 'django.template.context_processors.static', 'django.contrib.messages.context_processors.messages', 'django.contrib.auth.context_processors.auth', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'admin_tools.template_loaders.Loader', ], 'debug': DEBUG, }, }, ] WSGI_APPLICATION = 'application.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'telegram_avtorazborov_bot', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '', } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'ru-ru' TIME_ZONE = 'Europe/Moscow' USE_I18N = True … -
Why does from . import views work and import views does not?
This question came to my mind while exploring Django. Suppose this structure: . ├── db.sqlite3 ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── myapp ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py ├── urls.py └── views.py In polls/urls.py, this statement import views fine: from . import views while just import views raises ModuleNotFoundError. What I understand is that import foo searches for foo in a list of directories defined by sys.path which includes the current package, and also from the documentation: Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. So, both import foo and from . foo should work quite the same. If that is true, why it isn't the case for the django imports? If it's not true, what do I misunderstand? -
how to filter between two existing date django
i'm trying to filter and check if two dates are already exists , for example we have this existing two dates 28-6-2021 11:30 PM and 30-6-2021 11:30 PM , i have to prevent the users to select any dates which contains between that two existing dates for example if the user try to select 29-6-2021 12:00 PM to 1-7-2021 12:00 PM it should raise an error the dates already taken ! this is my models.py class Booking(models.Model): room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') check_in = models.DateTimeField(default=datetime.now) check_out = models.DateTimeField() #my form class BookingForm(forms.ModelForm): check_in = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) check_out = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) class Meta: model = Booking fields = ['check_in','check_out'] and this is my views.py , i've tried this to achieve it @login_required def add_booking(request,room_no): room_number = get_object_or_404(Room,room_no=room_no) if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): obj = form.save(commit=False) if room_number.rooms.filter(check_in__gte=check_in,check_out__gte=check_out).exists(): #if room_number.rooms.filter(Q(check_in__gte=check_in, )|Q(check_out__lte=check_out)).exists(): #but still doesnt work return HttpResponse('taken! sorry , try another room please') obj.room_no = room_number obj.save() messages.success(request,f'room number {room_number} added') form = BookingForm() return render(request,'booking/add_booking.html',{'form':form,'room_number':room_number}) but doesn't work , the project is for a hotel , and booking app , i have to prevent users from selecting wrong dates ! please is it possible ? thank you so much .. -
How can we create an endpoint in django for google api client
I am trying to implement login with google in Native kotlin.And using django as a backend. For google api clint I have added python code in my django project. verify_oauth2_token.py from google.oauth2 import id_token from google.auth.transport import request from delopus.settings import CLIENT_ID # (Receive token by HTTPS POST) # ... try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]: # raise ValueError('Could not verify audience.') # If auth request is from a G Suite domain: # if idinfo['hd'] != GSUITE_DOMAIN_NAME: # raise ValueError('Wrong hosted domain.') # ID token is valid. Get the user's Google Account ID from the decoded token. userid = idinfo['sub'] except ValueError: # Invalid token pass I am trying to create an endpoint like below urls.py path('user/google/oauth', exampleView.as_view(), name='google_oauth'), In this exampleView I don't have class view. I need class view so that I can create an endpoint. But I am not sure how to create class view in django for endpoint url so that I can validate an ID token using the tokeninfo endpoint. like given …