Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show list of image URLs using django rest framework?
I am trying to create a django API where I can upload images against a unique username (without any authentication), and then the API can be fed the username to list all the IMAGES uploaded for that username. I am using the \media\ folder to store the images. My project structure . βββ backend β βββ backend β β βββ __init__.py β β βββ __pycache__ β β βββ asgi.py β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β βββ db.sqlite3 β βββ imgapi β β βββ __init__.py β β βββ __pycache__ β β βββ admin.py β β βββ apps.py β β βββ migrations β β βββ models.py β β βββ serializers.py β β βββ tests.py β β βββ urls.py β β βββ views.py β βββ manage.py β βββ media βββ venv imgapi/models.py class File(models.Model): file = models.FileField(blank=False, null=False) name = models.CharField(max_length=20, default='user') imgapi/serializers.py class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ['file','name'] imgapi/views.py class FileUploadView(APIView): parser_class = (FileUploadParser, MultiPartParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) So far with this, I can upload an image along with a username. And it gives me a β¦ -
remembered() got an unexpected keyword argument 'pk'
I am trying to increment a value through a button click. But I get the error remembered() got an unexpected keyword argument 'pk' Which I don't understand, because as far as I can see the function remembered() needs both the PK's I send it. Urls path('mypage/<int:pk>/', DeckDetailView.as_view(),name='mypage-study-deck'), path('mypage/<int:pk>/<int:card_id>', views.remembered, name='remembered') Views class DeckDetailView(LoginRequiredMixin, DetailView): model = Deck def get_context_data(self, *args, **kwargs): deck = self.get_object() deck_title = deck.title context = super(DeckDetailView, self).get_context_data(*args, **kwargs) context['cards'] = Card.objects.filter( decks__title=deck_title).filter(days_till_study=1) return context def remembered(request, card_id, deck_id): if request.method == 'POST': deck = get_object_or_404(Deck, pk=deck_id) card = get_object_or_404(Card, pk=card_id) card.days_till_study = card.days_till_study * 2 card.save() return redirect('/mypage/' + str(deck.id)) Template {% for card in cards reversed %} <div class="my-column col-xl-4 mt-2 "> <div class="card"> <div class="card-body"> <h5 class="card-title"> {{card.question}} </h5> <p class="card-text"> </p> <a href="{% url 'mypage-study-deck' deck.id %}"> <!-- Here we add the collapse functionality for the button --> <p> <a class="btn btn-success" data-toggle="collapse" href="#{{card.id}}" role="button" aria-expanded="false" aria-controls="{{card.id}}"> See Answer </a> </p> <div class="collapse" id="{{card.id}}"> <div class="card card-body"> <p> {{card.answer}} </p> <a href="javascript:{document.getElementById('remembered').submit()}"> <div class="btn btn-success"> Remembered </div> <!-- Days to study should be incremented - I need to get some post up in here?--> </div> </div> </div> </div> </div> <form id="remembered" method="POST" action="{% β¦ -
How to delete that particular row in the html table in which each row in that html table contains delete button with backend as django
Hello Everyone, I hope all are fine and safe. I am displaying the contents from the Database and displaying it in the form of html table with each row contains a delete button. Now my question is on, how to delete that particular row if i click the delete button of that row using django. I added the delete button and tried seeing many other posts on stack overflow regarding this question. But i dont see any related to my question. Please help me with the solution and let me know if you need any more details #view-entry.html <tbody> {% for item in list_values %} <tr> <td>{{item.entry_type}}</td> <td>{{item.amount}}</td> <td>{{item.details}}</td> <td>{{item.capture_date}}</td> <td> <button id="btn-delete" type ="submit" class="btn btn-danger">Delete </button></td> </tr> {% endfor %} </tbody> #views.py def view_entry(request): list_values=IncomeExpense.objects.all().filter(username=request.user) #context={'list_values':list_values} return render(request, "view-entry.html", {'name':username, 'list_values': list_values}) -
DRF Serializer doesn't raise error in update but doesn't update
I have a model with a foreign key I'm trying to update via the serializer, I don't want to use the built-in ID field to find the foreign key. My Serializer code seems to be working fine, no error is being raised but it doesn't update the foreign key field. Models: class Group(models.Model): group_id = models.CharField(max_length=100) name = models.CharField(max_length=255) farm = models.ForeignKey(to=Farm, on_delete=models.CASCADE, related_name=RelatedNames.GROUPS, default=None, null=True, blank=True, ) milking = models.BooleanField(help_text=GroupHelpTexts.MILKING) sub_groups = models.ForeignKey('self', on_delete=models.PROTECT, related_name=RelatedNames.SUBGROUPS, null=True, blank=True, ) def __str__(self): return f'{self.name}' class Cow(models.Model): management_id = models.CharField(max_length=255) eid_number = models.CharField(max_length=255, primary_key=True, blank=False, ) group = models.ForeignKey(Group, on_delete=models.PROTECT, default=None, null=True, blank=True, related_name=RelatedNames.COWS) My serializer: class CowManagementSerializer(serializers.ModelSerializer): group = serializers.SlugRelatedField(slug_field='group_id', queryset=Group.objects.all()) class Meta: model = Cow fields = ['management_id', 'eid_number', 'group'] def validate(self, attrs): if attrs['group']: try: name = attrs['group'] user = self.context['request'].user group = Group.objects.get(name=name, farm__user=user) attrs['group'] == group return attrs except Group.DoesNotExist: raise serializers.ValidationError("Group Not Found") return attrs def update(self, instance, validated_data): group = validated_data.pop('group') instance.group = group instance.save() return instance If I remove the slug related field I get this error: { "group": [ "Incorrect type. Expected pk value, received str." ] } with it, I get a 200 status code but no update is being made. -
Adding more than one model using Django ModelFormMixin in views.py
I have a Django related problem. I have two models; Model A & Model B. Model B is related to Model A trough a foreign key. In my views.py I have a CBV for a Single instance of Model A using generic.DetailView & generic.ModelFormMixin. I'm now wondering if there is a way to pass in more than one instance of a model in this view. At this point, I'm only able to pass in the Model A (which enables me to change values of the model in the DetailView). The idea would be something like this (this is ofc not working): #views.py class SingleModelA(generic.DetailView, ModelFormMixin): model = ModelA, ModelB I assume this would probably also require some changes in the post() method as well, which at the moment looks like this: def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: raise ValueError(f"INVALID FORM: {form}") I am able trough get_context_data() to present the ModelB instances belonging to this instance of ModelA, but I would like to access the ModelB instance's form in order to update ModelB straight from ModelA's DetailView. Any help is much appreciated! -
How to dynamically change a form in django based on user input (before submission)
I'm doing a web page that contains a form that must be changed dynamically based on the previous user inputs (before it's submitted). For example, if a name ends up with the string S.L, it needs to automatically span the rest of the fields to introduce the company data, if not it must submit the form with the default values or with any value at all. The form inherits from a model and everything is rendered as a crispy form. In the views.py I have: @login_required def form_home(request): if request.method == 'POST': Inputs = InputsForm(request.POST) if Inputs.is_valid(): inp = Inputs.save(commit=False) inp.author = request.user inp.email = request.user.email data = {'email': request.user.email, **Inputs.cleaned_data} obtain_calculate_create_send(data) inp.save() messages.success(request, f'Your form is valid!') return redirect('result/' + str(inp.pk) + '/') else: messages.warning(request, f'Please, check the inputs and enter valid ones') content = {'Inputs': Inputs, 'title': 'valuations'} else: Inputs = InputsForm(request.POST or None) content = {'Inputs': Inputs, 'title': 'valuations'} return render(request, 'valuations/form_home.html', content) In forms.py: class InputsForm(forms.ModelForm): # Basic Info country_choices = import_lists('Countries', equal=True) years = import_lists('years') name = forms.CharField(label='Company Name', initial='Example. S.L') country = forms.TypedChoiceField(choices=country_choices, label='Country') foundation_year = forms.TypedChoiceField(coerce=int, choices=years, label='Foundation year') employees = forms.IntegerField(label='Number of employees') industry = forms.TypedChoiceField(choices=industry_choices, label='Industry') class Meta: model = Inputs β¦ -
Django Filter: "Sort By" Feature
I want to sort the products based on boolean field "is_featured", date creation, and price. My goal: This is what i want to achieve. Images shows a website that I am taking ideas from. I currently have a checkbox filter (implemented through django-filter) for users to filter based on brand and category. You can see my "draft" here https://ecommercelsm.herokuapp.com/product/ I want to add a sort_by dropdown menu like the one in the attached image so that users can sort the orders of the products by featured, price or date creation after filtering or without. I do not know how to go about this. Can someone help? I feel like i need to add more fields to my ProductFilter. models.py class Product(MPTTModel): bool_choices = ( (True, 'Yes'), (False, 'No'), ) parent = TreeForeignKey('self', blank = True, null = True, related_name = 'children', on_delete=models.CASCADE) name = models.CharField(max_length=50) slug = models.SlugField(unique=True, null=False) category = TreeManyToManyField(Category, blank = True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="product") price = models.DecimalField(max_digits=9, decimal_places=2) image = models.ImageField(blank = True, upload_to = 'images/') is_featured = models.BooleanField(choices=bool_choices) created_at = models.DateTimeField(auto_now_add = True) class Meta: db_table = 'product' class MPTTMeta: order_insertion_by = ['name'] class Brand(models.Model): name = models.CharField(max_length=30) class Category(MPTTModel): bool_choices = ( β¦ -
Why does I am getting the following error[2020/08/16 12:10:47] HTTP GET /ws/ 503 [61.62, 127.0.0.1:41300]
[2020/08/16 12:10:47] HTTP GET /ws/ 503 [61.62, 127.0.0.1:41300] I'm using websockets for realtime data and when I run my server i get 503 error. -
How to load image in background of jumbotron in my django project?
I have been stuck in this for quite a while now. I am doing a project in Django in which I need to put an image in the background in the jumbotron. home.html {% extends 'blog/base.html' %} {% load static %} {% block content %} <header> <style> .jumbotron { background-image: url('{{STATIC_URL}}blog/home-bg.jpg'); background-size: cover; } </style> </header> <!-- JUMBOTRON --> <div class="jumbotron text-center"> <div class="container"> <h1>Welcome To CodeBlog</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor</p> <a href="{% url 'blog-about' %}" class="btn btn-primary">Read More</a> </div> </div> //some more lines of code {% endblock %} home-bg.jpg is present in the static/blog/home-bg.jpg settings.py STATIC_URL = '/static/' But still, I am not getting what is expected. I am using Bootstrap4 and Django 2.2 -
my pdf download results, not showing an image, django
i have a problem, when i download the pdf, my image is not come out this is my html <img src="https://www.qries.com/images/banner_logo.png" height="120cm" width="121cm"> and this is my views.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = io.BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) def myview(request): #Retrieve data or whatever you need postingan_list = Pengajuan_SKTM.objects.filter() return render_to_pdf( 'pengurusan/surat.html', { 'pagesize':'A4', 'postingan_list' : postingan_list, }) -
Send json data with window.location.href
I try to write a function login to change page when user input user, password and touch login button. After fetch, I get the json file {user:'user', password:'password', status:'1'}. If status==1, then go to the home page, but in my case, I cannot get the json file in home page. Is it possible to send data with window.location.href? <script> function login(){ data = { user : document.getElementById('user').value, password : document.getElementById('password').value } package = { method: 'POST', body: JSON.stringify(data) } fetch("/account/do/login/", package) .then(function(response){ json = response.json() return(json) }) .then(function(json){ if(json.status==0){ window.location.href = "/account/login/" } if(json.status==1){ window.location.href = "/account/home/" } }) } </script> -
Why django listview couldn't get url parameter
I'm trying to implement a feature that shows events registered for the day by sending the year-month-day to url. But go to [http://127.0.0.1:8000/calendar/2020-08-16/] Reverse for 'calendar' with objects '(') not found. ['calendar/(?)P\d{4}-\d{2}-\d{2})/$'] error shows. I keep getting this kind of error. What's wrong with the listview? I need your help. urls.py url(r'^(?P<date>\d{4}-\d{2}-\d{2})/$', views.CalendarView.as_view(), name='calendar'), path('event/new/',views.event, name='event_new'), path('event/edit/<int:event_id>',views.event_edit, name='event_edit'), views.py class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' context_object_name = 'today_list' def get_queryset(self, **kwargs): queryset = { 'today_list_items': Event.objects.all().filter(profile=self.request.user.user_profile).filter(start_time__date=self.kwargs['date']), 'today_list_rating_sum': Event.objects.all().filter(profile=self.request.user.user_profile).filter(start_time__date=self.kwargs['date']).aggregate(Sum('rating')).values(), } return queryset def get_context_data(self, **kwargs): if self.request.user.user_profile is None: return render(self.request, 'cal/calendar.html', {'error': 'νλ‘νμ μμ±ν΄μ£ΌμΈμ'}) context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(self.request.user, withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) context['date'] = self.date day = get_specifiec_date(self.request.GET.get('day', None)) context['prev_day'] = prev_day(day) return context -
How to install TailwindCSS to a Django project?
How to install Tailwind css in a Django project? I didn't succeed by using the installation tutorial in official TailwindCSS website. After some research I found answer to my problem. -
Getting a input value in django view after inserting html by AJAX
In my html, i insert a code by ajax request like: if (document.getElementById("div3").className == "active"){ for (var [name, value] of Object.entries(institutionsByName)){ document.getElementById("institution-checkbox").innerHTML += '<label name="organization_label">' + '<input type="checkbox" name="organization" value="' + value + '" id="institution-key"/>' + '<span class="checkbox radio"></span>' + '<span class="description">' + '<div class="title">'+ name + '</div>' + '<div class="subtitle">' + '</div>' + '</span>' + '</label>' } } Then i try to get a 'organization' value by django view like: institutions1 = request.POST.get('institution-key') However it returns None, How can i get the id of my institution/organization in a correct way in my django view? In html code, one of them looks like: <input type="checkbox" name="organization" value="9" id="institution-key"> -
React frontend + graphene Django backend SPA deployment
I want to deploy a SPA on only one VM, with debian 10. What I wanted to do is all routes to go to index.html of my static react app, except /admin/* and /graphql/* which should lead to the corresponding django pages. I have tried using Caddy, setting up a reverse proxy for /admin/* and /graphql/* but I end up with a working frontend and a working admin page (but the style of this page is not loaded for some reason). However, the graphql page does not work at all (blank page) and the frontend cannot make request to the backend. Do you know how I should do it? I was wondering if I'd rather go with nginx and uWSGI instead of using Caddy, with which I had to use gunicorn, but then I would need help to configure nginx properly. Or maybe the way I wanted to do it is a dead-end and I should totally change it? Thanks for your help! -
Django new version 3.1, the settings file have some changes
On Django new version 3.1, the settings file have some changes, and I came to ask how I have to proceed to set my static files? The way that I usually did doesn't work more. Last versions: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Version 3.1: from pathlib import Path BASE_DIR = Path(__file__).resolve(strict=True).parent.parent I usually set my static files like this: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') If I insert the import os will work, but is it the right practice? What is the best practice to set this? Thank you? -
Visibility problem for static files -- django
I connected static files in django, but they won't connect, can you help? settings: STATICFILES_DIRS = [ "web_page/static", ] STATIC_URL = '/static/' STATIC_ROOT = '/static/' index.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static "css/standart_template.css" %}" rel="stylesheet" type="text/css" > <title>HouseVOP</title> </head> urls - projects: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('web_page.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urls - app: from django.urls import path from .views import FormListView, Success from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', FormListView, name = 'home'), path('success/', Success, name = 'success') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Before turning here, I searched many sites, so now I may simply not see something. In the first version of the code, I laid the path to the static files along with os.path.join (BASE_DIR, etc., but it did not work ... -
How to return to the same point after performing a function in django
I am making a social media app using django. I added a like function to the posts but in my code, when the user clicks the like button, it reloads the page and the user is back to the top of the page. I want that after clicking the like button, user returns to the same post on the page. how do i do that?? please help. Thanku. This is my views.py def likepost(request, post_id): user = request.user post_connected = post.objects.get(id=post_id) mypost = like_post.objects.filter(user=user, liked=post_connected) if mypost.exists(): mypost.delete() post_connected.likes -= 1 post_connected.save() else: mylike = like_post.objects.create(user=user, liked=post_connected) mylike.save() post_connected.likes += 1 post_connected.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) This is my template view <form action="/like/{{posts.id}}/" method="POST"> {% csrf_token %} <button style="background-color: inherit; border:none; outline:none; margin-left:-10px; width:4%;"> {% if posts in myliked %} <span style="font-size:17px;"> <i class="fa fa-heart" aria-hidden="true" style="color: red;"></i> </span> {% else %} <span style="font-size:17px;"> <i class="fa fa-heart" aria-hidden="true" style="color: lightgrey;"></i> </span> {% endif %} </button> {{posts.likes}} </form> This is my urls.py path('like/<int:post_id>/', views.likepost, name='like'), -
how to get random 1/2 data from database in jinj2 template in Django?
<table> {% for field in fields %} <tr> <td>{{ field.name }}</td> <td>{{ field.value }}</td> </tr> {% endfor %} </table> here we will get all the data from fields . but i want to only get randomly 1/2 (i can specified how many) data in jinja2 template from backend ? How to do this ? -
Django: AttributeError: <Model> object has no attribute '_meta'
NOTE:- I have referred to SO links & other tutorials but I am unable to get past this error. Django version:django-3.1 Context:- I have a product which will can have multiple images attached to it against p_id(PK). TODO:- Use django-admin to upload multiple images against a product code Error:AttributeError: 'PhotoInline' object has no attribute '_meta' models.py from django.db import models from django.urls import reverse from django.utils import timezone # Create your models here. class Product(models.Model): """ 1. **product** | Column-Name | Type | | ------------ | ---------- | | p_id | NUMERIC-AI | | product_name | VARCHAR | | COST | NUMERIC | """ p_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=250) cost = models.FloatField(default=0) created_on = models.DateField(default=timezone.now) def get_absolute_url(self): return reverse('product:index') def __str__(self): return self.product_name class Meta: db_table = 'product' verbose_name = 'Product List' def img_upload_location(p_id, filename): p_id = f"{p_id.p_id_id}".replace(" ", "-") file_name = filename.lower().replace(" ", "-") return f"pimages/{p_id}/{file_name}" class Pimage(models.Model): """ | Column-Name | Type | | ----------- | ------- | | p_id(FK) | NUMERIC | | img | VARCHAR | """ p_id = models.ForeignKey(Product, on_delete=models.CASCADE) # img = models.ImageField(upload_to='images/') img = models.ImageField(upload_to=img_upload_location) def get_absolute_url(self): return reverse('pimage:index') # def __str__(self): # # return Product.objects.get(p_id=f'{self.p_id}').product_name # return f'{self.p_id}' def __unicode__(self): return β¦ -
Body not Posting in Django Rest API call using Javascript fetch
I am using Django RestFramework API in my Node.js App. I am using Javascript fetch API to send some data to backend of my Project which is configured in Django. But the data is not getting posted. It runs fine in PostMan but not using fetch. my API class is as follows: class ProfileList(APIView): def get(self, request): ProfileObjects = Profile.objects.all() serializer = ProfileSerializer(ProfileObjects, many=True) return Response(serializer.data) def post(self, request, **kwargs): print(request.POST) print(self.request.POST) ProfileObjects = Profile.objects.all() serializer = ProfileSerializer(ProfileObjects, many=True) return Response(serializer.data) The fetch call looks like this..: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); fetch('http://127.0.0.1:8000/API/', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Authorization': csrftoken }, body: JSON.stringify({data: "your data"}) }).then(res => res.json()) .then(res => console.log(res)); Well according to the API class view it should print {data: "your data"} but it isn't. Instead this is being printed out while using fetch call <QueryDict: {}> <QueryDict: {}> β¦ -
keyerror in Django REST Framework Serializer.save() and validated_data
I'm new on Django Rest Framework and when I want to POST data and I get this error KeyError at author=self.validated_data['author'], KeyError: 'author' Here's my code: in my models.py class Question(models.Model): #author author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #question question=answer=models.TextField(default='Write your question') #answer answer=models.TextField(default='write your answer') #paragraph paragraph=models.ForeignKey(Paragraph,on_delete=models.CASCADE) #date published_date = models.DateTimeField(verbose_name='published_date', auto_now_add=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return "{} - {} - {} - {}".format(self.author, self.question, self.answer,self.paragraph) and my views.py def question_view(request): if request.method == 'POST': serializer = ParagraphSerializer(data=request.data) data = {} if serializer.is_valid(): post = serializer.save() data['author'] = post.author data['question'] = post.question data['answer'] = post.answer data['paragraph'] = post.paragraph else: data = serializer.errors return Response(data) and at the end my Serializers.py class ParagraphSerializer(serializers.ModelSerializer): paragraph=serializers.SlugRelatedField( many=True, read_only=True, slug_field='title' ) author=serializers.SlugRelatedField( slug_field=Account.email, required=False, read_only=True ) class Meta: model = Question fields = ['author','question', 'answer','paragraph'] def save(self): post=Question( author=self.validated_data['author'], question=self.validated_data['question'], answer=self.validated_data['answer'], paragraph=self.validated_data['paragraph']) post.save() return post -
django multiple model and formset ina single view only saves last value for the formset
all the required files i am getting issue with the formset section it only saves the last row's value and keeps the rest data blank i am not able to solve this issue it would be great if any one can help me out with this code model.py from django.db import models class Rfq(models.Model): rfq = models.IntegerField() def __int__(self): return self.rfq class General(models.Model): #General Information supplier_name = models.CharField(max_length=300) suppler_manufacturing_location =models.CharField(max_length=300, blank=True, default='') rfq_tracking = models.CharField(max_length=300, blank=True, default='') supplier_dunns =models.CharField(max_length=300, blank=True, default='') rfq = models.ForeignKey(Rfq, null=True, on_delete=models.CASCADE) def __str__(self): return self.supplier_name class Material(models.Model): #Material material_description = models.CharField(max_length=300) gross_material_weight = models.CharField(max_length=300, blank=True, default='') blank_size = models.CharField(max_length=300, blank=True, default='') rfq = models.ForeignKey(Rfq,related_name = "materials", null=True, on_delete=models.CASCADE) def __int__(self): return self.rfq class Meta: db_table = "materials" class Purchased(models.Model): #Purchased Components & Outside Processing material_item_process_description= models.CharField(max_length=300) quantity_per_assembly = models.FloatField() unit_of_measure = models.CharField(max_length=300, blank=True, default='') cost_unit_of_measure = models.FloatField() rfq = models.ForeignKey(Rfq, null=True, on_delete=models.CASCADE) def __str__(self): return self.material_item_process_description class Processing(models.Model): annual_volume = models.CharField(max_length=300) set_up_time = models.FloatField(blank=True, default='') set_up_persons = models.CharField(max_length=300, blank=True, default='') rfq = models.ForeignKey(Rfq, null=True, on_delete=models.CASCADE) def __str__(self): return self.annual_volume class Packaging(models.Model): #Packaging, Logistics, Amortization, Duties & Customs packaging_cost = models.FloatField() freight_cost_1 = models.FloatField(blank=True, default='') freight_cost_2 = models.FloatField(blank=True, default='') freight_cost_3 = models.FloatField(blank=True, default='') rfq = models.ForeignKey(Rfq, β¦ -
Django handle errors in class based views
I am trying to build a URL shortener, but I hit a wall. models.py from django.db import models from hashlib import md5 # Create your models here. class Url (models.Model): url = models.URLField(unique = True,max_length=500) clicks = models.IntegerField(default=0) url_hash = models.CharField(unique=True,max_length=8) short_url = models.URLField(unique=True,default="https://myurl.com/s") create_at = models.DateTimeField(auto_now_add=True) def clicked(self): self.clicks += 1 self.save() def save(self, *args, **kwargs): if self._state.adding: self.url_hash = md5(self.url.encode()).hexdigest()[:8] self.short_url = "myurl.com/s/" + self.url_hash def get_absolute_url(self): from django.urls import reverse return reverse('shortener_detail', args=[str(self.id)]) relevant view class CreateShortyView(CreateView): model = Url template_name = 'shortener/home.html' form_class = UrlShortenerForm def get_context_data(self, **kwargs): kwargs['object_list'] = top10 = Url.objects.order_by('-clicks')[:10] return super(CreateShortyView,self).get_context_data(**kwargs) and form class UrlShortenerForm(forms.ModelForm): url = forms.URLField(max_length=500,widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Your long URL'}),label=False) class Meta: model = Url fields = ['url'] When invalid form data gets supplied django rerenders my template and adds a <ul> with the errors. I want to do the following things: When an Url entry already exists simply redirect to my detail template When a non Url is supplied render them myself somewhere on the page not as a <ul> Help is really appreciated! -
How to reset password using Django and gmail
I am trying to make user allows to reset their forgotten password I got this error (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError 77sm14812049pfx.85 - gsmtp', 'webmaster@localhost') I have some following codes.# settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') and urls.py path('password-reset', auth_views.PasswordResetView.as_view(template_name='register/passwords/password_reset.html'), name='password_reset'), path('password-reset/done', auth_views.PasswordResetDoneView.as_view(template_name='register/passwords/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='register/passwords/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-reset', auth_views.PasswordResetCompleteView.as_view(template_name='register/passwords/password_reset_complete.html'), name='password_reset_complete'),