Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom login form will not validate against is_valid()
Summary: My custom login form is failing to validate against .is_valid(). I have been able to confirm the email & password values are being passed through to views.py as print(request.POST.get('') returns both the email (required for login) and the password. I think my issue is different from other similar questions because they all seem to address missing required fields. I tried excluding every field I could think of from .is_valid but the form won't validate. I click the button and nothing happens. I am using Django 3.7. accounts/forms.py class LoginForm(forms.Form): email = forms.EmailField(label='email', max_length='255') password = forms.CharField(label='password') def __init__(self, request, *args, **kwargs): self.request = request super(LoginForm, self).__init__(*args, **kwargs) def form_valid(self, form): form.save() return super(LoginForm, self).form_valid(form) accounts/views.py I can't access anything inside the "form.is_valid" if statement. I pop out on the else: side. def login_page(request): if request.method == 'POST': #create form instance / populate form = LoginForm(request.POST) context = { "email": "email", "password": "password", "first_name": "first_name", "last_name": "last_name", "is_active": "is_active", "form": form } if form.is_valid(): username = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) form.save() if user is not None: if user.is_active: login(request, user) print(request.is_authenticated()) context['form'] = LoginForm() return redirect('/') else: pass else: pass else: '''This is where I … -
Adding django-modeltranslation to existing project ruins tests
I have existing project and I decided to add translations options. I installed django-modeltranslation, added languages to settings, models to translation.py and added models in admin.py. from modeltranslation.translator import translator, TranslationOptions from .models import GameTask class GameTaskTranslationOptions(TranslationOptions): fields =('name', 'description', 'button_text') translator.register(GameTask, GameTaskTranslationOptions) @admin.register(GameTask) class GameTaskAdmin(TranslationAdmin): model = GameTask But as I mentioned I added it to existing project. So I have to move my existing data to created fields. So after makemigrations but before migrate I added to my migration file: def populate_function(apps, schema_editor): management.call_command("update_translation_fields") class Migration(migrations.Migration): dependencies = [ ('pages', '0054_auto_20210105_1041'), ] operations = [ ........., migrations.RunPython(populate_function, migrations.RunPython.noop), ] After that I run python manage.py migrate pages migrate_file. And it works. I have my database updated and my data aren't lost, they are moved to default language field set in settings. But after running my test I get: django.db.utils.ProgrammingError: column pages_gametask.button_text_pl does not exist. LINE 1: ..._text_pl" = "pages_gametask"."button_text" WHERE ("pages_gam... ^ HINT: Perhaps you meant to reference the column "pages_gametask.button_text". So to sum up, I have what I wanted - I have fields for my languages in my database, data aren't lost, but look like during test, the default database can't create due to language's fields. Can … -
AH01630: client denied by server configuration error
I am running Django in production and I have problem when visitors fills out a form in my website and an email is sent in to me in the backend. There is no problem when running in development mode, and the problem only arises in production. I am using apache2 together with mod_wsgi. Below is a snippet of my error_log [Sat Mar 20 18:36:52.693566 2021] [authz_core:error] [pid 63623:tid 140495391864576] [client 66.249.69.150:50390] AH01630: client denied by server configuration: /etc/wsgi-port-80/htdocs/cgi-bin [Sat Mar 20 18:46:20.822928 2021] [authz_core:error] [pid 63623:tid 140495391598336] [client 66.249.75.187:51831] AH01630: client denied by server configuration: /etc/wsgi-port-80/htdocs/cgi-bin [Sat Mar 20 18:49:18.121736 2021] [authz_core:error] [pid 63600:tid 140495390799616] [client 66.249.77.27:61325] AH01630: client denied by server configuration: /etc/wsgi-port-80/htdocs/cgi-bin [Sat Mar 20 18:49:25.616719 2021] [wsgi:error] [pid 63599:tid 140495337584384] [remote 52.175.223.195:7872] Not Found: /wp-includes/js/wp-emoji-release.min.js [Sat Mar 20 18:50:25.165286 2021] [wsgi:error] [pid 63599:tid 140494956918528] Exception in thread Thread-7: [Sat Mar 20 18:50:25.165357 2021] [wsgi:error] [pid 63599:tid 140494956918528] Traceback (most recent call last): [Sat Mar 20 18:50:25.165373 2021] [wsgi:error] [pid 63599:tid 140494956918528] File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner [Sat Mar 20 18:50:25.165832 2021] [wsgi:error] [pid 63599:tid 140494956918528] self.run() [Sat Mar 20 18:50:25.165847 2021] [wsgi:error] [pid 63599:tid 140494956918528] File "/usr/lib/python3.8/threading.py", line 870, in run [Sat Mar 20 18:50:25.166139 2021] … -
GET request in python with "requests" lib to a CloudFlare protected site returns Error 1020 "Please enable cookies"
I'm making a request like this: import requests s = requests.Session() r = s.get('http://<endpoint-url>') print(r.text) It returns an HTML page, and I can see these lines: Please enable cookies.</div> ... <span data-translate="error">Error</span> <span>1020</span> When I print s.cookies.get_dict() I'm getting this: {'__cfduid': 'd06702291bb6520f2 ...'} It works when I open the URL in the browser and I can see it sets this cookie. The problem is when I try to make the request from python. I looked in the response library docs, doesn't mention how to "enable cookies". Couldn't find anything useful on error 1020, or in the target website's API docs. What should I do? -
Authenticating Custom User Model for Login Django
I created my custom user model in my Django project. My user registering works properly. However, my login is not. This is my custom user model: from django.db import models import datetime from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils import timezone from django.utils.translation import gettext_lazy as _ class NewUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=150, primary_key = True) firstName = models.CharField(max_length=150) lastName = models.CharField(max_length=150) nombreArtistico = models.CharField(max_length=150, default=None, null=True, unique=True) #Validacion create_superuser last_login = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) #Info de la suscripcion_form activa = models.BooleanField(default=False) fecha_creacion = models.DateField(default=None, null=True) fecha_actualizacion = models.DateField(default=datetime.date.today) disponibilidad_de_reproducciones = models.IntegerField(default=3) # objects = CustomAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['firstName', 'lastName'] def __str__(self): return self.username This is my Authentication Login Form: from django.forms import ModelForm from django import forms from usuarios.models import NewUser from django.contrib.auth.forms import UserCreationForm from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() class Register(forms.Form): username = forms.CharField(label="username", max_length=150) firstName = forms.CharField(label="First Name", max_length=150) lastName = forms.CharField(label="Last Name", max_length=150) password = forms.CharField(label="Password", max_length=150, widget=forms.PasswordInput) class AuthenticationForm(forms.Form): username = forms.CharField(label="username", max_length=150) password = forms.CharField(label="Password", max_length=150, widget=forms.PasswordInput) This is what I am trying in my login view. def login_view(response): if response.method == "POST": print(response.POST['username']) form = … -
Why are my django modelformsets being prepopulated after user uploads data?
So, I have a django modelformset for allowing the user to upload multiple listings on a fake ecommerce site. When the user first accesses the "upload page" the forms are clear and there's no problem. After the user uploads some items, though, it seems like django is prepopulating the forms with the information the user submitted earlier. I don't want this, and I have no clue how to prevent it. Here is the forms.py: class ProductModelForm(forms.ModelForm): class Meta: model = Product fields = [ "product_name", "product_description", "product_price", ] class ProductImageModelForm(forms.ModelForm): class Meta: model = ProductImage fields = [ "product_image", ] ProductModelFormSet = modelformset_factory( Product, fields=( "product_name", "product_description", "product_price", ), extra=3, ) ProductImageModelFormSet = modelformset_factory( ProductImage, fields=( "product_image", ), extra=3, ) and here's the view that handles it: @login_required def product_upload_view(request): if request.method == "POST": product_form_set = ProductModelFormSet(request.POST) product_image_form_set = ProductImageModelFormSet(request.POST, request.FILES) if (product_form_set.is_valid() and product_image_form_set.is_valid()): for obj, obj_image in zip(product_form_set.save(commit=False), product_image_form_set.save(commit=False)): obj.product_seller = request.user obj.product_pub_date = timezone.now() obj.product_image = obj_image obj_image.save() obj.save() return HttpResponseRedirect("somewhere/else/") product_form_set = ProductModelFormSet() product_image_form_set = ProductImageModelFormSet() return render(request, "products/upload.html", { "product_form_set": product_form_set, "product_image_form_set": product_image_form_set, }) Now, I don't know if I'm even explaining my problem right because I can't seem to find an answer online but … -
Why is Django rendering one of my app's templates as plain text
I am working on a blog development in Django and there are different categories of posts or articles on category_list.html which have been created using ORM library and to each category i have added some articles using ORM library with the help of category slug which are rendered on category_view.html and problem is that list of categories are shown perfectly on category_list.html after adding from admin panel of django and when I click on any category name(contains get_absolute_url link), it takes me perfectly to category_view.html page but on category_view.html, data is shown in the form of text means renders the complete content of category_view.html in the form of plain text. All other templates are getting rendered by django perfectly but what is the reason that category_view.html is getting rendered as plain text? Please help me def category_list(request,category_slug=None): category=None categories=CategoryList.objects.all() # article=Article.objects.all() return render(request,'category_list.html',{'categories':categories}) def category_view(request,category_slug): category=get_object_or_404(CategoryList,slug=category_slug) article=Article.objects.filter(category=category) return render(request,'category_view.html',{'category':category},{'article':article}) My url.py contains the following urls: path("",views.index), path('category',views.category_list, name='category_list'), path('<slug:category_slug>',views.category_view, name='story_by_category'), This is link in category_list.html which takes me to category_view.html <div class="row py-3"> {%for c in categories%} <div class="col-lg col-12 homeimg" id="img1"> <h5><a href="{{c.get_absolute_url}}">{{c.name}}</a></h5> <img class="secimg border-info" src="{{c.image_url|default_if_none:'#'}}" alt="gameplay videos"> </div> {%endfor%} </div> -
Django 3.0: django-notifications-hq, admin have a notification when Product has created by seller
Hi there i'm new in django-notification ,and i'm looking for a method to notify admin when a product or Order has created (i develop an E-commerce whith django and bootstrap4) help please -
Django using Celery not performing my task
I have been trying for the past 3 days to get django to perfom asynchronous tasks on a periodic schedule. Came across Celery which seemed like a perfect match for my problem but the more I read online the more problems there seemed to exist that I had prepared. Anyway I was able to vaguely glue up together pieces of information to finally come up with a "somewhat solution" because there were so many deprecated modules and methods it was hard to find a working example from start to finish. So I am trying to create a task which will create a certain model object periodically (let's say 30 seconds for sake of the argument). So I installed redis as the "broker", (so I saw fit in other discussions) and managed to set up my task up and running but the problem is that even when it executes, no new model is created, I suspect that it might be cause of maybe a misconfiguration between the local and the settings time-zone but frankly I'm not sure, supposedly it should be able to create new instance when run through django-celery-beat tables in the admin panel my init.py: from __future__ import absolute_import, … -
Failure to authenticate User with AuthenticationForm
I'm attempting to create a TemplateView where each subclass renders an AuthenticationForm; subclassing it and naming it UserLoginForm. This gives the User the opportunity to login with their credentials on any page they visit and be redirected to that same page after being successfully authenticated. When validating UserLoginForm, it fails to authenticate when it reaches form.clean() and raises self.get_invalid_login_error(). The TestCase used to simulate this scenario creates a User, then a POST request with the same credentials is sent. What's causing the UserLoginForm to invalidate the data passed to it and not finding the User? https://github.com/django/django/blob/main/django/contrib/auth/forms.py#L197 class TestTopicListMainPage__003(TestCase): '''Verify that an anonymous user is logged into their User account''' @classmethod def setUpTestData(cls): user = User.objects.create_user("User", 'secretcode') cls.data = { 'username': "User", 'password': "secretcode" } def test_topics_listing_login_user(self): response = self.client.post( reverse("topics:listing"), data=self.data ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "topics/listing.html") self.assertContains(response, "Logout") class AbstractListingView(TemplateView): template_name = "topics/listing.html" def get_context_data(self): context = super().get_context_data() context['topics'] = Topic.objects.all() context['search_form'] = SearchForm() context['login_form'] = UserLoginForm return context def post(self, request): context = self.get_context_data() form = context['login_form'](request, data=request.POST) if form.is_valid(): resolver = resolve(request.path) login(request, form.user_cache) return HttpResponseRedirect(reverse(resolver.url_name)) return self.render_to_response(context) class TopicsMainPage(AbstractListingView): extra_content = { 'heading': 'Questions', 'query_links': ['interesting', 'hot', 'week', 'month'] } def get(self, request): query = request.GET.get('tab', None) … -
Django doesn't create test database when running test
I read in Django document that a blank database will be created for testing. I am new to Django so I barely changed anything in setting.py and currently using Sqlite database. However, when I run python manage.py test, Django keep telling the user has been existed, so I tried changing the username for the created users in TestCase, run the test again and found out that the new users are created in the existing database. The test file is as bellow: class UserTestCase(unittest.TestCase): def setUp(self): admin = User.objects.create(username="admin", password="1") user1 = User.objects.create(username="user1", password="1") user2 = User.objects.create(username="user2", password="1") admin.following.add(user1) admin.followers.add(user2) def test_users_count(self): self.assertEqual(User.objects.count()==3) My model is as bellow: class User(AbstractUser): followers = models.ManyToManyField('self', related_name="following", symmetrical=False, through='Follow', through_fields=('followee', 'follower')) def __str__(self): return f"{self.username}" def serialize(self): return { "id": self.id, "username": self.username, } class Follow(models.Model): followee = models.ForeignKey( 'User', on_delete=models.CASCADE, related_name='+' ) follower = models.ForeignKey( 'User', on_delete=models.CASCADE, related_name='+' ) def clean(self, *args, **kwargs): if self.follower__id == self.followee__id: raise ValidationError('Can not follow self.') return super().clean(*args, **kwargs) class Meta: constraints = [ models.UniqueConstraint(fields=['follower', 'followee'], name='follow_once'), models.CheckConstraint(check=~Q(follower=F('followee')), name='not_follow_self') ] -
Python dynamic update instance method
admin is instance. I want to do something to instance like decorator. class CodeInClass(admin.AdminSite): def get_app_list(self, request): all_list = super().get_app_list(request) # reorder the app list as you like return all_list def get_app_list(request): all_list = super().get_app_list_old(request) # dosomething() return all_list admin.site.get_app_list_old = admin.site.get_app_list admin.site.get_app_list = get_app_list Get error: RuntimeError at /admin/ super(): __class__ cell not found -
AttributeError on django migrations (production)
In production I divided settings to 2 parts prod_settings.py and local_settings.py. For server Gunicorn with Nginx. So after makemigrations command it returns AttributeError: 'str' object has no attribute 'setdefault' The Traceback is -> Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/artashes/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/artashes/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/artashes/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/artashes/venv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/artashes/venv/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/artashes/venv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/artashes/venv/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/artashes/venv/lib/python3.8/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/artashes/venv/lib/python3.8/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/home/artashes/venv/lib/python3.8/site-packages/django/db/models/options.py", line 206, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/artashes/venv/lib/python3.8/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home/artashes/venv/lib/python3.8/site-packages/django/db/utils.py", line 211, … -
How do I check if another user is being followed by another user?
So I have a UserProfile Model with a relationships field which defines relationships between two users class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None , null= True) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') and a Relationship table class Relationship(models.Model): from_person = models.ForeignKey(UserProfile,on_delete=models.CASCADE,related_name='from_people') to_person = models.ForeignKey(UserProfile,on_delete=models.CASCADE,related_name='to_people') status = models.IntegerField(choices=RELATIONSHIP_STATUSES) Case example: Let's say I have a UserProfile(1) object and I need to access it's relationship field to determine if another UserProfile(2) has a relationship with UserProfile(1), how do I write such a query? I have seen code like: rel = UserProfile1.relationships.filter( to_people__from_person=UserProfile1) return rel.filter(pk = UserProfile2.id).exists() But I do not understand the code below. Does this return a Relationship object or UserProfile object? I am guessing to_people is for the reverse access to Relationship from UserProfile object but I don't understand how it's been done. Docs tell me the filtering is done based on field__lookuptype=value but I don't get it wrt the code below. Can someone shed more light on this? UserProfile1.relationships.filter( to_people__from_person=UserProfile1) -
How to add comment form in ListView Django?
Into: I have a queryset of multiple posts in listviewpage. i want to add comment form with each of post in listviewpage instead of detailpageview. Problem: The code below is getting error 'ValidationError' object has no attribute 'get' I would be grateful for any help. models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) comments = models.TextField(max_length=1000, blank=True) created_at = models.DateTimeField(auto_now_add=True) views.py def ListViewPage(request): queryset = Post.objects.all() comment = CommentForm(data=request.POST) if request.method == 'POST': try: pk = request.POST.get('pk') post = Post.objects.get(id=pk) except Post.DoesNotExist: return ValidationError(f'No Post by id {pk}') if comment.is_valid(): com = comment.save(commit=False) com.posts = post com.save() context = { 'posts': queryset, 'form': comment } return render(request, 'post_list.html', context) -
How to generate model and table dynamically in Django
I am new to DJango. I have an requirement to create a table at runtime, I mean whenever a new user signup on my application, a new table should be created with that user's name, so table should be created with out migration command, My DB is mysql, attrs = { 'name': models.CharField(max_length=32), '__module__': 'myapp.models' } dynamic_username="riswan" user_model = type(dynamic_username, (models.Model,), attrs) how to implement this ? Please help -
save form data with one to one relationship in django
I have one to one relationship with the Django User model and custom Profile model. I trying to save user and profile data at the same time when the user is registered. But the problem is the data of the profile model is not validating and data is not saving in the database here is code model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) picture = models.ImageField(upload_to = 'profile_pictures') Join_as = models.CharField(choices=USER_CHOICES, max_length=70) date = models.DateField(auto_now_add=True) form.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['picture','Join_as'] labels = { 'picture':'Upload Profile Picture' } widgets = { 'Join_as':forms.Select(attrs={'class':'form-select'}), } view.py def rigister(request): if request.method == 'POST': user_form = UserCreationForm(request.POST) profile_form = ProfileForm(request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return HttpResponseRedirect('/') else: user_form = UserCreationForm() profile_form = ProfileForm() contaxt = {'user_form':user_form,'profile_form':profile_form} return render(request, 'registration/register.html', contaxt) -
TypeError: cannot unpack non-iterable int object in Django rest framework
I am trying to get a list of orders of only those products associated with that merchant. In my project, every product is associated with a merchant. In the merchant dashboard, merchants should be able to view only their products and orders. When I try to filter the orders based on products associated with that merchant, I got the above error. My models: class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) #items = models.ManyToManyField(OrderItem,blank=True, null=True,related_name="order_items") #start_date = models.DateTimeField(auto_now_add=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.CharField(max_length=50,blank=True,null=True) def __str__(self): return f"{self.quantity} items of {self.item} of {self.order.user}" class Meta: verbose_name_plural= "Cart Items" ordering = ('-id',) My views: class SellerOrderAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = OrderItemSerializer def get_queryset(self): merchant = get_object_or_404(Seller,self.kwargs['pk']) return OrderItem.objects.all(item__merchant=merchant) My serializers: class OrderItemSerializer(serializers.ModelSerializer): order_variants = VariantSerializer(read_only=True) #order_variants =VariantSerializer() item = ProductSerializer(read_only=True) … -
Why is django not creating a database table with 'migrate' command
I am new to Django, and for some odd reason my models are not creating a database table and am completely clueless as to why. When I run the command: "python manage.py makemigrations" I get the following shows up int he console output: Migrations for 'auctions': auctions/migrations/0001_initial.py - Create model User - Create model Item Which appears to be accurate to me. So then I run the command: "python manage.py migrate" and the following shows up in the console output. Operations to perform: Apply all migrations: accounts, admin, auctions, auth, contenttypes, sessions Running migrations: No migrations to apply. Looking into the database and sure enough nothing was created. Below is output of my models.py file: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): def __str__(self): return f"{self.first_name}" class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="item_list") title = models.CharField(max_length=64) description = models.CharField(max_length=256, blank=True) img_url = models.CharField(max_length=256, blank=True) starting_bid = models.DecimalField(decimal_places=2, max_digits=8) category = models.CharField(max_length=24, default='No Category') status = models.BooleanField(default=True) def __str__(self): return f"{self.title}, {self.description}" -
Hello. I try do command docker-compose up (build I have already did) project with django + mySQL (api) . But I got exceptions:
So this my DockerFile: FROM python:3.9.1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/outlet COPY ./req.txt /usr/src/req.txt RUN pip install -r /usr/src/req.txt COPY . /usr/src/outlet EXPOSE 8000 My docker-compose.yml: version: '3.7' services: db: image: mysql:8.0 restart: always volumes: - mysql_data:/var/lib/mysql/data/ environment: MYSQL_ROOT_PASSWORD: 12345678D MYSQL_DATABASE: outlet web: build: context: ./ dockerfile: Dockerfile command: bash -c "python /usr/src/oultet/manage.py migrate --noinput && python /usr/src/outlet/manage.py runserver 0.0.0.0:8000" volumes: - .:/usr/src/outlet ports: - 8000:8000 depends_on: - db volumes: pg_data: mysql_data: My prestart.sh: #! /usr/bin/env bash sleep 10; python manage.py migrate sleep 10; python manage.py runserver 0.0.0.0:8000 And finally my settings.py: """ Django settings for Outlet project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") #'23&b)#mf&wc2j+8&r%stc+9-0*5byqcr59_=!h2vvb3wo8dp-m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = int(os.environ.get("DEBUG",default=0)) ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', … -
Django Feedparser Inex out of range issue
Im building feed scraper application as a beginner project using the feedparser module. I have everything working ok except there are some feeds where the description needs sanitization as its mixed up with noise that I do not want to display witin the webapp. Here is the code that I can tried in python which works: Code that give desired output in python Now here is the code that I have in my views.py file which gives an index error: Code in Django that gives index error Any help would be really appreciated, I just cant understand why this code works in Python but Django seems to throw an error. Many thanks in advance. -
create appointment app with django with non register user
I'm trying to create an appointment app with Django for register and non register user in the case of register user it's easy but for non register user my idea is to create a temporary user with just a few information in the user form and the profile form but it showed me nothing in the html file and in the first case it did not save the appointment this is my function in the views.py @login_required def create_appointment_D(request): if request.method=='POST' : user = User() if request.user.is_doctor() or request.user.is_reception(): appointment = request.POST['type'] if appointment=='register patient': form_appointment = AppointmentForm_2() if form_appointment.is_valid(): form_appointment.save(commit=False) form_appointment.user = request.user form_appointment.end_time = form_appointment.start_time + timedelta(minutes=30) form_appointment.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') else: form_appointment = AppointmentForm_2() form_user = UserEditForm() profile_form = ProfileUpdateForm() if form_appointment.is_valid() and form_user.is_valid() and profile_form.is_valid(): form_appointment.save(commit=False) form_appointment.user = request.user form_appointment.end_time = form_appointment.start_time + timedelta(minutes=30) form_user.save(commit=False) form_user.type_of_user = user.type_of_user.TEMPORARY profile_form.save(commit=False) form_appointment.save() form_user.save() profile_form.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement1.html', {'form':form_appointment, 'user_form':form_user, 'form_appointment': profile_form}) else: return HttpResponseRedirect(reverse("create_appointment_P")) return render(request,'appointement/add_appointement_options.html') this is my forms.py class AppointmentForm_2(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) patient = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.PATIENT)) date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) start_time = forms.DateField(widget=forms.DateInput(attrs={'type': 'time'})) class Meta: model = Appointment fields = ('patient', 'doctor', 'date', 'start_time') class UserEditForm(forms.ModelForm): … -
Checking if values are in JSON received via API (Python / Django)
I am trying to check if certain values are within data sent by stripe to a webhook in my Django application. The data received looks like this within a WebHookEventTrigger model in a field called 'body' (removed some irrelevant fields): Body= { "id": "evt_1IX2nQHiJcStEaySS5pgOO4l", "object": "event", "api_version": "2020-03-02", "created": 1616239004, "data": { "object": { "id": "cs_test_a1ZHPGoSfEreDQhdioGxpWgYc1y5lhnwuo5qdeOsBqpio764yk0caFIBwg", "object": "checkout.session", "amount_subtotal": 1000, "amount_total": 1000, "currency": "gbp", "customer": "cus_1234", "customer_details": { "email": "abc@gmail.com", }, "customer_email": null, "mode": "payment", "payment_intent": "pi_1234", "payment_method_types": [ "card" ], "payment_status": "paid", "total_details": { "amount_discount": 0, "amount_tax": 0 } } }, "type": "checkout.session.completed" } I'm trying to see if certain values are in the json data as follows, although I receive errors with this code such as 'Unsupported lookup 'data' for TextField or join on the field not permitted': Values I am checking: chargeamount = 1000 chargecustomer = cus_1234 chargetimestamp = str(1616239004) chargetimestamp = chargetimestamp[:-3] #cut last 3 digits of timestamp as seconds will vary Code to check if values exist: checkoutsession = WebhookEventTrigger.objects.get(body__data__object__customer=chargecustomer, body__data__object__amount_total=chargeamount, body__created__icontains=chargetimestamp) checkoutsessionid = checkoutsession.body['data']['object']['id'] -
Authenticate a user login based on face encodings stored on database?
I am working on a face-login project where a user can submit his images using a webcam during the registration and login to the website using a live camera feed. The problem I am facing currently is submitting the snapshot stored on the HTML canvas a form "response" and storing the face-encoding or the entire image for now to the database associated with this user. I have successfully created a Registration / Login page that authenticates based on the Username and the Password for now. I made this using the 'User' model imported from django.contrib.auth.models. I read a bit about OneToOne models but it says not to be used for Authorization and I specifically need it for Authorizing the login. On the Registration page, I have added a section where a user can click a button and take a snapshot. The problem is How do I submit this image as a part of the form? Store this base64 image to the Database which I will retrieve later for Authentication. Any hints on how to proceed would be great! I tried modyfing the User model to have an extra face_data field but it doesn't work. Views.py from django.shortcuts import render, HttpResponse, … -
Django Admin Page show model referencing to another model as choose list
I already created a new database instance called StatusList: class StatusList(models.Model): status_text = models.CharField(max_length=300) color = ColorField(default='#ff0000') def __str__(self): return self.status_text I also created some entries like: "Shop closed; red color", "Shop open; green color", etc... This is supposed to show up, when calling the Homepage and show the status with the associated color. Therefore, I would like to choose (drop-down list in Admin Page) one entry provided by StatusList. I thought about a second model called "StatusChoosen", but does it make sense? It is an instance with just one entry representiong the one choosen by an admin. Even in this case I don't know how to show all entries from StatusList and return the active one. I would appreciate your help.