Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration error when database has custom views
Django 3.1. app folder : stocks project folder with settings inside: main I have this model: class Bar(models.Model): stock = models.CharField(max_length=10) timestamp = models.DateTimeField() date = models.DateField() time = models.TimeField() open = models.DecimalField(max_digits=6, decimal_places=2) high = models.DecimalField(max_digits=6, decimal_places=2) low = models.DecimalField(max_digits=6, decimal_places=2) close = models.DecimalField(max_digits=6, decimal_places=2) is_regular = models.BooleanField() change = models.DecimalField(max_digits=10, decimal_places=4) In the SQLite database I have created view daily_bottoms from that model using SQliteStudio. Now I am trying to migrate because added another field. makemigrations works fine, but when trying to migrate I get an error: django.db.utils.OperationalError: error in view daily_bottoms: no such table: main.stocks_bar If I delete the view then it will migrate , but I would like to avoid that every time. How to make it work? -
Django admin 'pk' attribute error in main site
I am using the default admin site with the following config: urls.py: urlpatterns = [ path('admin/', admin.site.urls) ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin' ] admin.py admin.site.register(Student) I removed everything unrelated to admin. The error AttributeError: 'NoneType' object has no attribute 'pk' occurs ONLY when accessing localhost/admin. In other words, accessing the database directly like localhost/admin/school/student doesn't throw an exception. Full Traceback: Traceback (most recent call last): File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 202, in _get_response response = response.render() File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py", line 938, in render bit = … -
Django How to convert image to base64 then make a post request with the result
I'm trying to make a form with an image upload field then I convert this image to base64 and make a post request to an API with the base64 in the body my forms.py: class FridgeForm(forms.ModelForm): class Meta(forms.ModelForm): model = Fridge fields = [ 'name', 'date', 'picture' ] widgets = { 'date': forms.DateTimeInput } I tried to do it with jquery using val() but I get the image path string not the image $(document).on('submit', function(e){ e.preventDefault(); }) function canvasBase64(image) { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = image.width; canvas.height = image.hight; ctx.drawImage(image, 0, 0) return canvas.toDataURL('image/jpeg') } $("button.encode").on("click", function(){ const image = $("input[name=picture]").val() console.log(typeof image) console.log(image) canvasBase64(image, function(base64) { console.log('RESULT: ', base64) fetch(url, { method: 'POST', headers: { "X-CSRFToken": csrftoken, }, body: (base64) }) .then(response => response.json()) .then(data => { console.log('data: ', data) }) }) }) -
Django CMS in Django
I am building a django app that would allow users to create html content (to be used as an email template), but keep getting TemplateSyntaxError. I am trying to use the django-cms plugins in my own view and templates any ideas. {% extends 'admin/merchant/base.html' %} {% load cache %} {% load cms_tags %} {% block extra_head %} {% placeholder "css" %} {% endblock extra_head %} {% block content %} <body> {% cms_toolbar %} {% placeholder "content" or %} Nothing is coming through... {% endplaceholder %} </body> {% endblock content %} but i get this error: Template error: In template /home/joel/Projects/Vendora Deploy/src/templates/admin/merchant/newsletter/create-page.html, error at line 15 Invalid block tag on line 15: 'endblock'. Did you forget to register or load this tag? 5 : {% block extra_head %} 6 : {% placeholder "css" %} 7 : {% endblock extra_head %} 8 : 9 : {% block content %} 10 : <body> 11 : {% cms_toolbar %} 12 : 13 : {% placeholder "content" or %} Nothing is coming through... {% endplaceholder %} 14 : </body> 15 : {% endblock content %} 16 : 17 : 18 : ``` [1]:[Traceback Image][1] https://i.stack.imgur.com/PkHi9.png -
How do I write a rest framework serializer to create an instance of a model containing both foreign key relations and generic relations?
I'm trying to create instances of a model using a POST method on django rest framework. I need a serializer method which can handle the logic behind this. In my models I have two instances of a foreign key and one instance of a generic relation foreign key. Here are my models: class UserModel(models.Model): MEMBERSHIP_TYPE = [ ('NM', 'NORMAL'), ('PT', 'PLATA'), ('OR', 'ORO'), ('PL', 'PLATINO'), ] id = models.AutoField(primary_key=True) username = models.CharField(max_length=100) photo = models.ImageField(upload_to='images/', blank=True) address = models.TextField() client_type = models.CharField(max_length=2, choices=MEMBERSHIP_TYPE, default= 'NM') def __str__(self): return self.username class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField() description = models.TextField() def __str__(self): return self.code class OrderModel(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey('UserModel', on_delete=models.CASCADE) gen_time = models.DateTimeField(auto_now_add=True) gen_supplied = models.DateTimeField() urgent = models.BooleanField() order_to = GenericForeignKey() article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() object_id = models.BigIntegerField(default=None, null=True) content_type = models.ForeignKey( ContentType, default=None, null=True, on_delete=models.SET_NULL) class WarehouseModel(models.Model): id = models.AutoField(primary_key=True) warehouse_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class StoreModel(models.Model): id = models.AutoField(primary_key=True) reference = models.IntegerField() store_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class BusinessModel(models.Model): id = models.AutoField(primary_key=True) reference = models.IntegerField() store_num = models.IntegerField() order_rel = GenericRelation(OrderModel) class DetailModel(models.Model): id = models.AutoField(primary_key=True) detail = models.TextField() order = models.ForeignKey('OrderModel', on_delete=models.CASCADE) and here's my serializer so far: class … -
See how many orders he has on his profile page. Django
When I enter my user profile page, I want it to see the total number of orders until today. i tried aggregate and annonate but it's not work. I hope so i use filter method but i don't know how to do it. Orders count = adet in model I added ""if siparis.bayi_id == user.id"" so that the user entering can take action on his orders. Temp Html {% for siparis in siparis %} {% if siparis.bayi_id == user.id %} <strong>{{ a }}</strong><br><small>Siparişler Toplamı</small> {% endif %} {% endfor %} Model Siparis means order class Siparis(models.Model): bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"}) urun = models.ForeignKey(Urun, on_delete=models.CASCADE) adet = models.IntegerField() tarih = models.DateTimeField() status = models.BooleanField() @property def miktar(self): return (self.adet * self.urun.fiyat) @property def fiyat(self): return self.urun.fiyat class Meta: verbose_name = 'Bayi Sipariş' verbose_name_plural = 'Bayi Siparişleri' views def bayi_bayidetay(request): siparis = Siparis.objects.all() urunler = Urun.objects.all() bayiler = bayi_bilgi.objects.all() a = Siparis.objects.aggregate(Sum("adet")) return render(request,'bayi/bayi_detay.html',{'bayiler':bayiler,'siparis':siparis,'urunler':urunler, 'a': a}) Thank you -
how to trigger AWS Lambda function with Django framework?
I need to create a Button with Django Framework and connect to trigger lambda function (aws), click to button to should trigger the function. Also, another page to upload files to S3 Bucket with django from local. Should I work on REST API or there is a way around this. how to get started on this or execute the idea? also helpful if you could share resources on this. -
CkEditor image works in localhost but in production it doesn't preview image and save image in Django framework
Here is my settings.py file. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' MEDIA_ROOT = MEDIA_DIR CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { 'default': { 'extraPlugins': 'codesnippet', 'toolbar': 'full', 'height': 300, 'width': '100%', 'contentsCss': 'img {max-width: 100%;height: auto! important;}', }, } I have kept CKEditor folder under the static folder. Uploading images using RichTextUploadingField works correctly in localhost. In Production server (cPanel) after DEBUG = False it is not previewing any images clicking "Send it to the Server" and not saving the images. Please help regarding the issue. -
Field 'id' expected a number but got <QuerySet [<Example: 9NjKaWHB3q6SVSq>]>
I wish you a good years, I got an issue. I'd like to get resa_exemple == exemple But I got an issue with this Field 'id' expected a number but got <QuerySet [<Example: 9NjKaWHB3q6SVSq>]> I don't really understand why? class RerservationOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) exemple = models.ManyToManyField('Example',blank=True, related_name='reservation_order_exemple') ... class Reservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) resa_order = models.ManyToManyField('RerservationOrder',blank=True, related_name='resa_order_reservation') resa_exemple = models.ManyToManyField('Example',blank=True, related_name='resa_order_example') def AddResaOrder(request, slug, pk): current_reservation = get_object_or_404(Reservation, slug=slug) cuisine = get_object_or_404(Cuisine, id=pk) resa = current_reservation.resa_exemple.all() if request.method == "POST": #this work create_resa_order = current_reservation.resa_order.create(user=request.user, ...) #this does not work create_resa_order.exemple.add(resa) #this work current_reservation.resa_order.add(create_resa_order) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Handling text files Heroku's ephemeral file-system to upgrade Python
My Python runtime for one of my first Django projects which I am working on that I am deploying to Heroku is out of date. It’s Python version 3.6.7. My build log tells me I should be using a more recent version - - v3.6.12. When I Google, ‘how to upgrade python heroku’, the first search result is the official Heroku doc which identifies supported run times. The doc explains to view your current run time, you can use: $ python --version or in the project root use $ cat runtime.txt and to select a run time, you can change the contents of runtime.txt. I found the file and I can view its contents with cat. It’s Python v3.6.7 for sure, which is out of date and needs to be changed. The two problems I have encountered are: Viewing the file is easy. What I can’t figure out is how to open/edit runtime.txt. My first instinct is to try CLI interface text editors such as vim, vi, pico, nano, all of which are not installed. My question is: How do I edit text files for my Django project on Heroku? Even once I find that out, my next problem is … -
How can I dynamically define forms.IntegerField's min_value parameter?
I am working with Django and its Forms classes. I have created a Form with a single forms.IntegerField and I want to define its min_value parameter dynamically: class BiddingForm(forms.Form): bidding_form = forms.IntegerField(min_value=1, help_text="€", label="Bid") Right now, it is statically set to 1. I have tried to overwrite the __init__() function and pass in a min_value there. But since bidding_form is a class variable, I cannot use the resulting instance variable min_value on it: class BiddingForm(forms.Form): min_value = 1 def __init__(self, min_value): super().__init__() self.min_value = min_value bidding_form = forms.IntegerField(min_value=min_value, help_text="€", label="Bid") As of my understanding, above class creates an instance variable min_value inside of __init__() which just shadows the class variable min_value and it ultimately results in min_value being 1 in the bidding_form's declaration. Since I have little understanding of Python and Django, I have not yet found a solution to this. So, how can I dynamically define forms.IntegerField's min_value parameter? -
Explanation on Django's request processing - Why does it select one urlpattern from another
So I am doing an free online course that involves Django and have run into something that is rather confusing regarding how Django processes requests. My Django application has a single module and within this module I have essentially two pages that I am generating both of which inherit from a layout template. There is an index page (which contains links to individual entries) and an entry page which displays the content of each individual entry. There are two ways to get to an entry page. You could either directly click on the link that is present on the index page or you could type in the search bar that is present on index page. If the name matches the entry in the search bar it will take you to that entry page. Each method of reaching an entry page has its own url pattern in the urls.py file and each one has its own route function in the views.py file. What was happening was that regardless of what was typed into the search bar, it would only use the route that was meant for directly clicking on the entry link from the index page rather than the route that … -
Could not setup django-oauth-toolkit authentication
I'm going to restrict my working rest_framework.views.APIView inherited class, to be visible only by authenticated users. I made these modifications: Added authentication_classes and permission_classes to my class: class TestView(APIView): authentication_classes = (OAuth2Authentication,) permission_classes = (IsAuthenticated,) return Response("Hey there...") Got an access_token from django-oauth-toolkit: curl -XPOST "http://172.18.0.1:8000/oauth2/token/" \ -d 'grant_type=client_credentials&client_id=MY-CLIENT-ID&client_secret=MY-CLIENT-SECRET' {"access_token": "Haje1ZTrc7VH4rRkTbJCIkX5u83Tm6", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups"} Tried requesting the view without setting the access_token: curl -XGET "http://172.18.0.1:8000/api/v1/test/" {"detail":"Authentication credentials were not provided."} Tried a new request with the access_token: {"detail":"You do not have permission to perform this action."} Should I do anything more to enable access_token authentication? Note: I have installed these libraries in the environment: Django==2.2.17 djangorestframework==3.12.2 django-oauth-toolkit==1.3.3 -
Error in the Syntax of Django urls.py file
in my website urls.py file for the file named "pollsapp"(name of my project) my code is from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('',include('pollsapp.urls')), ] also my website urls.py code for the file named "appy" ( which is my name of the web application) from django.urls import path from . import views urlpatterns = [ path('',views.home, name = 'home') ] and the error I am getting in both the urls terminal is : File "C:\Users\HP User\djangocode\pollsapp\pollsapp\urls.py", line 21 path('admin/', admin.site.urls), ^ SyntaxError: invalid syntax -
Block tags not appearing in django html template
I might have a bit complicated case but here it is, I have this base.html file which not only contains the tags, {% block title %}{% endblock %} But also some other tags for my navbar such as, {% block home %}{% endblock %}{% block profile %}{% endblock %}where I implement my active class. My navbar is being used as a separate html file which I am rendering using the include tag. The problem is, whenever I extend my base.html file, and render another html template, the title block works fine, but the ones in the navbar don't. Here is how I render it in my home.html {% extends 'base.html' %} {% load static %} {% block title %}Home{% endblock %} {% block home %}active{% endblock %} {# this tag doesn't work #} -
i am using five anchor tag but only first four working
i am working on a django project where i have use 5 anchor tag first 4 anchor tag working fine but the 5th one is not even behaving like a link ,my cursor not changing to pointer <div class="nav-bar"> <a href=""> home </a> <a href=""> about </a> <a href=""> contact </a> <a href=""> message </a> <a href=""> post </a> </div> -
Docker "is not a valid port number or address:port pair."
I am new in docker. I want to run my django app on port 9000. After command docker-compose up I am getting this message Creating motion_full_version_backend_1 ... done Attaching to motion_full_version_backend_1 backend_1 | Unknown command: 'makemigrations\r'. Did you mean makemigrations? backend_1 | Type 'manage.py help' for usage. backend_1 | Unknown command: 'migrate\r'. Did you mean migrate? backend_1 | Type 'manage.py help' for usage. " is not a valid port number or address:port pair.* My Dockerfile : FROM continuumio/miniconda3:latest ENV LANG=C.UTF-8 LC_ALL=C.UTF-8 RUN apt-get update && apt-get upgrade -y && apt-get install -qqy \ wget \ bzip2 \ graphviz RUN mkdir -p /backend COPY ./backend/requirements.yml /backend/requirements.yml # Create environment RUN /opt/conda/bin/conda env create -f /backend/requirements.yml # Add env path to environment ENV PATH /opt/conda/envs/backend/bin:$PATH # Activate interpreter RUN echo "source activate backend" >~/.bashrc # Create a scripts folder RUN mkdir -p /scripts COPY ./scripts /scripts RUN chmod +x ./scripts* COPY ./backend /backend WORKDIR /backend I am using script to run it python manage.py makemigrations python manage.py migrate python manage.py runserver 0.0.0.0:9000 my docker-compose.yml looks like this version: '3' services: backend: image: backend:latest restart: always env_file: - ./envs/dev.env command: 'sh /scripts/dev.sh' ports: - "9000:9000" Any Ideas what I am doing wrong? -
How to combine jwilder-nginx + django?
Honestly, I don't know nothing about nginx configuration and terms like "reverse proxy". I want to run my django project locally only, this is my actual docker-compose file configuration: version: "3" volumes: local_postgres_data: {} local_postgres_data_backups: {} services: nginx: image: nginx:alpine container_name: nz01 ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web networks: - djangonetwork web: build: context: . dockerfile: compose/django/Dockerfile container_name: dz01 depends_on: - db volumes: - ./src:/src expose: - "8000" links: - redis env_file: - ./.envs/.django networks: - djangonetwork db: build: context: . dockerfile: compose/postgres/Dockerfile container_name: pz01 env_file: - ./.envs/.postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups networks: - djangonetwork redis: image: redis:alpine container_name: rz01 ports: - "6379:6379" networks: - djangonetwork networks: djangonetwork: driver: bridge and my nginx config file: client_max_body_size 10M; upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /src/static/; } location /media/ { autoindex on; alias /src/media/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } I have read that Kubernetes Ingress service can be recreated for docker-compose with jwilder-nginx image, so you can have https certificate and use a url instead of host machine ip to access your django service, but I don't know how to … -
How to create a serilizer for this queryset :
Take a look at my queryset : def get_queryset(self,*args,**kwargs): user = self.request.query_params.get('user',None) if user is None: raise ValidationError(detail={'user':'This field is required — send as a query_param'}) user, created = User.objects.get_or_create(username=user) if created: raise ValidationError(detail={'user':'Invalid username'}) visiter = self.request.user if user.profile.private: followers_obj, created = Follow.objects.get_or_create(user=user.profile) if not followers_obj.followers.filter(username=user).exists(): raise ValidationError(detail={'Private account':'This account is private , follow the user to access the followers'}) _all_ = [] followers_obj, created = Follow.objects.get_or_create(user=user.profile) all_followers = followers_obj.followers.all() # FOllowers are User instances for follower in all_followers: follower_username = follower.username try: follower_profile_picture = follower.profile.profile_picture.url except: follower_profile_picture = "" if len(follower.first_name) == 0 and len(follower.last_name) == 0 : follower_name = follower_username else: follower_name = follower.get_full_name() follower_follows_me = follows(follower,visiter) i_follow_follower = follows(visiter,follower) follower_ispublic = not follower.profile.private follower_obj, created = Follow.objects.get_or_create(user=follower.profile) follow_request_sent = follower_obj.followRequests.filter(user=visiter).exists() user_info = [follower_username,follower_profile_picture,follower_name, follower_follows_me,i_follow_follower,follower_ispublic,follow_request_sent] _all_.append(user_info) return _all_ And now take a look at my serilizer : class FollowersSerilizer(serializers.Serializer): follower_username = serializers.CharField(max_length=150) follower_profile_picture = serializers.CharField(max_length=None) follower_name = serializers.CharField(max_length=150) follower_folllows_me = serializers.BooleanField() i_follow_follower = serializers.BooleanField() follower_ispublic = serializers.BooleanField() follow_request_sent = serializers.BooleanField() When I make an API call , i get the following error : Traceback (most recent call last): File "C:\Users\Farhan Syedain\AppData\Local\Programs\Python\Python39-32\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "C:\Users\Farhan Syedain\AppData\Local\Programs\Python\Python39-32\lib\site-packages\rest_framework\fields.py", line 97, in get_attribute instance = … -
Pass Factories in Pytest parametrize
I'm trying to pass Factories in my pytest tests but I'm having some difficulty with it. A bit of context -- based on a string, I have some logic which attempts to set a Django model AudioAsset as a foreign key on some models, e.g. a Story or a Song. What I want to test is this logic class AudioAsset(models.Model): ... class Story(models.Model): background_music = ForeignKey(AudioAsset) ... class Song(models.Model): vocals = ForeignKey(AudioAsset) ... I've created a StoryFactory and SongFactory to help me with testing, but I'm having some trouble using pytest.mark.parametrize together with factories @pytest.mark.parametrize( "factory,attribute_name,string", ( (StoryFactory, "background_music", "story-1-background"), (SongFactory, "vocals", "song-2-sound"), ) ) def test_attach_audio_asset(): audio_asset = AudioAssetFactory() model_instance = factory() # Errors here when I try to use a Factory # Trigger the relation update # ... assert getattr(model, attribute_name) == audio_asset I get an error function uses no argument 'factory'. How can I use both factory-boy and pytest together? -
Django Register account activating with send email
I want to create registration, after registering user get email and after clicking url (which will be in user's email) their account will activate. I added Email configurations in settings.py using Celery and django signals. How should I write? Here is my codes models.py from django.db import models from django.conf import settings from django.core.mail import send_mail from .tasks import email_user from django.contrib.auth.models import ( AbstractBaseUser, User, UserManager, PermissionsMixin ) class UserManager(UserManager): def create_user(self, email, password=None): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): user = self.create_user(email, password) user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=100) surname = models.CharField(max_length=100) email = models.EmailField(unique=True) phone = models.IntegerField(unique=True, null=True) profile_img = models.ImageField(upload_to='images', null=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email class EmailConfirmed(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) is_active = models.BooleanField(default=False) def __unicode__(self): return str(self.is_active) def activate_user_email(self): message="Click url to activate your account" email_user.delay(message, settings.DEFAULT_FROM_EMAIL) tasks.py from .celery import app from .models import activate_user_email from django.core.mail import send_mail @app.task def email_user(self,message,from_email=None, **kwargs): send_mail(message, from_email,[self.user.email],, kwargs) -
how to auto add inline models in django admin page
i have a model in django admin, and that model have 2 inline models inside it as shown : @ admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): inlines = [FamilyGroupInline, FamilyMemberInline] fieldsets = ( (None, { 'fields': ('complete',), }), ('Transaction Details', { 'fields': ('chp_reference', 'income_period', 'property_market_rent', 'rent_effective_date', 'number_of_family_group',), }), ('Report', { 'classes': ('collapse',), 'fields': ('report',), }), ) im trying to customize the Transaction admin page, i want the two inline models be added automatically once i start a new Transaction, and dont have to click "add another ..." button what is the best approach to achieve that ? would appreciate your help! -
exceptions in django not showing
This is my first project in django framework, I am using visual studio code. I am trying to save data from user registration form to database. What I am trying to achieve is:: how to check whether the form is validate or not in server side something like in asp.net Page.IsValid method. Now suppose my page is validate and then while trying to save my data, there occur some network error or via other reasons there is error. Then how can I show the complete error in my page. Also what libraries I have to import for that? My code:: user = User.objects.create_user(username = username, password = password) try: user.save() messages.success(request, 'successfully registered') except Error as e: raise ValidationError(e) messages.error(request, e) Here in my code, how can I show the complete error or exceptions occured during the user.save() method. Currently this code is not working. I did not know how to proceed further since this is my first project in django. Thank You! -
How to pass an argument in django templatetag or call form valid like in the views?
Hi Guys I want to add CreateView to be accessible all my web pages, so I opted for template tags, which bring out the form quite nicely but it can't save. I believe because of the user field which I want to be automatically added before saving the form. in Views.py is quite simple. class BusinessCreate(LoginRequiredMixin, CreateView): model = Business form_class = BusinessAddForm template_name = 'business/form.html' def form_valid(self, form): form.instance.user = self.request.user # this is what i want to add in templatetags messages.success(self.request, 'successfully created your biashara') return super().form_valid(form) this is my form.py class BusinessAddForm(ModelForm): logo = forms.ImageField(label='', required=False, widget=forms.FileInput(attrs={'placeholder': 'your logo'})) description = forms.Field(label='', widget=forms.Textarea(attrs={'placeholder': 'Describe your biashara'})) name = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Your biashara name'})) email = forms.EmailField(label='', required=True, widget=forms.TextInput(attrs={'placeholder': 'Email'})) class Meta: model = Business fields = ( 'name', 'logo', 'email', 'description') Now I have a template tag templatetags/business.py from django.template import Library from business.forms import BusinessAddForm register = Library() @register.inclusion_tag('includes/business_form.html', takes_context=True) def get_business_form(): form = BusinessAddForm() return { 'form': form, } which renders the form quite well but doesn't save. No errors though. so where can I add the current logged in user to user Field? my models.py class Business(models.Model): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=200, … -
How to search in a object only (django)
so I want to create a search bar that allows you to search for a specific object. Here is a website for example: https://www.thumbtack.com/ Basically, I want it to give you options that you can select from, and I also want it to autocomplete what you're typing. (You cannot search if it's one of the options). How can I do that?