Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Json Data Migrations - Invalid Syntax
I am loading json data from migrations. So in my migrations file I have put the following code # Generated by Django 2.1.7 on 2019-03-15 11:20 from django.db import migrations from django.db import migrations import json from django.contrib.gis.geos import fromstr from pathlib import Path DATA_FILENAME = 'data.json' def load_data(apps, schema_editor): Shop = apps.get_model('shops', 'Shop') jsonfile = Path(__file__).parents[2] / DATA_FILENAME with open(str(jsonfile)) as datafile: objects = json.load(datafile) for obj in objects['elements']: try: objType = obj['type'] if objType == 'node': tags = obj['tags'] name = tags.get('name','no-name') longitude = obj.get('lon', 0) latitude = obj.get('lat', 0) location = fromstr(f'POINT({longitude} {latitude})', srid=4326) Shop(name=name, location = location).save() except KeyError: pass class Migration(migrations.Migration): dependencies = [ ('shops', '0001_initial'), ] operations = [ migrations.RunPython(load_data) ] But it is giving me error which i don't have idea - The error is in this line - location = fromstr(f'POINT({longitude} {latitude})', srid=4326) Error - File "/project/geo_django/shops/migrations/0002_auto_20190315_1120.py", line 26 location = fromstr(f'POINT({longitude} {latitude})', srid=4326) ^ SyntaxError: invalid syntax I am using Python 3.5.2 -
How to filter extra context data from one serializer when used in another?
With django rest framework, I have two serializers for two different models. Lets say, the models are Author and Book. Author Model has the fields: name, address, phone, email, description and created_at while the book has the fields: name, publisher_name, genre, description, created_at and author(foreign key to Author model). Now, I have the serializers defined for Author and Book: class BookSerializer(serializers.Serializer): class Meta: model = Book exclude = ['created_at'] class AuthorSerializer(serializers.Serializer): books = BookSerializer(many=True,required=False,null=True) class Meta: model = Author exclude = ['created_at'] The current schema gives the return of Book serializer for instance as: { "id":1, "name":"Book_name", "publisher_name":"Publisher", "genre":"g", "description":"Book description", "author":1 } While the return of authorserializer is: { "id":1, "address":"Address", "phone":9812312312, "email":"email@email.c", "description":"this is description", "books": [ { "id":1, "name":"Book_name", "publisher_name":"Publisher", "genre":"g", "description":"Book description", "author":1 } ] } The thing is that I dont want all the details in the books of the return for Authorserializer, and want to exclude the description and genre. How to do this? -
Django append function result to object item
I am using django-haystack and I am trying to implement a way to append the page number to a pdf link in order to open it in the specific page. My goal is to open the pdf in the page where the first hit is found. I know the position of the hit in my document and the position where the page changes. For example i know that the first hit starts at character 2067 and the second page changes at character 3000, so i have to open the pdf at the second page. My question is: how can i get the result of the function that finds the number of the page where the pdf should open and render it ? I am thinking that the result should be something like that <a href="{% static 'img/sample.pdf#page={{ pageNumber }}' %}"> but i am open to any other suggestions. P.S. I am not asking you to solve my problem. I am asking for suggestions or a constructive discussion as i am new to django. Thank you in advance -
Attribute error module 'django.db.models' has no attribute RichTextUploadingField
Hi am trying to integrate ckeditor in my blog and here is the error am getting help out when i try to use from ckeditor_uploader.fields import RichTextUploadingField,RichTextField, error cannot import RichTextField models.py from django.db import models from django.template.defaultfilters import slugify from django.conf import settings from taggit.managers import TaggableManager from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): STATUS_CHOICES=( ('Published','Published'), ('Draft','Draft'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1,on_delete=models.CASCADE) title = models.CharField(max_length=250) body = models.RichTextUploadingField() Category=models.ForeignKey(Category,on_delete=models.CASCADE) seo_title = models.CharField(max_length=60,blank=True,null=True) seo_description = models.CharField(max_length=125,blank=True,null=True) slug = models.SlugField(max_length=200,unique=True) status = models.CharField(max_length=10,default='Draft',choices=STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) thumb=models.ImageField(blank=True) tags = TaggableManager() def save(self,*args,**kwargs): self.slug=slugify(self.title) super(Post,self).save(*args,**kwargs) def __str__(self): return self.title def snippet(self): return self.body[:300]+'....' #def get_absolute_url(self): settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', 'blog', 'django_social_share', 'taggit', 'ckeditor', 'ckeditor_uploader', ] STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') #PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) #STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') #... SITE_ID = 1 #################################### ## CKEDITOR CONFIGURATION ## #################################### CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } also trying to use the import from ckeditor.fields import RichTextField says cannot import from RichTextField -
Expire the user activation link and remove from database in django
I have an user signup, where the user's account is activated after link with a token send to their email address is clicked. I want to expire the link and delete their data from the database if the specific link is not clicked within 24 hours. I have read it in one place, that the link is expired after 48 hours, is that correct? Here is my question - How can I automatically remove those users who do not click on the activation link with in 24 hours? (So far I can do that by going to admin panel and by checking email is confirmed or not) Here is my activate function, def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, ObjectDoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.email_confirmed = True user.save() login(request, user) return redirect('home') else: return render(request, 'user/account_activation_invalid.html') This is my tokens.py to create token, from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() What should I change to achieve that? -
Create modal dynamically from json response
I am dumping a html code of a div in json format at client side.I am using Django Channels Groups to do this. Server-Side def my_view(obj1,obj2): #---------------------some_existing_lines_of_code-----------------------------------# notification={"id":"<div class=\"modal fade\" id=\"lab-slide-bottom-popup\" data-keyboard=\"false\" data-backdrop=\"false\"><div class=\"lab-modal-body\"><button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button><form>Name: <input id=\"v_name\" type=\"text\" name=\"visitor_name\" ><br><br>E-mail: <input id=\"v_email\" type=\"email\" name=\"emailaddress\"><br><br>Inquiry:<select id=\"v_inquiry\"><option value=\"Sales\">Sales</option><option value=\"Support\">Support</option><option value=\"Contact\">Contact</option></select><br><br><input class=\"submit-btn\" type=\"submit\" name=\"Submit\"></form></div></div>"} Group(group_name).send({"text": json.dumps(notification),}) Now at client side i am listening this data sent by server Client-Side webSocketBridge.listen(function(text) { //Here i have to use the data sent by server to create the modal.I need your help here.What i think it should be something like following $("body").html(text.id); jQuery(document).ready(function($) { setTimeout(function() { $('#lab-slide-bottom-popup').modal('show'); }, 2000); $(document).ready(function() { $('.lab-slide-up').find('a').attr('data-toggle', 'modal'); $('.lab-slide-up').find('a').attr('data-target', '#lab-slide-bottom-popup'); }); }); }); When my code runs rather than showing up the modal, a blank page is shown to me.How do i use the JSON sent by my server to create modal dynamically? P.S:I have provided the source of script jquery,link to stylesheet of this modal and other necessary scripts at client side but i haven't shown them here just to maintain clarity otherwise it would have looked messy. -
How to retrieve django many to many field with list of subscribed objects
users on my project can subscribe model Board and I try to show all objects from all subscribed boards who user subscribe. But don't know how. I search through internet but nothing help me in this. Model board: class Board(models.Model): title = models.CharField(max_length=255, verbose_name='Tytuł') slug = AutoSlugField(populate_from='title', unique=True) image = ImageField(blank=True, manual_crop="" ,verbose_name='Tło') body = models.TextField(verbose_name='Opis kategorii') author = models.ForeignKey(User, on_delete=models.CASCADE) subscribers = models.ManyToManyField(User, related_name='subscribed_boards', blank=True) created_at = models.DateTimeField(auto_now_add=True) Models related to(I try to show this objects from subscribed boards): class Subject(models.Model): title = models.CharField(max_length=255, verbose_name='Tytuł') slug = AutoSlugField(populate_from='title', unique=True) body = HTMLField(blank=True, verbose_name='Treść') image = models.ImageField(upload_to='subject', null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subjects', verbose_name='Kategoria') votes = GenericRelation(LikeDislike, related_query_name='subjectsvotes') class Embed(models.Model): url = models.URLField(max_length=255) title = models.CharField(max_length=255, verbose_name='Tytuł') description = HTMLField(verbose_name='Opis') thumbnail_url = models.URLField(max_length=255) html = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, on_delete=models.CASCADE, blank=True, null=True, related_name='embeds', verbose_name='Kategoria') votes = GenericRelation(LikeDislike, related_query_name='embedvotes') slug = AutoSlugField(populate_from='title', unique=True) In view I try this: def feed(request): user = get_object_or_404(User, username=request.user) feed = user.subscribed_boards.all() embeds = feed.filter(embed__in=feed) return render(request, 'boards/feed.html', {'feed': feed, 'embeds': embeds}) -
Django REST Framework doesn't render ModelViewSet with GM2MField
I'm trying to use Django REST Framework: models.py class Document(models.Model): doc_date = models.DateTimeField() doc_num = models.IntegerField(unique_for_date='doc_date') follower = GM2MField() serializers.py class DocIncomeSerializer(serializers.ModelSerializer): class Meta: model = models.DocIncome exclude = () views.py class DocIncomeViewSet(viewsets.ModelViewSet): serializer_class = serializers.DocIncomeSerializer queryset = DocIncome.objects.all() I get error when open api url: 'GM2MField' object has no attribute 'get_limit_choices_to' How can I fix it? -
Django - Alert model datefield expire
I have a list of models. All models (as in the example) have a start date field and an expiration date field. I need a function that after saving a new record inside the model: extend the class of all models (except the one in the first example) check that in the model in question there are the date and expiry date fields order the list of records within the model in descending order from the most distant expiry date that if today's date is the same as the expiration date give me the value within the expiration date in red that if today's date is less than the expiry date give me the value within the expiration date in green All the models are the same as this class contract(models.Model): id = models.AutoField(primary_key=True) condition= models.ForeignKey( 'condition', models.DO_NOTHING, blank=True, verbose_name='Condition') date = models.DateField('Date') date_expire = models.DateField('Date Expire', max_length=500) enable = models.BooleanField('Enable') def __str__(self): return self.date_expire class Meta: verbose_name = 'contract' verbose_name_plural = "contracts" managed = False db_table = 'a_contract' -
puzzle in python of removing particular characters from the inserted string
Is there any other substitue for this code where i do not use random function so that the testing compiler can remove any character it wants. also a constraint is given that only atmost 2 characters can be removed from the string def puzzle(s): import random # s= str(input("string is : ")) l = [0, 1, 2] lenthofstring = len(s) n = random.choice(l) # print(n) for x in range(0, n + 1): p = random.choice(s) # print(p) s1 = s.replace(p, '') # print(s,s1) # print(len(s),len(s1)) if len(s1)<len(s) / 2: return True else: return False print(puzzle(s=str(input()))) -
Is this warning in django_tenants still valid?
In apps.py of django_tenants, I see this: recommended_config = """ Warning: You should put 'django_tenants' at the end of INSTALLED_APPS: INSTALLED_APPS = TENANT_APPS + SHARED_APPS + ('django_tenants',) This is necessary to overwrite built-in django management commands with their schema-aware implementations. """ My question is: is that still valid? We had django_tenants installed (in dev) for a few weeks before I happened to see that message in the code. It wasn't last in INSTALLED_APPS, but it seemed to be working just fine. -
Not able to create records using django rest framework
I am trying to create a record in Status model by taking an object from Visit model.but while passing values to create record am getting error as few filed data is required. my code is given below along with the data am passing. models.py class Visit(models.Model): name = models.CharField(max_length=200, name="name") gender = models.CharField(choices=GENDER_CHOICE, max_length=1, name="gender") mobile = models.CharField(max_length=18,default="", name="mobile") email = models.CharField(max_length=256, null=True, blank=True, name="email") address = models.TextField(null=True, blank=True, name="address") visit_type = models.IntegerField(choices=VISIT_TYPE, name="visit_type") visit_purpose = models.CharField(max_length=250, name="visit_purpose") visitor_photo = models.FileField(upload_to="visitor/",null=True, blank=True) id_photo = models.FileField(upload_to="id_card/",null=True, blank=True) date_created = models.DateTimeField(default=timezone.now, editable=False) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.id: self.date_created = timezone.now() super(Visit, self).save(*args, **kwargs) class Status(models.Model): visit = models.ForeignKey(Visit,on_delete=models.CASCADE) description = models.CharField(name="description",max_length=200) time = models.DateTimeField(null=True, blank=True) aproved = models.BooleanField(default=False) visit_complete = models.BooleanField(default=False) exit_time = models.DateTimeField(null=True, blank=True) date_created = models.DateTimeField(default=timezone.now, editable=False) def __str__(self): return self.visit.name def save(self, *args, **kwargs): if not self.id: self.date_created = timezone.now() super(Status, self).save(*args, **kwargs) serializer.py class VisitSerializers(serializers.ModelSerializer): class Meta: model = Visit fields = ('name','gender','mobile','email','address','visit_type','visit_purpose','visitor_photo','id_photo') class StatusSerializers(serializers.ModelSerializer): visit = VisitSerializers(required=True) class Meta: model = Status fields = ('visit', 'description','time','aproved','visit_complete','exit_time') def create(self, validated_data): visit_data = validated_data.pop('visit') visit = VisitSerializers.create(VisitSerializers(), validated_data=visit_data) status, created = StatusSerializers.objects.update_or_create(visit=visit, description=validated_data.pop('description')) return status views.py @api_view(['GET', 'POST']) def create_visitor(request): if request.method == … -
how can we specify the header parameters and post parameters for our django-rest api's using APIVIEW in django rest swagger UI
This is my app/views.py class ExampleView(APIView): def get(self, request, format=None): print(request.META['HTTP_HEADER']) # Want this header from swagger ui snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) app/serilaizers.py class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner') current screenshot of swagger UI as there is no field for header parameters and post parameter. -
How to display and handle product quantity while buying in django ecommerce
I want to display and handle how many(quantity of ) selected products are available in the shop and how many selected products customer ordered in the detail page and cart-items page.And i want to calculate the total price based on the quantity ,shipping fee and price together. How can i do that ?? urls.py path('mycart/', views.mycart, name='mycart'), path('<slug>/cart/', views.cart, name='cart'), path('<slug>/',views.detail,name='detail'), models.py class Product(models.Model): name = models.CharField(max_length=250) image = models.ImageField(upload_to='products') seller = models.ForeignKey(User,on_delete=CASCADE) slug = AutoSlugField(populate_from='name') category = models.ForeignKey(Category,on_delete=CASCADE) description = models.TextField(blank=True,default="Description Field") brand = models.CharField(max_length=250) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=10,default=0.0,decimal_places=2) shipping_fee = models.DecimalField(max_digits=10,default=0.0,decimal_places=2) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.name views.py def cart(request,slug): product = Product.objects.get(slug=slug) initial = {"items":[],"price":0.0,"count":0} session = request.session.get('data',initial) session["items"].append(slug) session["price"] += float(product.price) if product.shipping_fee: session['price'] += float(product.shipping_fee) # if product.quantity: # session['price'] *= float(product.quantity) session["count"] += 1 request.session["data"] = session messages.success(request,'Added to Cart.') return redirect('shop:detail',slug) def mycart(request): sess = request.session.get("data", {"items": []}) products = Product.objects.filter(active=True, slug__in=sess["items"]) if not products: return render(request,'shop/empty_cart.html') context = {"products": products, "categories": categories} return render(request,'shop/cart_item.html',context) @login_required(redirect_field_name='next', login_url='shop:users_signin') def sell_product(request): if request.method == "POST": form = SellProductForm(request.POST,request.FILES) if form.is_valid(): myproduct = form.save(commit=False) myproduct.seller = request.user myproduct.save() messages.success(request,'Your Product has been posted successfully') … -
how to get the table data in place of table object_new Object in Django
i want the data so that i can perform operations on them but i get this Order_table Object(1) and so . Screenshot of table Thanks -
Best way to filter queryset by counting number of ForeignKey in Django
I have 2 models, ChatRoom and Message: Model ChatRoom: class ChatRoom(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='chat_creator', null=True, blank=True) with_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='room_user_with') Model Message: class Message(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE, related_name='message_room') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='message_user') content = models.TextField() I want to filter ChatRoom queryset by getting ChatRoom which have more than 10 messages in it. What is the best way to do this? Thank in advance! -
Django pagination work very slow when Dataset is too large
Django Pagination is very slow when dataset is very large(>100k) my dataset is 80 columns and more than 100k rows. when i load the page or change the page it takes 14-15 second there is anything that i can do to make it fast what can i do to make it fast. please help model.py class Finaltest3(models.Model): a = models.DateTimeField(db_column='Dat',primary_key=True, blank=True, null=False) # Field name made lowercase. b = models.TextField(db_column='C', blank=True, null=True) # Field name made lowercase. c = models.TextField(db_column='S', blank=True, null=True) # Field name made lowercase. d = models.TextField(db_column='Ca', blank=True, null=True) # Field name made lowercase. e = models.TextField(db_column='Ac', blank=True, null=True) # Field name made lowercase. f = models.TextField(db_column='Re', blank=True, null=True) # Field name made lowercase. . . . . . fd = models.TextField(db_column='Add', blank=True, null=True) # Field name made lowercase. fd= models.TextField(db_column='Addit', blank=True, null=True) # Field name made lowercase. fd = models.TextField(db_column='Additional', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'finaltest3' view.py from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger import datetime from datetime import date from datetime import timedelta from django.http import HttpResponseRedirect from django.shortcuts import render def displayLogs(request): today = date.today() lastweek=today - timedelta(days=7) print('lastweek',lastweek) user_list = Finaltest3.objects.filter(dat__gt=lastweek) paginator = Paginator(user_list, 10) … -
Generate pdf from html using xhtml2pdf in django project
I am trying to generate pdf from html template in a django project using xhtml2pdf. Everything is working fine but bootstrap is not working. I am following this tutorial https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ Views.py def generate_pdf(request, inflow_id): template = 'cashflow/invoice2.html' inflow = get_object_or_404(Inflow, pk=inflow_id) context = { "invoice_id": inflow.id, "customer_name": inflow.student, "amount": inflow.amount, "today": inflow.time, "fee_type": inflow.fee_type, } pdf = render_to_pdf(template, context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % inflow.student content = "inline; filename='%s'" % filename download = request.GET.get("download") if download: content = "attachment; filename='%s'" % filename response['Content-Disposition'] = content return response return HttpResponse("Not found") render_to_pdf function in utils.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None invoice2.html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>duck</title> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-4 col-md-3"> <div class="card" style="width: 24rem;"> <img class="card-img-top" src='https://cdn.bulbagarden.net/upload/thumb/0/0d/025Pikachu.png/250px-025Pikachu.png' alt="Card image cap"> <div class="card-body"> <p class="card-text">Please enter all the fee payments here.</p> </div> </div> </div> <div> <h1>Invoice id: {{ invoice_id }}</h1> <h2>Customer name: {{ customer_name }}</h2> <h3>Amount: {{ amount }}</h3> <h4>Time: {{ today }}</h4> <h5>Fee Type: {{ fee_type }}</h5> </div> </div> </div> … -
Django select option rest after error message appear in template if i change option in select
i have created form for delivery note, i am using form formset, forms.py class Delivery_note_transiction_form(forms.Form): item = forms.ModelChoiceField(label=False,queryset=Product.objects.none(),widget=Select2Widget(attrs={"class" : "item"})) description = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder' : 'optionall','class' : 'description'}),label=False,required=False) quantity = forms.IntegerField(widget=forms.NumberInput(attrs={'class' : 'quantity'}),label=False,min_value=0) id = forms.CharField(widget=forms.HiddenInput,required=False) views.py def delivery_note_creation(request): Delivery_note_transiction_form_formset = forms.formset_factory(form=Delivery_note_transiction_form,can_delete=True) if request.method == 'POST': inv_no = Invoice_max.objects.get(invoice_name='delivery') form = Deliver_Note_Main_Modelform(request.POST,initial={'delivery_invoice_no' : inv_no.invoice_no + 1}) formset = Delivery_note_transiction_form_formset(request.POST,request.FILES) if form.is_valid() and formset.is_valid(): ins = form.save(commit=False) ins.author = request.user ins.save() for transfer in formset: Delivery_Note_Transiction.objects.create(item=transfer.cleaned_data['item'], description=transfer.cleaned_data['description'], quantity=transfer.cleaned_data['quantity'], delivery_invoice_no=ins , ) max_invoice = Invoice_max.objects.get(invoice_name='delivery') max_invoice.invoice_no = max_invoice.invoice_no + 1 max_invoice.save() return HttpResponseRedirect(reverse_lazy('delivery note:delivery note home page')) else: invoice_create = Invoice_max.objects.get_or_create(invoice_name='delivery') inv = Invoice_max.objects.get(invoice_name='delivery') form = Deliver_Note_Main_Modelform(initial={ 'deliver_date' : datetime.today(), 'delivery_invoice_no' : inv.invoice_no + 1, 'total_quantity':0}) formset = Delivery_note_transiction_form_formset() return render(request,'delivery_note/delivery note creation.html', { 'deliver_main': form, 'delivery_transiction' : formset }) trmplate.html {% extends 'home/base.html' %} {% load crispy_forms_tags %} {% block title %} {% endblock title %} {% block media %} {{ deliver_main.media.css }} {{ delivery_transiction.media.css}} {% endblock media %} {% block content %} <div class="w3-container"> <h1>Delivery Note</h1> <form method="post">{% csrf_token %} <div class="row"> {{ deliver_main.errors }} {{ deliver_main.non_field_errors }} <div class="row"> <div class="col-sm-6">{{ deliver_main.customer|as_crispy_field }}</div> <div class="col-sm-6">{{ deliver_main.deliver_date|as_crispy_field }}</div> </div> <div class="row"> <div class="col-sm-6">{{ deliver_main.delivery_address|as_crispy_field }}</div> <div class="col-sm-6">{{ deliver_main.delivery_invoice_no|as_crispy_field }}</div> </div> … -
urls.py to different project django
I'm setting up a Django webserver and I have multiple projects on there and I want to serve different projects based on what domain the user is coming from. I've tried setting up a "master project" that has a urls.py, and redirect from there to different projects, but I couldn't link to different projects and I don't think that's the way I'm supposed to do it. I know I can use Apache virtualhosts but it's such a hassle and I wonder if there's a better approach. -
Django get_absolute_url() returning user to homepage
When a user creates a post using the CreateView I want it so when a user submits the Post, they then see the post they just made. But for some reason my get_absolute_url() is not working. Prior to this I started to work on slugifying the Post and Category models and haven't been able to see if they work due to the fact get_absolute_url won't work. Models: class Category(models.Model): title = models.CharField(max_length=200) colorcode = models.CharField(max_length=20, blank=True, null=True) description = models.TextField() image = models.ImageField(blank=True, null=True) slug = models.SlugField(unique=True) def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) image = models.ImageField(blank=True, null=True) live = models.BooleanField(default=False) slug = models.SlugField(unique=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug}) def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-pk") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().pk) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_reciever(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_reciever, sender=Post) Views: class IndexView(ListView): model = Post queryset = Post.objects.filter(live=True) template_name = "public/index.html" class … -
Forbidden (403) in a post request - djangorest-react
I have an endpoint for users registration. I use react for my front side of project. I send POST request to the endpoint with json body to register user. but it return's Forbidden (403). When I use postman to test functionality everything is Ok but with axios It is not. Error: POST /user/register/ 403 (Forbidden) endpoint: user/register/ Register API View: class UserRegisterAPIView(APIView): serializer_class = UserRegisterSerializer permission_classes = [permissions.AllowAny] def post(self, request, format=None, *args, **kwargs): print(request.data) serializer = UserRegisterSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() user_data = serializer.validated_data return Response(user_data) Register Serializer: I used django's default User model from django.contrib.auth.models import User class UserRegisterSerializer(serializers.ModelSerializer): password2 = serializers.CharField( style={'input_type': 'password'}) class Meta: model = User fields = ["username", "email", "password", "password2"] extra_kwargs = { 'password': {'write_only': True}, 'password2': {'write_only': True} } def validate(self, data): password = data.get('password') password2 = data.pop('password2') if len(str(password)) < 5: raise serializers.ValidationError("Password is too short.") if password != password2: raise serializers.ValidationError("Passwords don't match.") return data def create(self, validated_data): username = validated_data.get('username') email = validated_data.get('email') password = validated_data.get('password') user = User.objects.create_user(username=username, email=email, password=password) if user and user.is_active: return user Action: export const register = ({ username, password, password2, email }) => dispatch => { const config = { headers: { 'Content-Type': … -
Set nginx proxy for react multi-stage build with docker compose
I am - once again - very confused, with nginx, docker and react. Here is what is what I want: 1.) a Django REST api that exposes a port only locally 2.) I want the staticfiles of the REST api handled by nginx 3.) a ReactJS front end that is served via nginx on port 80 (I dont know if it is nessesary to serve react via nginx - but I've heard it reduces image size). The problem: It does not work. All containers can run individually but serving React via nginx as well as the restAPI goes over my head. What I saw is that the image I am layering in reactJS "tiangolo/node-frontend:10" also copies a nginx.conf file that may overwrite mine? Can somebody tell me wether or not I am completely on the wrong path here? Using a million tutorials, I am here: nginx.conf upstream website_rest { server restapi:8000; } upstream website_frontend { server frontend:8080; } server { listen 80; location /rest_call/ { proxy_pass http://website_rest; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location / { proxy_pass http://frontend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /rest_call/staticfiles/ { alias /usr/src/website-dj/staticfiles/; } } This is the … -
How to save a Mode Form with MultiSelectCheckBox?
I am trying to save a form including various fields such as many-to-one relationship and MultiSelectCheckBox as follows: Model: class master(models.Model): id_numb=models.CharField(max_length=40,unique=True) gender=models.CharField(max_length=6) name=models.CharField(max_length=100) family_name=models.CharField(max_length=100) birth_date=models.DateField() nation_id=models.IntegerField(blank=True, null=True) id_code=models.IntegerField(blank=True, null=True) education=models.CharField(max_length=100, blank=True, null=True) job=models.CharField(max_length=100, blank=True, null=True) marriage_state=models.CharField(max_length=6, blank=True, null=True) comm=models.CharField(max_length=100, blank=True, null=True) mobile=models.IntegerField(blank=True, null=True) phone=models.IntegerField(blank=True, null=True) email=models.EmailField(blank=True, null=True) address=models.CharField(max_length=200, blank=True, null=True) def __str__(self): return (self.name +" "+ self.family_name) class kelas(models.Model): master=models.ForeignKey(master,on_delete=models.CASCADE,blank=True, null=True) kelas_no=models.CharField(max_length=40,unique=True) start_date_c=models.DateField(blank=True,null=True) finish_date_c=models.DateField(blank=True,null=True) day_no=models.CharField(max_length=200,blank=True,null=True) View: def courseregister(request): if request.method=="POST": form=CourseForm(request.POST) courses=kelas.objects.all() if form.is_valid(): try: form.save() form=CourseForm() #return redirect("/show") except: pass else: form=CourseForm() courses=kelas.objects.all() return render(request, 'music/course.html', {'form':form,'courses':courses}) Form: class CourseForm(forms.ModelForm): days=( ('1','Sa'), ('2','Su'), ('3','Mo'), ('4','Tu'), ('5','We'), ('6','Th'), ('7','Fr'), ) day_no=forms.ChoiceField(choices=days, widget=forms.CheckboxSelectMultiple()) class Meta: model = kelas fields = "__all__" def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control myinputbox' }) self.fields['day_no'].widget.attrs.update({'class': 'form-check-input'}) Data in model "Kelas" doesn't save. where is my fault? I review many times, but i could find anything. thanks in advance for your help. -
How to handle foreign keys with Django Rest Framework
I'm struggling to make my API work, the tutorials are quite tricky about this part. I want to have a '/comments/' POST request with body {movie_id: 1, content="Some comment") and connect it to some Movie. In serializer I'm getting: {'movie': [ErrorDetail(string='This field is required.', code='required')]} How can I map movie_id to movie? By the way, I can change the name to movie if this would be easier. Models.py: from django.db import models from django.utils import timezone class Movie(models.Model): title = models.CharField(max_length=200) year = models.IntegerField() class Comment(models.Model): content = models.TextField(max_length=300) publish_date = models.DateField(default=timezone.now()) movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='movie_id') serializers.py: class MovieSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Movie fields = '__all__' class CommentSerializer(serializers.HyperlinkedModelSerializer): movie_id = serializers.PrimaryKeyRelatedField(many=False, read_only=True) class Meta: model = Comment fields = '__all__' views.py (for Comment, Movie works fine): from .models import Movie, Comment from rest_framework import viewsets, status from rest_framework.response import Response from .serializers import MovieSerializer, CommentSerializer class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer def create(self, request, *args, **kwargs): serializer = CommentSerializer(data=request.data, context={'request': request}) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)