Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to navigate to a different page using Id in Django
I'm Using materialize CSS scrollspy with Django to navigate to a specific section inside a page using section id. How can I navigate that specific section when I'm on a different page. <li><a href="/">Home</a></li> <li><a href="#cat" >sample categories</a></li> <li><a href="/category">Categories</a></li> <li><a href="/gallery">Gallery</a></li> <li><a href="/about">About Me</a></li> <li><a href="/blog">Blog</a></li> <section id="cat"> <div class="container-fluid"> <div class="row"> <h3 class="center">Few Categories I do</h3> {% for category in categories|slice:":3" %} <div class="col s12 m4"> ``` -
Fetch user model data and update another model in django
I have user model using AbstractBaseUser class. I am registering user using email, username and password. User class: class User(AbstractBaseUser): """ Creates a customized database table for user """ email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] objects = UserManager() def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True I want to extend this model to another model called Employee. For extending user model to employee model I have used django signal class. Employee class: class Employee(models.Model): """ Create employee attributes """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True) e_id = models.IntegerField(unique=True, null=True, blank=True) first_name = models.CharField(max_length=128,blank=True) last_name = models.CharField(max_length=128, blank=True) address = models.CharField(max_length=256, blank=True) phone_number = models.CharField(max_length=128, blank=True) email = models.EmailField(max_length=128, unique=True) @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: … -
Django CBV with pagination from ajax request and filtering
I have a class based ListView which is called by an ajax request where I also may pass some filtering params. The template should be paginated. Every thing is working fine. The only issue I cannot switch to the second or third page. The shown content is always the same, the one from the first page. The pagination is displayed well in the template. Here my code: class SpecificationListView(AjaxRequiredMixin, ListView): model = Category context_object_name = 'categories' template_name = 'catalog/specification/listSpecificationFiltered.html' paginate_by = 2 def post(self, request, *args, **kwargs): search_value = request.POST.get('searchValue', None) sel_category = request.POST.get('selCategory', 'ALL') chk_active = request.POST.get('chkActive', 0) created_start_date = request.POST.get('dateCreatedStartDate') or '2020-01-01' created_end_date = request.POST.get('dateCreatedEndDate') or datetime.datetime.now().strftime('%Y-%m-%d') expired_start_date = request.POST.get('dateExpiredStartDate') or '2020-01-01' expired_end_date = request.POST.get('dateExpiredEndDate') or datetime.datetime.now().strftime('%Y-%m-%d') filters = Q() search_value = None if (search_value == '' or len(search_value) < 3) else search_value if search_value is not None: filters = filters & Q(specification__name__icontains=search_value) | Q(specification__description__icontains=search_value) if sel_category != 'ALL': filters = filters & Q(pk=sel_category) if chk_active == '1': filters = filters & Q(specification__expired__isnull=True) specification_filters = Q() if created_start_date != '2020-01-01' or created_end_date != datetime.datetime.now().strftime('%Y-%m-%d'): specification_filters = specification_filters & Q(created__range=[created_start_date, created_end_date]) if expired_start_date != '2020-01-01' or expired_end_date != datetime.datetime.now().strftime('%Y-%m-%d'): specification_filters = specification_filters & Q(expired__range=[expired_start_date, expired_end_date]) # categories are retrieved … -
Runtime error when deploying Django app to Heroku
I am trying to deploy my Django application to Heroku. When i try to deploy the app with, I get the following error log in Heroku: -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.7.7 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.7.5 -----> Installing pip -----> Installing dependencies with Pipenv 2018.5.18… Traceback (most recent call last): File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/elements/abstracttable.py", line 27, in _enumerate_items yield next(non_metadata), next(non_metadata) StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/pipenv/project.py", line 438, in _parse_pipfile return contoml.loads(contents) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/contoml/__init__.py", line 15, in loads elements = parse_tokens(tokens) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/__init__.py", line 17, in parse_tokens return _parse_token_stream(TokenStream(tokens)) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/__init__.py", line 29, in _parse_token_stream elements, pending = toml_file_elements(token_stream) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/parser.py", line 375, in toml_file_elements captured = capture_from(token_stream).find(one).or_find(file_entry_element).or_empty() File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/recdesc.py", line 33, in find element, pending_ts = finder(self._token_stream) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/parser.py", line 372, in one c1 = capture_from(ts1).find(file_entry_element).and_find(toml_file_elements) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/recdesc.py", line 109, in and_find return Capturer(self.pending_tokens, self.value()).find(finder) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/recdesc.py", line 33, in find element, pending_ts = finder(self._token_stream) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/parser.py", line 375, in toml_file_elements captured = capture_from(token_stream).find(one).or_find(file_entry_element).or_empty() File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/recdesc.py", line 33, in find element, pending_ts = finder(self._token_stream) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/parser.py", line 372, in one c1 = capture_from(ts1).find(file_entry_element).and_find(toml_file_elements) File "/tmp/build_42417f10e9aa3fe5c0ff0fdc5c0d7ca7/.heroku/python/lib/python3.7/site-packages/pipenv/patched/prettytoml/parser/recdesc.py", … -
django-rest-framework get_schema_view: TypeError: Object of type 'Document' is not JSON serializable
django-rest-framework package from version 3.9 now renders api schema view in yaml format by default Announcement When I try to render it in JSON format as in example https://www.django-rest-framework.org/community/3.9-announcement/#built-in-openapi-schema-support from rest_framework.renderers import JSONOpenAPIRenderer from rest_framework.schemas import get_schema_view schema_view = get_schema_view( # pylint: disable=invalid-name title="API", public=True, urlconf='api.urls', renderer_classes=[JSONOpenAPIRenderer] ) urlpatterns = [ url("^schema/", schema_view) ] I'm getting: TypeError: Object of type 'Document' is not JSON serializable Versions of packages: Django==2.2.12, djangorestframework==3.11.0, openapi-codec==1.3.2 Any help will be greatly appreciated. -
Create an entry in a Model with multiple Related Fields to User Table by POST
I have got an Item Model in which I'm trying to create an entry with a POST Request. Am too new for this to understand what's going on and make necessary changes. My Model - User field to capture from which user the request had come class Item(models.Model): title = models.CharField(max_length=140) user = models.ForeignKey(User) managed_by = models.ForeignKey( django_settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, verbose_name=_("managed by"), related_name='item_managed_by') owner = models.ForeignKey( django_settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, verbose_name=_("owner"), related_name='item_owner') created_date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(blank=True, null=True) completed = models.BooleanField() is_deleted = models.BooleanField(default=False) My Viewset class ItemViewset(viewsets.ModelViewSet): serializer_class = ItemSerializer queryset = Item.objects.all() def get_queryset(self): user = self.request.user if user is not None: queryset = Item.objects.filter(user__email = user.email) else: queryset = Item.objects.none() return queryset class index(ListView): template_name='index.html' model=Item def get_context_data(self, **kwargs): context = super(index, self).get_context_data(**kwargs) context['items'] = Item.objects.filter(user=self.req_user,completed=False,is_deleted=False)[:5] return context My Serializer class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' read_only_fields = ['user'] def create(self, validated_data): validated_data['user'] = self.context['request'].user return super(ItemSerializer, self).create(validated_data) POST request data {"title" : "Some Title", "managed_by" : "manager@gmail.com", "owner" : "owner@gmail.com", "due_date" : "2020-08-01 T13:00:00Z" "completed": false, "is_deleted" : false } With this POST am looking for creating an entry in the Item model by creating the Foreign key relations to … -
rendering dataframe of pandas in django template
I want to render dataframe of pandas with classes into django template. Please find below code. {% autoescape off %} {% surface_data.nu.to_html classes="table bg-light table-striped table-hover table-sm" %} {% endautoescape %} where surface_data.nu is the dataframe. using https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html?highlight=to_html I have other methods to that. I just wanted to check is there any efficient way to do it. -
Why doesn't my Django application on AWS EC2 doesn't read data from DB?
So I have my Django application running on AWS EC2. The application is a CRUD application, where users can freely create posts. I've just created a post, but wasn't able to see the post in my application. I've checked the admin, and made sure that the data is saved perfectly. It just doesn't show up on the page where it's supposed to be. This worked perfectly fine in the local server, before deploying. What could be the problem here? Thanks. *I'm using Postgres for the engine. -
Multiple Instances Of One Model In A Single Form
A user can have many books attached to his account. Each book a user has also has a model holding data unique to that User/Book pair: class BookData(models.Model): user = models.ForeignKey(User, related_name='user_book_data', on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) read = models.BooleanField() class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) On a User's profile page I am displaying a table of all that User's Books along with their title, author and a checkbox for 'read'. Displaying the title and author are easy as these do not need a form as the user cannot edit this data. The checkbox 'read' however does need a form as the user can mark each book as being read or not. My problem is how to get all instances of BookData with a foreignKey to user within a single form. I would usually populate forms like this form = Form(instance=request.user.userform), but obviously this wont work. I'd imagine it's something like form = StudentModuleDataForm(StudentModuleData.objects.filter(student_id=studentUserModel.student.id)) I also read about formsets, but I think these are more for when users can add extra fields to a form. Thank you. -
how I can create live notification
I have model Order class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30, null=True, ) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) how I can send live notification to shop when the new order created my views.py def CreateOrder(request, shop_id, product_id): customer = request.user.customer shop = Shop.objects.get(id=shop_id) product = Product.objects.get(id=product_id) form = OrderForm() quantity = request.POST.get('quantity') note = request.POST.get('note') if request.method == 'POST': order = Order.objects.create(customer=customer, shop=shop, product=product, quantity=quantity, note=note) return redirect('CustomerOrder') -
How to generate multiple multipart presigned post url to upload a file in boto3
I have searched this issue and found multiple solutions but nothing worked yet. Searched : https://sandyghai.github.io/AWS-S3-Multipart-Upload-Using-Presigned-Url/ https://github.com/boto/boto3/issues/2305 -
Django Rest Framework : Login
I'm trying to make a django rest API. I've already created the registration API, now, I want to create the login API. In my form, I'm sending two data : email and password. I would like to check if there is an account that matched with these two fields. I don't really know if what I am doing is the good way to do a login api. Here is my code : views.py : ... #Log in @api_view(['POST', ]) def log_in(request): if request.method == 'POST': data = {} email = request.POST.get['email'] password = request.POST.get['password'] password = hashlib.sha1(password, encode('utf-8')) account = memberArea.objects.filter(email = email, password = password) if account: data['succes'] = "Successfully connected" data['id'] = account.id data['email'] = accound.email else : data['error'] = "email and password doesn't match !" return Response(data) When I run my code, I get this error : 'method' object is not subscriptable. I think it's because email and password are not QuerySet. If it's the method to login an user, how can I turn email and password into QuerySet ? If there is another way which is commonly used to make login api, what is it? Thanks by advance for your help. -
Django filtering large dataset taking too long
I know there have been a lot of questions regarding this subject, but I couldn't find any of my case. My problem is rather simple. In my influencer app, I have Note model which contains about 30 fields: class Note(models.Model): desc = models.TextField() likeCount = models.PositiveIntegerField() commentCount = models.PositiveIntegerField() ... tags = models.ManyToManyField(Tag) postTs = models.DateTimeField(null=True) And there is more than 1 million Notes in my PostgreSQL database hosted by AWS RDS. Now when I execute the following code: notes = ( Note.objects.filter(desc__icontains='some word') .values("likeCount", "collectCount", "shareCount", "commentCount", "postTs")[:10] ) print(len(notes)) # Output: 10 it takes around 7 seconds. The resulting SQL query is: SELECT "influencer_note"."likeCount", "influencer_note"."collectCount", "influencer_note"."shareCount", "influencer_note"."commentCount", "influencer_note"."postTs" FROM "influencer_note" WHERE UPPER("influencer_note"."desc"::text) LIKE UPPER('%some word%') LIMIT 10 I think I have done pretty much everything to optimize the query (such as selecting the only necessary fields and limiting the number of data -- 10 is obviously a small number), but it's still taking abnormal amount of time. What are the possible causes for this problem and how can I further optimize this? Ultimately, I need to make a chart with the filtered queryset, which is why I need a solution other than pagination or LIMIT. Thank you in … -
cant use Case When without having values : can't set attribute django
i tried to do some calculate and make a condition during calculate process MyModel.objects.filter(active=True).annotate( paid_price=( F('models__price') * F('models__order')), storage_price((F('models__model__B_Price')+F('models__model__cost'))*F('models__order')) ).annotate(income=Case(When(paid_price__gte=F('storage_price') , then=F('paid_price') - F('storage_price')),default=0,output_field=IntegerField())) but it raise this error can't set attribute but while i try to use values it works fine , but at this query i dont need values in my query and the problem within this line annotate(income=Case(When(paid_price__gte=F('storage_price') , then=F('paid_price') - F('storage_price')),default=0,output_field=IntegerField()) why i cant use Case(When()) without using values thanks for helping -
How to get the path of files uploded through django forms and saved in media folder?
I am taking a file from django form and saving it in media folder.Then i want to copy its content and write into another file, but i am not able to get the path that i had uploaded and saved in media folder . File is actually getting saved in media folder but then i am not be able to access it , i guess their is some problem with the path that i am using to read. views.py def result(request): import os if request.method == 'POST': uploaded_file=request.FILES['upfile'] fs= FileSystemStorage() modulename=fs.save(uploaded_file.name,uploaded_file) url=fs.url(modulename) print(url) with open(url) as f: prog=f.readlines() with open('E:\\Main Project\\appProject\\otherfile.py','w') as f1: f1.writelines(prog) Any resource or reference will be helpful. Thanks in Advance -
Django Rest Serializer with double foreign keys
Hey I'm rather new to the whole REST framework. I'm doing a project where I want to get all the users and their projects they are currently working on. However I'm not quite sure how I would go about linking the serializer together for the JSON output. Right now my 3 models look like this class User(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField() def __str__(self): return str(self.first_name) class ProjectUser(models.Model): project = models.ForeignKey("Project", on_delete=models.CASCADE) user = models.ForeignKey("User", on_delete=models.CASCADE) is_lead = models.BooleanField(default=False) class Meta: unique_together = (("project", "user"),) def __str__(self): return str(self.id) class Project(models.Model): name = models.CharField(max_length=255) client = models.Charfield(max_length=255) def __str__(self): return str(self.name) I think a custom serializer would be best for this, but I'm lost as to how to query the data to it. -
nothing is displayed on the page with all products in Django
There is a model with three classes of category-subcategory-products class Category(models.Model): name_category = models.CharField(verbose_name = 'name cat', max_length = 100, null=True) image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic') slug = models.SlugField(max_length=160, unique=True, null=True) def __str__(self): return self.name_category class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='категория', related_name='sub') name_subcategory = models.CharField(verbose_name = 'name subcat', max_length = 100, null=True) image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic') slug = models.SlugField(max_length=160, unique=True, null=True) def __str__(self): return self.name_subcategory class Product(models.Model): subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, verbose_name='категория',related_name='prod') name_product = models.CharField(verbose_name = 'name product', max_length = 100, null=True) image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='pic') price = models.IntegerField('price') def __str__(self): return self.name_product views.py class CategoryView(ListView): """all category""" model = Category class CategoryDetailView(DetailView): """all sub category""" model = Category class SubcategoryView(ListView): """all product""" model = Subcategory url.py urlpatterns = [ path("", views.CategoryView.as_view()), path('<slug:slug>/', views.CategoryDetailView.as_view(), name='category_detail'), path('<slug:slug>/<slug:slug_sub>/', views.SubcategoryView.as_view(), name='subcategory_list'), ] page template from which I go to the page with all products (category_detail.html) {% extends 'base.html' %} {% block content %} <h2>{{ category.name_category }}</h2> {% for sub in category.sub.all %} <a href="{% url 'subcategory_list' slug=category.slug slug_sub=sub.slug %}"> {{sub.name_subcategory}}</a> <img src="{{sub.image.url}}" width="100px" height="100px"> {% endfor %} {% endblock %} page template (subcategory_list.html) with all products (here I did not write the output of the products because … -
Styling `django-social-widgets` buttons
I included the following two buttons to share the content in twitter and facebook respectively. {% social_widget_render "twitter/share_button.html" href=request.build_absolute_uri %} {% social_widget_render "facebook/share_button.html" href=request.build_absolute_uri data-layout="button_count" %} and it looks like: I inspect it and could only fix the margin and positioning but couldn't fix the background color, removing the social icons adding my own custom texts. #twitter-widget-0 { margin-top: 10px !important; } .fb_iframe_widget { span { vertical-align: middle !important; margin-top: -0.5rem; } } How to add or remove custom icons of it. Further, add custom texts like instead of share text for facebook share, I can replace it with share on facebook, or style the button to look like this: Thanks in advance -
Unable to export images from django model to excel sheet using XLWT
I am creating an api to export images in model to the excel sheet using XLWT.But image is not showing in excel sheet.only showing path of the media.I do not know what ia am doing wronng.Help would be appreciated. models.py class Task(models.Model): Id=models.IntegerField() Name=models.CharField(max_length=50,null=False,blank=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) Image2=models.FileField(blank=True, default="", upload_to="media/images",null=True) Date=models.DateField(null=True,blank=True) def __str__(self): return str(self.Name) views.py def list(self, request): try: response=HttpResponse(content_type='application/ms-excel') response['Content-Disposition']='attachment; filename="users.xls"' wb=xlwt.Workbook(encoding='utf-8') ws=wb.add_sheet('Tasks', cell_overwrite_ok=True) row_num=0 font_style=xlwt.XFStyle() font_style.font.bold=True columns=['Id','Name','Image1','Image2','Date'] for col_num in range(len(columns)): ws.write(row_num,col_num,columns[col_num],font_style) font_style=xlwt.XFStyle() data=Task.objects.all()#.values_list('Id','Name','Image1','Image2','Date') date_format = xlwt.XFStyle() date_format.num_format_str = 'yyyy/mm/dd' for my_row in data: row_num+=1 ws.write(row_num,0,my_row.Id,font_style) ws.write(row_num,1,my_row.Name,font_style) #ws.write(row_num,2,my_row.Image1.url,font_style) ws.write(row_num,2,my_row.Image1.url,font_style) print(my_row.Image1.url) #ws.insert_bitmap(row_num,2,my_row.Image1.url,font_style) ws.write(row_num,3,my_row.Image2.url,font_style) #ws.insert_bitmap(row_num,3,my_row.Image2.url,font_style) ws.write(row_num,4,str(my_row.Date),font_style) wb.save(response) print(my_row.Date) return response except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
Confusion with templates in django
I was learning django and I have the following template: {% load static ax_base %} {% for tm in team_list %} <div> <div class="card our-team-slider-card mb-3"> <div class="row no-gutters"> <div class="col-sm-4"> <a href="" class="card-img-wrap" data-toggle="modal" data-target=".our-team-photo"> <img src="{% static tm.img %}" class="card-img" alt="..."> </a> </div> <div class="col-sm-8"> <div class="card-body"> <h5 class="card-title mb-4">{{ tm.name }}</h5> <div class="profession mb-4 fz14 opa05">{{ tm.position }}</div> <p class="card-text fz14 opa05">{{ tm.bio }}</p> <div class="contacts mb-2"> <a href="" class="styled-link text-black">{{ tm.phone }}</a><span> , </span><a href="" class="styled-link text-black">{{ tm.email }}</a> </div> <a href="" class="styled-link text-primary">Send message</a> </div> </div> </div> </div> </div> {% endfor %} So, the problem is I have two places where the above template is reused but what I want to do is to use col-sm-4 class in one place but not use col-sm-4 in the other place. Should I create two separate templates for that, that is, one template that uses col-sm-4 and the other template that does not use col-sm-4? Would that be correct? -
Filter object with tag in HTML Template django
My address model has a boolean filed value named active. Hence a user can have many addresses but one address i active. I want my html to only render the active address of the user. Is this possiable when using Inline formset? Model: class Address(models.Model): CustomUser = models.ForeignKey(CustomUser, on_delete=models.CASCADE) address = models.CharField(max_length=60, blank=False) zip_code = models.CharField(max_length=8, blank=False) city = models.CharField(max_length=30, blank=False) state = models.CharField(max_length=30, blank=False) active = models.BooleanField(name='active', default=True, editable=True) address_reg_date = models.DateTimeField(default=timezone.now) This is my view def ContactIndex(request, CustomUser_id): customuser = CustomUser.objects.get(pk=CustomUser_id) if request.method == "POST": ContactFormset = ContactInlineFormSet(request.POST, request.FILES, instance=customuser) AddressFormset = AddressInlineFormSet(request.POST, request.FILES, instance=customuser) if ContactFormset.is_valid() or AddressFormset.is_valid(): AddressFormset.save() ContactFormset.save() # Do something. Should generally end with a redirect. For example: return redirect ('ContactIndex', CustomUser_id=customuser.id) else: ContactFormset = ContactInlineFormSet(instance=customuser) AddressFormset = AddressInlineFormSet(instance=customuser) return render(request, 'members/member_contact_form.html', {'ContactFormset':ContactFormset, 'AddressFormset':AddressFormset, 'customuser':customuser, 'Address':Address }) This is the form class CollectionAddress(forms.ModelForm): class Meta: model = Address exclude = () AddressInlineFormSet = inlineformset_factory( CustomUser, Address, form=CollectionAddress, fields=['address', 'zip_code', 'city', 'state', 'active'], extra=1, max_num=1, can_delete=False ) -
i am trying to connect reactjs axios with django rest framework to make the post request. but i am getting POST 400 (Bad Request)
here is axios code: axios({ method: 'post', url: 'http://127.0.0.1:8000/api/form/', data: this.state, headers: { 'Content-Type': 'application/json'} }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); } here is views.py class Formview(APIView): def post(self,request): Fprov=request.POST.get('selectedPro') Fdist=request.POST.get('selectedDistrict') FpalikaT=request.POST.get('selectedPalikaType') FpalikaN=request.POST.get('enteredPalikaName') FWardN=request.POST.get('enteredWardNo') FWardOf=request.POST.get('enteredWardOfficeAddress') FWardC=request.POST.get('enteredWardContactNo') new=Form(Province=Fprov, District=Fdist, PalikaType=FpalikaT, PalikaName=FpalikaN, Ward_No=FWardN, Ward_Office_Address=FWardOf, Ward_Contact_No=FWardC) new.save() here is serializers.py from rest_framework import serializers from .models import Form class FormSerializer(serializers.ModelSerializer): class Meta: model = Form fields = 'all' -
How to add email confirmation in Django Signup View for forgotten password?
I am building a Django app and I am using the default PasswordChangeView for getting the confirmation email. But the problem is that it is only showing it in the terminal but I want to send it over an email. How do I do it? My Registration View class StudentRegistrationView(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/signup_form.html' success_url = reverse_lazy('student_course_list') def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): # result = super(StudentRegistrationView, self).form_valid(form) # cd = form.cleaned_data # user = authenticate(username=cd['username'], password=cd['password1']) user = form.save() Profile.objects.create(user=user) login(self.request, user, backend= 'students.authentication.EmailAuthBackend') return redirect('course_list') for the login view, I am using LoginView. How can I send the reset credentials over an email? -
FieldError: 'created' cannot be specified for Post model form as it is a non-editable field
Django 3.0.8 admin.py class PostAdmin(admin.ModelAdmin): list_display = ("id", "title", 'category',) def get_fields(self, request, obj=None): fields = [a_field.name for a_field in self.model._meta.fields] return fields def get_readonly_fields(self, request, obj): readonly_fields = self.readonly_fields if obj: if obj.already_published and (not request.user.has_perm('posts.change_already_puclished')): readonly_fields = READONLY_FIELDS_AFTER_PUBLISHING return readonly_fields traceback Exception Type: FieldError Exception Value: 'created' cannot be specified for Post model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class PostAdmin. Local vars Variable Value change False defaults {'exclude': None, 'fields': ['id', 'comment', 'title', 'slug', 'description', 'body', 'draft', 'already_published', 'featured_image', 'category', 'excerpt', 'h1', 'author', 'created', 'updated', 'sidebar', 'keywords', 'lsi', 'google_indexed', 'google_first_indexed', 'yandex_indexed', 'yandex_first_indexed'], 'form': <class 'django.forms.widgets.ModelForm'>, 'formfield_callback': functools.partial(<bound method BaseModelAdmin.formfield_for_dbfield of <posts.admin.PostAdmin object at 0x7f1d596e3820>>, request=<WSGIRequest: GET '/admin/posts/post/add/'>)} exclude None excluded None fields ['id', 'comment', 'title', 'slug', 'description', 'body', 'draft', 'already_published', 'featured_image', 'category', 'excerpt', 'h1', 'author', 'created', 'updated', 'sidebar', 'keywords', 'lsi', 'google_indexed', 'google_first_indexed', 'yandex_indexed', 'yandex_first_indexed'] form <class 'django.forms.widgets.ModelForm'> kwargs {} new_attrs {'declared_fields': {}} obj None readonly_fields () request <WSGIRequest: GET '/admin/posts/post/add/'> self <posts.admin.PostAdmin object at 0x7f1d596e3820> The same as image: I try this code both with a superuser and a user who don't have change_already_puclished permission. Superuser: when trying to add or change a post, the error appear. Ordinary user: adding posts is … -
How do I integrate facebook post to page api on my website?
I am stuck trying to integrate Facebook API to share content on my page for about a week now. I've gone through the Facebook developer documents and I seem to not get anywhere. Can someone guide me step by step how I can integrate the graph API to share videos and photos on my Facebook page through my website?