Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to fetch data for my website from 3rd party website in Django
I wanted to learn, how to fetch any kind of integer value from any website (with a particular given link). suppose if I search by today's temperature in google, it shows like this: I prefer to use Django. How can I fetch the value of temperature from this page? I mean what should be the views.py look like for this? I am totally new to this type of data fetching, having zero knowledge of this, please suggest to me some tutorial link or blog if you prefer. -
get_next/prev_by after searching django
I have trouble after trying to use get_next_by_FOO/ get_previous_by_FOO after searching. For example, Search result gives 10 differences results. if I click the first, It shows information. Then I click next, it won't show the second result in 10 results, shows the next value in data. I know where is the issue In my code, contract get data from Model Contract, not from search result, that is why I click next it doesnt show the result, but I dont know to fix in views.py #def show contract information def contract_detail(request, contract_id=None): contract = get_object_or_404(Contracts, contract=contract_id) try: the_next = contract.get_next_by_created_at() except: the_next=None try: the_prev = contract.get_previous_by_created_at() except: the_prev=None context = { "contract": contract, "the_next" : the_next, "the_prev": the_prev, } return render(request, "contract_detail.html", context) #def show list contract after seaching and pagination def list_contract(request): context = {} if request.method == 'GET': query1= request.GET.get('search1') query2= request.GET.get('search2') submitbutton= request.GET.get('submit') if query1 is not None: lookups_contract= Q(contract__icontains=query1) lookups_name = (Q(name__icontains=query2.upper())|Q(name__icontains=query2.lower())) results= Contracts.objects.filter(lookups_contract,lookups_name).distinct() contract_posts=results CONTRACT_POSTS_PER_PAGE = 10 CONTRACT_POSTS_PER_PAGE = request.GET.get('CONTRACT_POSTS_PER_PAGE', CONTRACT_POSTS_PER_PAGE) or 10 #pagination cho query search page = request.GET.get('page', 1) contract_posts_paginator = Paginator(contract_posts, CONTRACT_POSTS_PER_PAGE) try: contract_posts = contract_posts_paginator.page(page) except PageNotAnInteger: contract_posts = contract_posts_paginator.page(CONTRACT_POSTS_PER_PAGE) except EmptyPage: contract_posts = contract_posts_paginator.page(contract_posts_paginator.num_pages) context['contract_posts'] = contract_posts return render(request, "customer.html", context) … -
Unable identify mistake in URL pattern
I have 3 apps inside django project (leadmanager) leads, frontend, accounts Everything is working fine if I dont include accounts.urls (from accounts app) in leadmanager.urls but as soon as I include accounts.urls I getting the following error (all of these apps are registered in settings.py): $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Danial Ahmed\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Danial Ahmed\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Danial Ahmed\Desktop\Learning\django-react\venv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) … -
django get count of 'children' of related_name field (and do this in template?)
I am trying get the list of HQ (Head Quarter) Field Manager and count of Animal and Agent under Field Manger. Each foreign code has a related name. Models are class Fm(models.Model): hq = models.ForeignKey(Hq, on_delete=models.SET_NULL,null=True) fm = models.CharField(max_length=50) class User(AbstractBaseUser): email = models.EmailField(max_length=255,) fm = models.ForeignKey(Fm,on_delete=models.SET_NULL,related_name="agents") class Animal(models.Model): agent = models.ForeignKey(User,on_delete=models.SET_NULL,related_name="animals") farmer = models.CharField(max_length=50') View def print_table(request): fms = Fm.objects.all() context = {'fms':fms} return render(request, 'fm.html',context) Template {% for fm in fms %} <tr> <td>{{fm.hq}}</td> <td>{{fm.fm}}</td> <td>{{fm.agents.animals.all.count}}</td> (Error here) <td>{{fm.agents.all.count}}</td> </tr> {% endfor %} Expected OutPut HQ FM_Name Animal_Count Agent_Count HQ1 Any Name 10 (Not Working) 2 Current Output HQ FM_Name Animal_Count Agent_Count HQ1 Any Name 2 This is listing count of Animal but I need sum of all {% for x in fm.agents.all %} <div>{{x.animals.all.count}}</div><br> {% endfor %} Anyone Please Help Me -
How to add new Foreign Key objects in a Form in Django?
I have a blog that uses Django and currently I am building a page for creating new posts. In my Post model I have a Foreign Key field that is linked to a ImageField. When rendering the page using a generic class view, the field is displayed as a drop-down as expected, but I would like to add new thumbnails, not only selecting the existing ones, similar to the behavior of the admin page when there is a Foreign Key field, where: There is a plus sign next to the drop-down When clicked, shows a pop up where I can upload the image After uploading the image, return to the main page, where the new option is created in the drop-down How can I have a behavior similar to the admin's in my page? I tried to implement it as a widget, but the end result is very messy, as it just redirects to the admin page and I have to go back to my post creation page and reload to show the new option. Alternatively I could just replace the the Foreign Key drop-down with a field to upload a file, but I don't know how, as the foreign … -
unique constraint with objects.get_or_create
I've a unique constraint error : django.db.utils.IntegrityError: UNIQUE constraint failed: wikis_article.title this is my code: def Article_Edit(request, articleid): article = Article.objects.get(pk = articleid) form = EditForm(instance=article) if request.method == "POST": article_form = CreateForm(request.POST) if article_form.is_valid(): Article.objects.get_or_create( title=article_form.cleaned_data["title"], content=article_form.cleaned_data["content"], ) messages.success(request, 'article successfully added') return HttpResponseRedirect(reverse("Article_List")) return render(request, 'wikis/article_create.html', {"form": form}) with my model: class Article(models.Model): title = models.CharField( max_length=512, null=False, blank=False, unique=True,verbose_name=_("title")) content = MarkdownxField(blank=True, verbose_name=_("article contents")) created = models.DateTimeField( auto_now_add=True, verbose_name=_("created"), ) modified = models.DateTimeField( auto_now=True, verbose_name=_("modified"), help_text=_("Article properties last modified"), ) I know that if I delete my unique constraint on tile, I think this will work. But I need to maintain this constraint. I don't understand which get_or_create does not see that I M on editing an existing instance. thanks for helping -
django-tenants example 404 error, run through the tutorial video twice and keep getting the same error
This is from the tutorial video from Tom - I ran through it twice : http://t1.dtdemo.local:8000/ Request Method: GET Request URL: http://t1.dtdemo.local:8000/ Raised by: customers.views.TenantView http://t1.dtdemo.local:8000/admin Page not found (404) Request Method: GET Request URL: http://t1.dtdemo.local:8000/admin http://t1.dtdemo.local:8000/admin/ Page not found (404) Request Method: GET Request URL: http://t1.dtdemo.local:8000/admin/ Raised by: django.contrib.admin.sites.index Settings.py """ Django settings for dtdemo2 project. Generated by 'django-admin startproject' using Django 3.1.5. 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 # 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 = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition SHARED_APPS = [ 'django_tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'customers' ] TENANT_APPS=[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'myclientapp' ] INSTALLED_APPS=list(set(SHARED_APPS + TENANT_APPS)) MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dtdemo2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': … -
How to change message when save model in django?
When save model on browser. django will showing message "The ...... was added successfully.".I tried to change message at get_queryset() it look like too complicate. I want to know the best way how to change this message? and Where is to change? -
Django-filter field not showing after adding lookup expressions - django-filter lib
I'm trying to implement a search field for my website, I decide to use django-filter I was able to create a search field and search the records by typing the exact record name in the search field. (default it provides exact field lookup) And it worked fine. Then I decide to add more field lookup so the search experience improves. But after adding some field lookups the search form field stopped appearing in the template. I go through the documentation couple of times and also tried to google the issue but unable to solve it. Test: By the way, hard cording the field lookups(icontains) to the queryset worked. And also the query set works fine. So here's my context processor which handles the search field(search field is in the base.html) context_processor.py from django.db.models import Prefetch from django.shortcuts import render from store.filters import ProductFilter from store.models import Product, ProductImage, Wishlist def include_search_bar(request): queryset = Product.objects.order_by('name').prefetch_related( Prefetch( 'productimage_set', ProductImage.objects.filter(place='Main Product Image'), to_attr='main_image' ), ) product_filter = ProductFilter(request.GET, queryset=queryset) products = product_filter.qs context = { 'product_filter': product_filter, 'products': products, } return context filters.py import django_filters from .models import Product class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = { 'name':['icontains'] } # fields … -
Django + Jinja/css vs Django + React
I'm trying to develop a simple neat website using Django with a second page that has a python application. If you use React to cover the front end, can you avoid having to use the combination of Jinja/css? Thanks, Sad_man -
Modify login view in django crispy form
I am doing authentication using crispy forms in Django. I would like to modify labels username and password in login view, but I can't find any solution to do it (I think that I have to create my own login form, but maybe it is possible to extend it). urls.py path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] login.html {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Login {{ form|crispy}} </legend> </fieldset> <div class="form-group"> <button type="submit" class="btn btn-outline-info">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted">Don't have an account? <a class="ml-2" href="{% url 'register' %}">Register</a> </small> </div> </div> {% endblock content %} -
Page not found (404) error while searching through search page Raised by: blog.views.blogpost
i am unable to search and get 404 error same problem occur in sitemap views for creating static xml file, it does not return the url for static file and now have this problem with search as it is unable to find search .html gives this Page not found (404) error while searching through search page Raised by: blog.views.blogpost error. my Search Views myposts = Blogpost.objects.all() query = request.GET['search'] if len(query)>78: myposts = Blogpost.objects.none() else: post_title = Blogpost.objects.filter(Q(title__icontains=query)) posts_content = Blogpost.objects.filter(Q(content__icontains=query)) posts_slug = Blogpost.objects.filter(Q(slug__icontains=query)) myposts = post_title | posts_content | posts_slug if myposts.count() == 0: messages.warning(request, "No search results found. Please enter again.") context = {'myposts': myposts,'query':query} return render(request, 'blog/search.html', context) My url urlpatterns = [ path('', views.index, name='bloglist'), path('<slug:post>/', views.blogpost, name='blogpost'), path("contact/", views.contact, name="contact"), path("search/", views.search, name="search") ] My Search.html {% for post in myposts %} <div class="col-md-6"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <h3 class="mb-0"><a href="{{ post.get_absolute_url }}">{{post.title}}</a></h3> <div class="mb-1 text-muted"></div> <strong class="d-inline-block mb-2 text-primary"><a>{{post.author}} | {{post.created_on}}</a></strong> <p class="card-text mb-auto">{{post.content|safe}}</p> <a href="{{ post.get_absolute_url }}" class="stretched-link">Continue reading</a> </div> Project urls from blog.sitemaps import StaticViewsSitemap from blog.sitemaps import BlogSitemap sitemaps ={ 'blogpost': BlogSitemap(), 'static': StaticViewsSitemap(), } urlpatterns = [ … -
Django: use model_formfactory with @property model field
I have this Django model: # models.py class MyModel(models.model): _foo = models.CharField(max_length=200) foo_link = models.Charfield(max_length=250) @property def foo(self): return self._foo @foo.setter def foo(self, value): self._foo = value self.foo_link = "https://foobar.com/{}".format(value) I want foo to be a property, so that foo_link changes accordingly whenever I change it. So far, this works as expected and as described in tutorials such as this one. Except when I try to use modelform_factory with this property: # views.py from django.forms import modelform_factory def edit_foo(request, foo_id): mymodel = get_object_or_404(MyModel, pk=foo_id) FooForm = modelform_factory(MyModel, fields=("foo",)) if request.method == "POST": form = FooForm(request.POST, instance=mymodel) if form.is_valid(): form.save() else: form = FooForm(instance=mymodel) return render(request, "myapp/editfoo.html", {"form": form}) It fails with the error django.core.exceptions.FieldError: Unknown field(s) (foo) specified for MyModel. What did I do wrong here? -
MongoDB database. Error "Select a valid choice. That choice is not one of the available choices."
I have installed MongoDB in my Django project. Because is the first time I use Mongo, I decided to try how it works and I created a simple program in order to store data ( price and quantity in my case). The project is called "exchange" and it has 2 folders: exchange and app. This is the file models.py from 'app' folder: from django.db import models from djongo.models.fields import ObjectIdField, Field from django.contrib.auth.models import User class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) price = models.FloatField() quantity = models.FloatField() #ips = models.Field(default=[]) #subprofiles = models.Field(default={}) This is the file admin.py from django.contrib import admin from .models import * admin.site.register(Profile) admin.site.register(Order) This is how I set the database in the file settings.py of exchange folder DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'engine', } } So after made the migrations and create the superuser, I run the server, I went in the section Admin, than in Profile, and I created a profile choosing the only option available (my superuser). At this point I created an order in the Orders section: so I chose in the "profile" field … -
Custom fields in user model Django
I am using normal User model in Django to save my users. I would like to add first_name and last_name field, but I don't know how to extend my model and make it work. First and last name should be added in in register form (I use crispy forms). register view if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() # save user to database username = form.cleaned_data.get('username') messages.success(request, f"User {username} succesfully created! You can login now!") return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) register form def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) self.fields['password1'].label = "Hasło" self.fields['password2'].label = "Powtórz hasło" email = forms.EmailField() name = forms.CharField( label="Imię", required=True, max_length=30, ) surname = forms.CharField( label="Nazwisko", required=True, max_length=30, ) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'name', 'surname'] labels = { 'username': 'Nazwa użytkownika', } -
How to pass full data as it is without getting converted via GET?
I'm trying to manipulate my form's action via js with the following code: form.action = "{% url 'search.html' phrase='developer' %}" The problem is, it converts my data to weird signs instead of passing it as it is. http://localhost:8000/%7B%%20url%20'search.html'%20phrase='developer'%20%%7D? How can I avoid this convertion ? -
Getting Error AttributeError: type object 'Student' has no attribute 'Objects'
i am getting error AttributeError: type object 'Student' has no attribute 'Objects' when i try to run 'python manage.py makemigrations' in django Here is my models.py file #-*- coding: utf-8 -*- from django.db import models class Subject(models.Model): subject_name = models.CharField(max_length=200) chapter_title = models.CharField(max_length=200) class Student(models.Model): student_name = models.CharField(max_length=254) student_teacher = models.ManyToManyField(Subject) my Serializers.py file # -*- coding: utf-8 -*- from rest_framework import serializers from .models import Subject, Student class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = '__all__' my views.py File # -*- coding: utf-8 -*- from django.shortcuts import render from rest_framework import viewsets from .serializers import StudentSerializer, SubjectSerializer from .models import Subject, Student class StudentViewSet(viewsets.ModelViewSet): queryset = Student.Objects.all().order_by('student_name') serializer_class = StudentSerializer class SubjectViewSet(viewsets.ModelViewSet): queryset = Subject.Objects.all().order_by('subject_name') serializer_class = SubjectSerializer I have similar application but i am not getting error there. Please help