Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Problem with CKEDITOR attachments integrated in Django contact mail form
I integrated ckeditor in my contacts form-email following the instructions provided by the official documentation and it works correctly. My problem is the following (both locally and in production): when I attach an image or an attachment (via ckeditor uploader) and send the email from the form, I receive an email in which the image is not visible and the attachment is not downloadable. By copying the link of the image or attachment, the path is shown and not the url .. I think this is the problem. Don't know how to fix it? Anyone have any ideas? Thank you in advance!!! Below is the code I used: settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'core/static'), os.path.join(BASE_DIR, 'appForum/static'), os.path.join(BASE_DIR, 'appEventi/static') ] STATIC_URL = '/static/' STATIC_ROOT = "/home/django/static-serve" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media-serve') MEDIA_URL = '/media/' CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'ckeditor_uploads' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'toolbar_custom': { 'toolbar': 'Custom', 'skin': 'moono-lisa', 'width': 'auto', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat', 'Source',], {'name': 'insert', 'items': ['Image', 'Update', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar']}, {'name': 'extra', 'items': ['CodeSnippet']}, ], }, } models.py from ckeditor_uploader.fields import RichTextUploadingField # Create your … -
How to write save Postgresql query in Django
In my Django project I have SQL query like this: `..." WHERE column1 LIKE %s", query + " OR column2 LIKE %s", query...` I read that using the %s" is good practice because it prevents SQL injection, but when i run this I get an error like `can only concatenate tuple (not "str") to tuple`. How to write this query properly and avoid SQL injection? (Disclaimer: I know that ORM is fantastic, but I HAVE TO use raw query) -
Comparing list coming from form-field with database field of multiple values and filter out the objects [django]
I have postgresql database setup with django framework. straight to the problem I am facing, let's say in one of the database fields contains country data like "US,India,UK" (for this I have use django multiselectfield package to store data in database) and data coming from frontend is like "India,US" something like that. Now I have to filter object based on this. I can't use __in filter of django because it compare single value store in database to the list. any solution ? -
Django ./manage.py test is failing
I've created a migration file with 3 RunSQL operations. First operation is to drop a column and other two operations are to delete table data and the migration file is working fine. But ./manage.py test is failing with the below error. django.db.utils.ProgrammingError: column xxx does not exist. I can see the column is dropped in test_##app## db, but it is trying to drop column again. I can also see the migration file entry in django_migrations. Is there a way to check if the column is available or not before executing the ALTER operation in migration file? -
Trying to override djoser serializer getting AttributeError: Got AttributeError when attempting to get a value for field error
I am new to djoser I am user to authenicate a user. I then wanted patient information to be displayed when user/me is accessed but i overrode it to also show patient details as well but I go this error Error AttributeError: Got AttributeError when attempting to get a value for field `blood_sugar_level` on serializer `PatientInfoSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the UserProfile instance. Original exception text was: 'UserProfile' object has no attribute 'blood_sugar_level'. Models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.conf import settings # used to retreive AUTH_USER_MODEL from settings.py file # These two imports allow for the default user model to be customized or overrided from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin # Default model manager from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name,) user.set_password(password) #This hashes the user password so we do not have plain text passwordfs in our db user.save(using=self._db) return user def create_superuser(self, email, name, password): …