Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need suggestions to upload a huge amount of dataset
I'm looking for a solution to upload a huge excel data in Postgresql with a django rest api, the size of file is around 700mb while the number of rows are in millions. The options i'm looking for are: My question is how should i manage such a huge upload and how possibly show the status of uploaded data? Should i upload file in backend the parse and upload in tables? Should i parse data in frontend and upload on backend? Answer any suggestions you, what's the best practice that is used in real world apps? -
Django How to customize constraint Message in Meta Class?
I want to customize Meta class constraints default message. Here is my model that I have been working out. class BusRoute(BaseModel): route = models.ForeignKey(Route, on_delete=models.PROTECT) shift = models.ForeignKey( Shift, null=True, on_delete=models.PROTECT ) journey_length = models.TimeField(null=True) class Meta: default_permissions = () verbose_name = 'Bus Route' verbose_name_plural = 'Bus Routes' constraints = [ models.UniqueConstraint( fields=['route', 'shift'], name='unique_bus_company_route' ) ] The default constraint error message is as following Bus Route with this Shift already exists. Is there any way out I can customize this constraint message? -
from allauth.account.adapter import DefaultAccountAdapter causing error The SECRET_KEY setting must not be empty
I'm trying to create a custom rederect with djangl-allauth but when I import this #settings.py from allauth.account.adapter import DefaultAccountAdapter I got the following error. raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. #settings.py SECRET_KEY = 'I have a code here and it is not emrpy' -
TemplateDoesNotExist at /welcome_page/
I'm new in coding field. I decided to start a project with Django & Python, but I got stuck due to some errors. For the past 3 weeks, I tried to figure out what was the issue but couldn't find it. I will appreciate it if anyone help. when I run my code, I get as an error, "TemplateDoesNotExist at /welcome_page/" Everything as been specified but I'm still getting the same error Here is the error page: TemplateDoesNotExist at /welcome_page/ content of the welcome page: Content of my the welcome page my URLS : URLS where I defined welcome page My base content: My base content the place where the welcome page is calling from: The place where the welcome page is calling from My root to the welcome page from my C: drive: My root to the welcome page from my C: drive -
Serializer not working in custom method in model viewset,
This is my custom method in model viewset. class UserViewSet(viewsets.ModelViewSet): @action(detail=False, methods=['POST'],serializer_class=UserSerializer, name='Attach meta items ids') def create_user(self, request): queryset = User.objects.all() serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) this is my serialzer class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) print("lklml") def create(self, validated_data): print("hjniknjbj") if UserModel.objects.filter(email=validated_data['email']).exists(): raise serializers.ValidationError("A user is already registered with this e-mail address.") if UserModel.objects.filter( username=validated_data['username']).exists(): raise serializers.ValidationError("This username already exists.") user = UserModel.objects.create( username=validated_data['username'], email=validated_data['email'] ) # add custom password password validation later user.set_password(validated_data['password']) user.save() return user class Meta: model = UserModel fields = ("id", "username", "password", "email",) extra_kwargs = {"password": {'write_only': True}} Now when ever i hit the api it's directly returning data what i sent and not going through serializer process i.e: returning same thing which i am posting.The issue is only when i am using custom viewset method. {"username":"pragghgjhhhkhhhhjbjhjhkjbjvin","email":"pravwnkwin@dat.com","password":"kms@1234"} -
I am not understanding what role is item.quantity and item.get_total playing in the code
class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): #get total value of all products with their respective quantity orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): #get items total orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): #make more orderitem product = models.ForeignKey(Paidproduct, on_delete=models.SET_NULL, blank=True, null=True) #it's gonna give you what you actually define in def__str___.....return self.name order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) data_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): #to get total items of a certain product in cart.html total = self.product.price * self.quantity return total -
django forloop counter as a variable
So I am trying to make an e-commerce pizza site where when a user adds an item to the basket it is stored as a cookie in the form cart=[{"id":"2","quantity":"1"},{"id":"3","quantity":"5"},{"id":"5","quantity":"3"},{"id":"5","quantity":"3"}] And my views.py is... def cart(request): cart = request.COOKIES.get('cart') cart = json.loads(cart) items =[] basket=[] for i in cart: pizza = Product.objects.filter(pk=i['id']).first() basket.append(int(i['quantity'])) items.append(pizza) cart = len(cart) context = { "cart":cart, "pizzas":items, "basket":basket } return render (request, "store/cart.html", context) And my models.py is ... class Product(models.Model): name = models.CharField(max_length=70) price = models.IntegerField() description = models.CharField(max_length=300) image = models.ImageField(upload_to="pizza_images") def save(self, *args, **kwargs): super().save() img = Image.open(self.image.path) img.save(self.image.path) def __str__(self): return f"{self.name}" In which my template code... <table> <thead> <tr> <th scope="col" class="small_col">Item</th> <th id="product_col" scope="col">Product</th> <th scope="col" class="small_col">Quantity</th> <th scope="col" class="small_col">Price</th> </tr> </thead> <tbody> {% for pizza in pizzas %} <tr> <td class="center">{{forloop.counter}}</td> <td>{{pizza.name}}</td> <td class="quantity_row justify-content-center"> <input class="quantity_input" type="text" value="{{basket.forloop.counter0}}" id="pizza{{forloop.counter}}"> <div class="form_buttons"> <img onclick="add(this.getAttribute('data-attribute'))" data-attribute="pizza{{forloop.counter}}" src="https://s.svgbox.net/hero-outline.svg?ic=plus-sm&fill=000" > <img onclick="minus(this.getAttribute('data-attribute'))" data-attribute="pizza{{forloop.counter}}" src="https://s.svgbox.net/hero-outline.svg?ic=minus-sm&fill=000"> </div> </td> <td class="center"> <h6>$25</h6> </td> <td class="small_col"> <a><img class="mb-1" src="https://s.svgbox.net/hero-outline.svg?ic=trash&fill=d90429" width="20" height="20"></a> </td> </tr> {% endfor %} </tbody> </table> And in the input field I want the quantity of the product to be displayed. The line which says... <input class="quantity_input" type="text" value="{{basket.forloop.counter0}}" id="pizza{{forloop.counter}}">and for somereason the … -
Django is not able to read the data posted from the POSTMAN?
I have the following code snippet:- from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def ajax_post_view(request): if request.method == "POST": foo = request.POST.get('Foo') print(foo) return JsonResponse(foo, safe=False) else: return JsonResponse("Not a POST method", safe=False) And I am making a POST request from POSTMAN which showls null value in response:- What am I missing? -
Django context processor 'AnonymousUser' object is not iterable
Im new to Django and have the below context processor which passes some data which is displayed in the header. everything works ok until the user logs out which should direct them back to the login screen however i get the below error. enter image description here here is the code from . models import Job from datetime import date def add_variable_to_context(request): today = date.today() engineers_jobs = Job.objects.filter(date_due__lte = today).filter(assigned_to=request.user) engineer_overdue = 0 for job in engineers_jobs: engineer_overdue += 1 return { 'engineers_jobs': engineers_jobs, 'engineer_overdue':engineer_overdue, } i then tried the below from . models import Job from datetime import date def add_variable_to_context(request): if request.user.is_authenticated: today = date.today() engineers_jobs = Job.objects.filter(date_due__lte = today).filter(assigned_to=request.user) engineer_overdue = 0 for job in engineers_jobs: engineer_overdue += 1 return { 'engineers_jobs': engineers_jobs, 'engineer_overdue':engineer_overdue, } but that displayed the following error enter image description here can someone help me where i am going wrong? Thanks -
Django: Add context to TemplateView
I have very simple template which I would like to mount via TemplateView: urlpatterns = [ ... path('feedback', TemplateView.as_view(template_name='foo/feedback.html', context=dict(mail=settings.DEFAULT_FROM_EMAIL)), name='feedback'), ] But this does not work: TypeError: TemplateView() received an invalid keyword 'context'. as_view only accepts arguments that are already attributes of the class. How can I add render a template without writing a method? -
How to create complex multi model join query set with Django ORM
I want to create a query set with multiple tables. I cannot find any resource that helps Beside some small 2 table join examples, I cannot find any resource that is helpful for this, not in stackoverflow, the Django docs or even in the ORM Cookbook. Below is firstly the SQL I want to recreate followed by the models classes, simplified for the purpose of this question. They have in fact a LOT more fields. SELECT doc_uid, docd_filename, doct_name, docd_media_url FROM vugd_detail, vugdoc_vug_docs, doc_documents, docd_detail, doct_type WHERE vugd_vug_uid = vug_uid AND vugdoc_vug_uid = vug_uid AND vugdoc_doc_uid = doc_uid AND docd_doc_uid = doc_uid AND doct_uid = doc_doct_uid AND vugd_status = 1 AND docd_status = 1 AND NOW() BETWEEN vugd_start_date AND vugd_end_date AND NOW() BETWEEN docd_start_date AND docd_end_date AND vug_uid = {{Some ID}}; class VugVirtualUserGroup(models.Model): objects = None vug_uid = models.AutoField(primary_key=True) vug_name = models.CharField(unique=True, max_length=30) vug_short_code = models.CharField(max_length=6) vug_created_on = models.DateTimeField() vug_created_by = models.CharField(max_length=30) class Meta: managed = False db_table = 'vug_virtual_user_group' app_label = 'main' class VugdDetail(models.Model): objects = None vugd_uid = models.AutoField(primary_key=True) vugd_vug_uid = models.ForeignKey(VugVirtualUserGroup, models.DO_NOTHING, db_column='vugd_vug_uid') vugd_long_name = models.CharField(max_length=50) vugd_status = models.IntegerField() vugd_start_date = models.DateTimeField() vugd_end_date = models.DateTimeField() class Meta: managed = False db_table = 'vugd_detail' app_label = 'main' class … -
how to use use Django filtered class data to 2 seperate view
I am using Django filter and using it in normal view it is working as expected now I want to download the filtered data so for this I am writing one download view where I am trying to use the same FilterClass but no luck. It is giving me an ERROR. Can anyone please help/suggest how to use filtered queryset in filter class more than one view OR pass the data of filtered query to the download views. Please find my code. filters.py class CTAFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = CTS fields = ['id', 'EmailID','id','Shift_timing'] Here I want when the user will select Shift_timing for example Morning he will get 10 records so the same data I want to pass to the below download view. (For this I am using CTSFilter class but no luck.) Please find the below download code(View). def exportcts_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="CTA_ShiftTiming.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('CTS_ShiftChange Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['id','idk','Shift_timing','EmailID','Vendor_Company','Project_name','SerialNumber','Reason','last_updated_time'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # … -
Pass a custom param with a ModelViewSet URL
What's the best way of passing a param using a ModelViewSet? Forexample achieving something like this : http://127.0.0.1:8000/api/v1/financing-settings/template/?param=block Below is the approach I was using but found out I have set the param in the body section, but it's not what I want : class TemplateView(ModelViewSet): """ViewSet for Saving Block/ Step template.""" def list(self, request, *args, **kwargs): """Get list of Block/Steps with is_process_template is equal to True.""" param = request.data['param'] if param == "block": _block = Block.objects.filter(is_process_template=True).values() return JsonResponse({"data": list(_block)}, safe=False, status=200) elif param == "step": _step = Step.objects.filter(is_process_template=True).values() return JsonResponse({"data": list(_step)}, safe=False, status=200) return Response(status=status.HTTP_204_NO_CONTENT) -
Sequentially validating individual attributes with Django Rest Framework
I am very new to Django Rest Framework and am confused about coding the following task: when a user on the front-end enters an email address, without any other user information, the API should determine whether or not the email already exists. Likewise, when the user enters a username, without any other user information, the API should determine whether or not the username already exists. I am aware of the existence of validators, but I don't understand how to use them on partial data. Here is my serializers.py class class CustomUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) username = serializers.CharField(min_length=2) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField(min_length=2) last_name = serializers.CharField(min_length=2) class Meta: model = CustomUser fields = ('pk', 'email', 'username', 'password', 'created_at', 'first_name', 'last_name') extra_kwargs = {'password': {'write_only': True}} def validate_email(self, value): if CustomUser.objects.filter(email=value).exists(): raise serializers.ValidationError("An account already exists with that email address.") return value def validate_username(self, value): if CustomUser.objects.filter(username=value).exists(): raise serializers.ValidationError("An account aready exists with that username.") return value def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance And here is my views.py class class CustomUserCreate(APIView): permission_classes = (permissions.AllowAny,) authentication_classes = () def post(self, request, format='json'): """ Receives an HTTP request. Serializes … -
How to only use a single instance of multiple same name classes
When clicking on a link, it changes from like to unlike or vice versa but, the number of likes and unlike are supposed to change uniquely and not every single one of the posts in the same page. A for loop in Django is used to call the posts, so they have the same class names. The jquery below is supposed to change the like count of a specific post, but it changes every single one due to the class name. How can this be done please. jquery extract var previous_likes = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); full jquery code $('a.like').on('click', function(event){ event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); $.post('{% url "posts:post_like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $(event.target).data('action'); // toggle data-action $(event.target).data('action', previous_action == 'like' ? 'unlike' : 'like'); // toggle link text $(event.target).text(previous_action == 'like' ? 'Unlike' : 'Like'); // update total likes var previous_likes = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } } ); }); -
Troubles with test Django
i am noob in django and trying to find an adequate solution for my problem. Perhaps i have searched a lot but didn't find satisfy solution. How i can figure out with this problem? Test Errors: Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Try the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\Users\DjangoDev\Desktop\Django\mi> py .\manage.py test osu Creating test database for alias 'default'... System check identified no issues (0 silenced). EEEEEEEEEE ERROR: test_with_future_question (osu.tests.DetailModelTests) Traceback (most recent call last): File "C:\Users\DjangoDev\Desktop\Django\mi\osu\tests.py", line 60, in test_with_future_question future_quest = create_question('f', 30) File "C:\Users\DjangoDev\Desktop\Django\mi\osu\tests.py", line 26, in create_question return Question.objects.create(text, time) File "C:\Users\DjangoDev\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) TypeError: create() takes 1 positional argument but 3 were given ====================================================================== ERROR: test_with_past_question (osu.tests.DetailModelTests) Traceback (most recent call last): File "C:\Users\DjangoDev\Desktop\Django\mi\osu\tests.py", line 65, in test_with_past_question past_quest = create_question('p', -30) File "C:\Users\DjangoDev\Desktop\Django\mi\osu\tests.py", line 26, in create_question return Question.objects.create(text, time) File "C:\Users\DjangoDev\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) TypeError: create() takes 1 positional argument but 3 were given ====================================================================== ERROR: test_does_not_have_any_question (osu.tests.QuestionIndexModelTests) Traceback (most recent call last): File "C:\Users\DjangoDev\Desktop\Django\mi\osu\tests.py", line 33, in test_does_not_have_any_question self.assertContains(response.content, 'No osu are aviable') File "C:\Users\DjangoDev\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\testcases.py", line 461, in assertContains text_repr, real_count, msg_prefix = self._assert_contains( File "C:\Users\DjangoDev\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\testcases.py", line … -
how to submit image and text field in single API endpoint using drf and angular
Good day guy i'm working on an drf api endpoint that requires user uploading image and text to the same endpoint, i've done all that is required but i still keep getting error, below is snippet of my code and error msg APIVIEW class CreateProfileView(APIView): parser_classes = (MultiPartParser,) serializer_class = schoolProfileSerializer queryset = schoolProfile.objects.all() permission_classes = [permissions.AllowAny] def perform_create(self, serializer): serializer.save(user=self.request.user) def post(self, request): file_upload = schoolProfileSerializer(data =request.data, instance=request.user) if file_upload.is_valid(): file_upload.save() return Response(file_upload.data, status=status.HTTP_201_CREATED) else: return Response(file_upload.errors, status=status.HTTP_400_BAD_REQUEST ) SERIALIZER class Base64Imagefield(serializers.ImageField): def to_internal_value(self, data): if isinstance(self, six.string_types): if 'data: ' in data and ';base64, ' in data: header, data = data.split(';base64,') try: decode_file = base64.b64decode(data) except TypeError: self.fail('invalide image') file_name = str(uuid.uuid4())[:16] file_extension = self.get_file_extension(file_name, decode_file) complete_file_name = "%s.%s" %(file_name, file_extension) data = ContentFile(decode_file, name=complete_file_name) return super(Base64Imagefield, self).to_internal_value(data) def get_file_extension(self, file_name, decode_file): extension = imghdr.what(file_name, decode_file) extension = 'jpg' if extension == 'jpeg' else extension return extension class schoolProfileSerializer(serializers.ModelSerializer): parser_classes = (MultiPartParser, FormParser, ) id = serializers.IntegerField(source='pk', read_only=True) email = serializers.CharField(source='user.email', read_only=True) username = serializers.CharField(source='user.username', read_only=True) badge = Base64Imagefield(max_length=None, use_url=True) class Meta: model = schoolProfile fields = ( 'email', 'id', 'username', 'school_name', 'address', 'badge', 'gender', 'level', ) def create(self, validated_data, instance=None): if 'user' in validated_data: user = validated_data.pop('user') … -
how to display many to many and many to one datas of my table in django
I am totaly new to django and django rest-api, I have a tables named op , it has many to many relation with two other tables. (country through op_country) , (sector throgh op_sector) and 1 to many relation with table named attachements. below is my table models. class Op(models.Model) : name = models.CharField(max_length=40) class Meta : db_table = "op" class Country(models.Model) : name = models.CharField(max_length=60 , null=True , unique=True) coun_op = models.ManyToManyField(Op , through='Op_country' , through_fields=('country_id' , 'op_id')) class Meta : db_table = "country" def __str__(self) : return self.name class Op_country(models.Model) : op_id = models.ForeignKey(Op , on_delete=models.CASCADE) country_id = models.ForeignKey(Country , on_delete=models.CASCADE) class Meta: db_table = "op_country" class Attachments(models.Model) : op_id = models.ForeignKey('Op' , on_delete=models.CASCADE) link = models.CharField(max_length=200) class Meta : db_table = "attachments" **`below are my serializers.`** class op_Serializer(serializers.ModelSerializer): class Meta: model = Op fields = ['id', 'name'] class country_Serializer(serializers.ModelSerializer) : class Meta: model = Country fields = ['id', 'name'] class op_country_Serializer(serializers.ModelSerializer) : class Meta: model = Op_country fields = ['id', 'op_id', 'country_id'] class attachments_Serializer(serializers.ModelSerializer) : class Meta: model = Attachments fields = ['id', 'name','link'] right now when I sent a get request to my view my below viewset @permission_classes([AllowAny]) class op_ViewSet(viewsets.ModelViewSet) : serializer_class = op_Serializer def get_queryset(self) : … -
TypeError: unsupported operand type(s) for /: 'str' and 'str' django setting.py
when im taking my course of django i got this error i don't know how to fix it here is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } -
Choosing among ManyToMany, CharField and JSONField for performance
I want to get the most performance out of my database. I have instances between 250.000-300.000 and each of them has 15 columns. 5 of them is ManyToMany field. And their instances are very low in quantity, like 10-15 for each. And there is 4 columns in each. But only one of them has 1000-1200 instances with same amount of columns. Can I get a better performance by converting ManyToMany fields to CharFields or even storing everything into a single JSONField? How much do you think it will affect? And how can I test it and get numbers to compare? Example code is very much appreciated. Since I upload data to my database by using only fixtures, I don't really need any convenience of editing data in admin dashboard. -
Private messaging in Django - how to perform 1-sided delete
I have been trying to create a simple messaging system on my Django site. I have the basic functionality up and running but would now like to add a delete button. Originally, I was just going to use a DeleteView with jQuery but I realized this would delete the message object entirely making it inaccessible for both the sender and receiver. For example, if one user deleted a message from their inbox, it would also delete the message from the receiver's sent box. Is there a way to perform some kind of 1-sided delete so a user can delete a message on their side without impacting the other's? Maybe some way to create 2 message objects each time (i.e., a sent message and a received message)? Thanks! Message model: class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") reciever = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reciever") subject = models.CharField(max_length=128, default="-") content = models.TextField() send_date = models.DateTimeField(default=timezone.now) Delete JQuery: $(".delete-btn").click(function(e){ e.preventDefault if (confirm('Are you sure you want to delete?')) { var deleteUrl = $(this).attr("delete-href") var picID = $(this).attr("message-id") if (deleteUrl){ $.ajax({ url: deleteUrl, type: 'DELETE', method: "POST", data: {'csrfmiddlewaretoken': '{{csrf_token}}'}, }) } } }); Inbox HTML: <h1 class="d-inline-block">Inbox</h1> <a class="btn btn-secondary float-right" href="{% url 'compose' username=user.username … -
Django: Force ipv4 for EMAIL_HOST? (GMail: 421, '4.7.0 Try again later, closing connection.')
If I try to send a mails with Django via settings.EMAIL_HOST, I get this error: (421, '4.7.0 Try again later, closing connection.') I found a work-around (GMail 421 4.7.0 Try again later, closing connection) It works if I use a IPv4 connection (and not IPV6). EMAIL_HOST = '64.233.184.108' But this is just a work-around, I would like to have a solution. Because if google changes the IP of the smtp servers, my solution will fail. How can I tell Django or Python to use IPv4 when I use this? EMAIL_HOST = 'smtp.gmail.com' By default my system uses ipv6, and then Google thinks I am a spammer and blocks me with "(421, '4.7.0 Try again later, closing connection.')" -
Django - using modelForms data in another models field
I'm trying to make a form to create a new account with allocation attached to account model. Allocation has three properties that need inputs, then I need to attach that to account where there is the current allocation - which contains the foreign key(allocation) Here is my code: Views.py: def accounts(request): return render(request, 'accounts.html', { 'accounts': Account.objects.all() }) def createAccount(request): form = createAccountForm() otherForm = createAllocation() if request.method == 'POST': form = createAccountForm(request.POST, prefix="primary") otherForm = createAllocation(request.POST) if form.is_valid() and otherForm.is_valid(): otherForm = otherForm.save() form = form.save() context = {'form':form, 'otherForm':otherForm} return render(request, 'create_account.html', context) Models.py: class Allocation(models.Model): equity = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)], null=True, blank=True) bonds = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)], null=True, blank=True) options = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)], null=True, blank=True) date_assigned = models.DateField(auto_now_add=True) @property def is_valid(self): """ :return: True if sum of equity, bonds and options is 100 """ if self.equity + self.bonds + self.options != 100: # sum is not 100 return False return True class Account(models.Model): class Meta: app_label = 'account' ACCOUNT_TYPES = ( ('roth_ira', 'Roth IRA'), ('traditional_ira', 'Traditional IRA'), ('brokerage', 'Brokerage Account'), ('trust', 'Trust'), ) balance = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPES, null=False, blank=False) taxable = models.BooleanField(default=False) create_date = models.DateTimeField(null=True, blank=False) close_date = models.DateTimeField(null=True, blank=True) current_allocation = models.ForeignKey(Allocation, … -
Use model viewset as well as generic viewset toether in python django
I wrote seperate class api for each user functionality but someone experienced told me to combine all in one class using custion method functionality of viewset in django rest framework. This is my code: class UserRegisterViewset(viewsets.ModelViewSet): ''' Register's user in local db''' serializer_class = UserSerializer queryset = User.objects.all() class RequestPasswordResetEmailViewset(viewsets.ViewSet): ''' Resets password of user by mail''' def create(self, request, format=None): data = {'request': request, 'data': request.data} serializer = RequestPasswordResetEmailSerializer(data=data) email = request.data['email'] if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) uidb64 = urlsafe_base64_encode(smart_bytes(user.id)) token = PasswordResetTokenGenerator().make_token(user) current_site = "pdsp.datawrkz.com" relativelink = reverse( 'password-reset', kwargs={ 'uidb64': uidb64, 'token': token}) absurl = 'http://' + current_site + relativelink email_body = 'Hi ' + user.username + \ ' Use link below to reset your password \n' + absurl data = { 'email_body': email_body, 'to_email': user.email, 'email_subject': 'Reset your password'} email = EmailMessage( subject=data['email_subject'], body=data['email_body'], to=[ data['to_email']]) email.send() return Response( {'Success': 'We have sent you a link to reset your password'}) class PasswordTokenCheckViewset(viewsets.ViewSet): ''' Checks generated password token for user creation''' def create(self, request, uib64, token): try: id = smart_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(id=id) if not PasswordResetTokenGenerator().check_token(user, token): return Response( {'error': 'Token is not valid, please request a new one'}) return Response({'Success': True, 'message': 'Credentials Valid', 'uid64': uidb64, … -
Django showing Id of model in browser url instead of model name
I created models for companies in my new application in django and have also created the instance for it to show detail page for each company. But when a company is clicked, it shows the id of the company instead of the name in URL like this: http://127.0.0.1:8000/companies/2/ is there a way I can make it return the company name instead like this: http://127.0.0.1:8000/companies/stackoverflow/ this is the code for my model and am using function based views for this: class Company(models.Model): Online_Merchant = 'merch' Education = 'edu' Transportation = 'trans' Hospitalism = 'hosp' Healthcare = 'health' Construction = 'const' Blog = 'blog' Finance = 'fin' Media = 'media' Government_Agency = 'agency' Other = 'other' Manufacturing = 'manufacturing' sector = [ (Online_Merchant, 'Online Merchant'), (Education, 'Education'), (Transportation, 'Transportation'), (Hospitalism, 'Hospitalism'), (Healthcare, 'Healthcare'), (Construction, 'Construction'), (Blog, 'Blog'), (Finance, 'Finance'), (Media, 'Media'), (Manufacturing, 'Manufacturing'), (Government_Agency, 'Government Agency'), (Other, 'Other') ] Free = 'Free' Premium = 'Premium' package = [ (Free, 'Free'), (Premium, 'Premium') ] user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='Company User') company_sector = models.CharField(max_length=30, choices=sector, default=Online_Merchant, verbose_name='Sector') company_name = models.CharField(max_length=100) company_description = models.TextField() company_logo = models.ImageField(upload_to='company_logos', blank=True, null=True) company_address = models.TextField(max_length=2000) rating_array = ArrayField(models.IntegerField(), size=0, default=list) average_rating = Int_max.IntegerRangeField(default=0, verbose_name='Avg', min_value=1, max_value=5) …