Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django RegexValidator causing AttributeError in Django Admin
I'm using a RegexValidator pretty simply in my User Model: name_regex = RegexValidator(r"^[a-zA-Z0-9\s_]*$") name = models.CharField( _("Name"), default=generate_default_name, max_length=constants.USER_NAME_MAX_LENGTH, help_text=_("The user's display name."), validators=[name_regex], ) But when I use the standard Django UserAdmin I get this error whenever I try to save any field which confuses me greatly: 'RegexValidator' object has no attribute 'search' I don't do anything with search, nor do I reference RegexValidator at all in my standard instantiation of the userAdmin. admin.site.register(User, UserAdmin) Any ideas? -
django User.objects.create() is throwing error
here is the view to signup a user: @api_view(['POST']) def registerUser(request): # data is successfully passed from client data=request.data print("register data", data) try: print(data['name']) print(data['email']) print(make_password(data['password'])) # Everything prints so far but nothing after here user = User.objects.create( first_name=data['name'], username=data['email'], email=data['email'], password=make_password(data['password']) ) print("userrrrrrr",user) # serializer=UserSerializerWithToken(user, many=False) # dont login the user message={"detail":"Successfully registered"} # return Response(serializer.data) # I just want to send a simple message return Response(message) except: message={'detail':"User with this email already exists"} return Response(message, status=status.HTTP_400_BAD_REQUEST) I put notes on code. Data is received and I print everything. BUt User.objects.create() is causing an error so except block gets executed and i am getting error. I also tried User.objects.create_user() but getting same error. User.objects.create( first_name=data['name'], username=data['email'], email=data['email'], password=make_password(data['password']) ) -
Disable Bootstrap warnings from Django Compressor
Is there any way to disable warnings from Django compressor when compressing files? Currently when I'm compressing the files I get a lot of warnings like this: WARNING: The `make-container-max-widths` mixin has been deprecated as of v4.5.2. It will be removed entirely in v5. We're statically hosting Bootstrap, so I don't really care about those messages. I'd really just like them not to show up. -
How to make a chart from uploaded JSON file on webpage?
I have looked at options such as Google Charts, Charts.JS, Pandas, Any chart, etc, but I still feel a little stumped on direction to go forward. I want the chart to grab files saved on the admin side with url: http://127.0.0.1:8000/admin/infographicsite/filesupload/ and make a graph based on any JSON file uploaded to the webapp. There's also percentages/calculations done on a separate file that I will also bring in to connect with so graph can correctly represent said percentages. one JSON file that was uploaded looks like this: { "results":[ { "gender":"female", "name":{ "title":"Mrs", "first":"Debra", "last":"Johnston" }, "location":{ "street":{ "number":2192, "name":"Bridge Road" }, "city":"Coventry", "state":"Shropshire", "country":"United Kingdom", "postcode":"YK74 9FX", "coordinates":{ "latitude":"6.6918", "longitude":"111.6380" }, "timezone":{ "offset":"+5:45", "description":"Kathmandu" } }, "email":"debra.johnston@example.com", "login":{ "uuid":"475c314c-bd42-49b5-b81c-8016ddb1b5e3", "username":"smallleopard142", "password":"beach", "salt":"YqjLSvmF", "md5":"26436a12fdaa430eebb3c39236554b4f", "sha1":"cc972754b8164c7e48dab2e01ef2c107d110006b", "sha256":"8015b915af908793db031cd3e27a67883f0aeb674777fdc8b6226352155b57b4" }, "dob":{ "date":"1949-12-12T14:53:42.446Z", "age":72 }, "registered":{ "date":"2009-10-04T09:05:27.022Z", "age":12 }, "phone":"017687 39061", "cell":"0752-951-872", "id":{ "name":"NINO", "value":"ZT 33 57 79 M" }, "picture":{ "large":"https://randomuser.me/api/portraits/women/84.jpg", "medium":"https://randomuser.me/api/portraits/med/women/84.jpg", "thumbnail":"https://randomuser.me/api/portraits/thumb/women/84.jpg" }, "nat":"GB" }, { "gender":"female", "name":{ "title":"Miss", "first":"Gül", "last":"Türkyılmaz" }, "location":{ "street":{ "number":3425, "name":"Filistin Cd" }, "city":"Kilis", "state":"Antalya", "country":"Turkey", "postcode":32073, "coordinates":{ "latitude":"-15.1737", "longitude":"14.2954" }, "timezone":{ "offset":"-11:00", "description":"Midway Island, Samoa" } }, "email":"gul.turkyilmaz@example.com", "login":{ "uuid":"257f4418-270d-4002-9e84-6e33d9e82a71", "username":"smallpeacock303", "password":"ashley", "salt":"HegxAbaa", "md5":"b5a339d4d6eb3eebe51c437b99ab82ae", "sha1":"aebe19b90d0bc7701fc93ebeb9b251c90d31d08d", "sha256":"c871b4709aa301bf1cf09de5296ad96813a8818e3362860a6b260103502844e5" }, "dob":{ "date":"1993-03-08T17:29:09.139Z", "age":28 }, "registered":{ "date":"2003-02-02T01:58:10.729Z", "age":18 }, "phone":"(324)-499-6198", … -
Django Form after redirect is empty after successfully submitting a form
I have a template called courses for the url http://127.0.0.1:8000/gradebook/courses/. This template lists existing Course objects loads the CourseForm form. The form successfully creates new objects. If I go to the addassessment template with url http://127.0.0.1:8000/gradebook/addassessment/7/, it correctly loads the AssessmentForm. I want to submit this form and then return to the previous courses template. The AssessmentForm submits and the object is saved, but when it redirects back to the courses template, the CourseForm does not load. The courses template loads, the expect html loads correctly other than the form fields. I notice that the url for this page is still http://127.0.0.1:8000/gradebook/addassessment/7/ and not ../gradebook/courses/. app_name = 'gradebook' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('signup/', SignUpView.as_view(), name='signup'), path('courses/', views.courses, name='courses'), path('classroom/', views.classroom, name='classroom'), path('objective/<int:course_id>/', views.addobjective, name='addobjective'), path('addassessment/<int:course_id>/', views.addassessment, name='addassessment'), ] #urls.py project urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('admin/', admin.site.urls), path('gradebook/', include('gradebook.urls')), path('gradebook/', include('django.contrib.auth.urls')), ] #models.py class Course(models.Model): course_name = models.CharField(max_length=10) class Classroom(models.Model): classroom_name = models.CharField(max_length=10) course = models.ForeignKey(Course, on_delete=models.CASCADE) class Assessment(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) assessment_name = models.CharField(max_length=10) objectives = models.ManyToManyField('Objective') class Objective(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) objective_name = models.CharField(max_length=10) objective_description = models.CharField(max_length=30) #views.py def courses(request): course_list = Course.objects.order_by('course_name') context = {'course_list': course_list} if request.method == 'POST': details = … -
Django prefetch taking lot of time when accessing result the first time
I have Rule, Condition and Action models. A rule can have conditions and actions. Rule ->condition and rule->action are represented by many to many relationships class Condition(models.Model): id = models.BigAutoField(primary_key=True) rule_var = models.CharField(null=False, max_length=30) rule_var_type = models.CharField(choices=RuleVarType.choices, max_length=30) rule_operator = models.CharField(choices=Operator.choices, max_length=30) rule_value = models.CharField(null=False, max_length=100) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(default=timezone.now) class Meta: indexes = [models.Index(fields=["rule_var"])] class Action(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(null=False, max_length=30) label = models.CharField(null=False, max_length=60) params = models.JSONField(null=False) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(default=timezone.now) class Meta: indexes = [models.Index(fields=["label"]), models.Index(fields=["name"])] class Rule(models.Model): id = models.BigAutoField(primary_key=True) system = models.CharField(choices=System.choices, max_length=30) type = models.CharField(choices=Type.choices, max_length=30) expires_on = models.DateTimeField(default=timezone.now) created_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(default=timezone.now) conditions_any = models.ManyToManyField(Condition, related_name="condition_any") actions = models.ManyToManyField(Action) class Meta: indexes = [ models.Index(fields=["system", "expires_on", "type",]), ] When i am trying to get rules and associated conditions and actions using prefetch as below , rules = Rule.objects.filter( system=system, expires_on__gte=timezone.now() ).prefetch_related( Prefetch( "conditions_any", queryset=Condition.objects.only( "id", "rule_var", "rule_var_type", "rule_operator", "rule_value" ), to_attr="any_conditions", ) Prefetch( "actions", queryset=Action.objects.only("id", "name", "label", "params"), to_attr="related_actions", ), ) for rule in rules: for condition in rule.any_conditions: #do something for condition in rule.any_conditions: #do something i face the following issue. The debug logs for the db query points out that the prefetch queries … -
Pandas and confusion over passing by value and passing by reference
A function returns a Pandas DataFrame. I try to create a new DataFrame with "newFrame = myFunction()". But the newFrame variable acts more like a reference than a distinct object. Can you help? In these snippets, FrameMaker.py updates a DataFrame object on a timer. It has a function get_frame that returns that DataFrame object. Multiple scripts call that function to get a copy of the DataFrame. GetFrameData.py is an example. It calls the get_frame function and assigns the returned value to a variable. It should then have its own copy of the DataFrame, and anything it does to its copy of the DataFrame should have no effect on any other copies. But it does cause an effect. GetFrameData.py drops columns from the DataFrame. The first time that runs, the "values.drop" line runs successfully. The second time it runs, it gives an error that the DataFrame doesn't have the columns in question. It's like the 'values' variable is a reference to the DataFrame in FrameMaker.py, not a distinct object in the GetFrameData stack. Kind of like how Strings function in most languages. How should I change my code to get a copy of the DataFrame object, not a reference? FrameMaker.py def … -
Having Trouble Creating Nested LISP-Style List in Python
I have a list of functions and values I'd like to put into a nested list. I'd like the result to be a LISP style list(something that looks close to some LISP style executable code) that I can easily process later. This list comes from a "sentence", that gets split into a list by word - it keeps defined phrases (multi word) together, by checking any multi-word tokens in the DB first, gluing them and then separating them later. Any words not in the database are ignored. Punctuation is also ignored. It just matches actual stored Tokens. This lets me write a sentence that can get translated into functions I can process later. We can ignore the fact that these are functions, and just think of them as strings, since that's how they're stored, but functions and arguments describe the use case perfectly, since that's what they are. Functions will be the first item in a list, followed by their arguments in the same list. A function with no arguments will be in a list with only that one element. An argument that is itself a function will be in a list(with it's arguments, if any). The number of arguments … -
Django convert pdf to image
I'm receiving a PDF via form post and before uploading it into my models, I would like to convert it to an image (I'm using the library pdf2image). I'm able to work with a temporary file of the PDF and convert it to an image but I haven't been able to save the image into my models. Any idea?? Here's what I've got so far. Models.py class Files(models.Model): archivo = models.FileField(upload_to='pdf/') Views.py def converter(request): if request.method == 'POST': form = UploadFilesForm(request.POST ,request.FILES ) if form.is_valid(): #new_pdf = Files(archivo = request.FILES['archivo']) new_pdf = request.FILES['archivo'] path = default_storage.save("file.pdf", ContentFile(new_pdf.read())) path = settings.MEDIA_ROOT + '/' + "file.pdf" images = convert_from_path(path,fmt='png',dpi=300,grayscale=True) image = images[0] image.save("imagen.png") else: form = UploadFilesForm() context = {'form':form} return render(request, 'converter.html',context) -
Django form is not creating new entries
I have the following form to create new clients on a database on Django and rendered using crispyforms. However, even thoug it is rendered correctly, it's not creating new entries. models.py class Client (models.Model): def __str__(self): return self.name + ' '+ self.surname name = models.CharField(max_length=120) surname = models.CharField(max_length=120, null=True) phone = models.PositiveIntegerField(null=True) mail = models.EmailField(null=True) sport = models.TextField(blank=True, null=True) gender_options=( ("F", "femenino"), ("M", "masculino"), ) gender = models.CharField(max_length=120, null=True, choices=gender_options) birth = models.DateField(null=True) def get_absolute_url(self): return reverse("clientes:cliente", kwargs={"client_id": self.id}) pass forms.py from django import forms from .models import Client class NewClientForm(forms.Form): name = forms.CharField(label='Nombres') surname = forms.CharField(label='Apellidos') phone = forms.CharField(label='Teléfono') mail = forms.EmailField(label='Correo electrónico') gender = forms.ChoiceField(label='Género', choices= Client.gender_options) birth = forms.DateField(label='Fecha de nacimiento', widget=forms.TextInput(attrs={ 'id': "datepicker", })) sport = forms.CharField(label='Deportes') views.py def new_client_view(request): new_client_form = NewClientForm() if request.method == "POST": new_client_form = NewClientForm(request.POST) if new_client_form.is_valid(): Client.objects.create(**new_client_form.cleaned_data) else: print(new_client_form.errors) context = { "form": new_client_form } return render (request, 'clients/new-client.html', context) html {% extends 'base.html' %} {% load bootstrap4 %} {% load crispy_forms_tags %} {% block content %} <h1>Nuevo cliente</h1> <section class="container"> <form action="." method="POST" class="form-floating mb-3"> {%csrf_token%} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.name|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.surname|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ … -
Django Page not found Request Method: GET
I can't seem to figure out why my page can't be found. All the others previous ones are written exactly the same way. Why is this happening? VIEWS: def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logg:topic', topic_id=topic_id) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) URLS: app_name = "learning_logg" urlpatterns = [ #Home Page path('', views.index, name="index"), path('topics/', views.topics, name="topics"), path('topics/<int:topic_id>/', views.topics, name="topics"), path('new_topic/', views.new_topic, name='new_topic'), path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), ] NEW_ENTRY.HTML: {% extends "learning_logs/base.html" %} {% block content %} <p>Add a new entry:</p> <form action="{% url 'learning_logg:new_entry' topic.id %}" method='post'> {% csrf_token %} {{ form.as_pp }} <button name='submit'>Add entry</button> </form> <p><a> href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p> {% endblock content %} -
sort element when clicking on a button in django
i want to sort my items when clicking on a button i already did the search function in my list view like that: search_input = self.request.GET.get('search-area') or '' if search_input: context['tasks']=context['tasks'].filter(day="sunday") i want to get all the items which their attribute day is equal to "sunday" in my template i tried this: <form method="GET" style ="margin-top: 20px ; display : flex"> <input type="text" name="search-area" value="{{search_input}}"> <input class ="button" type="submit" value='Search'> </form> but the problem is that i need to write somthing to have the result, i just tried to do it with a form because this the solution that i found in internt but i want to do it just with a button -
Syncing Django Models with Overriden Save Method
I have a client and a user model. Both client and user have a flag called help_desk. The help desk clients and users are to be kept in sync. This means that: When user is marked as help_desk they are added to all help desk clients When user is unmarked as help_desk they are removed from all help desk clients When a client is marked as help_desk all help desk users added to it When a client is unmarked as help_desk all help desk users are removed from it I've been trying to solve this by overriding the save() method with the following: Client def save(self, *args, **kwargs): help_desk_users = get_user_model().objects.filter(is_help_desk=True) if self.help_desk: for user in help_desk_users: self.users.add(user) else: for user in self.users.all(): if user in help_desk_users: self.users.remove(user) super().save(*args, **kwargs) User def save(self, *args, **kwargs): if self.is_help_desk: for client in Client.objects.filter(help_desk=True): client.users.add(self) else: for client in Client.objects.filter(help_desk=True): client.users.remove(self) super().save(*args, **kwargs) The user code is working as expected but the client code is not. I think the reason is because you are unable to bulk update in an overriden save method - see docs. My question is, is this simply a limitation of Django? And if so, what are the best … -
Django json field sorting on first ip address
I have a model which stores ip addresses in json field: class UserIP(models.Model): name = models.TextField() ip_addresses = JsonField() Data looks something like this, UserIP.objects.filter(id__gt=100).values('ip_addresses') <QuerySet [{'ip_addresses': {'172.19.128.1': 1, '192.168.0.129': 1}}, {'ip_addresses': {'10.248.91.72': 1, '10.248.91.73': 1, '10.248.91.74': 1}}, {'ip_addresses': {'1.1.34.13': 1}}]> In output I need to sort the data based on first ip address in each record. So the ideal order should be, 1.1.34.13 10.248.91.72 172.19.128.1 When I do normal Django sorting it prints in order as below, UserIP.objects.filter(id__gt=100).values('ip_addresses').order_by('ip_addresses') 1.1.34.13 172.19.128.1 10.248.91.72 Please advice what would be the solution. -
Django Save Image In Different Formats Using Pillow
I have this site I am making for my school and I need to optimize it, like a lot. So I decided to serve all my images compressed and in next-gen formats like jpeg-2000 and webp. Using Pillow, this is what I have so far: class Bulletin(models.Model): banner = models.ImageField(upload_to='banner/', blank=True) def save(self, *args, **kwargs): super().save() if self.banner: image = Image.open(self.banner.path) resized = image.resize((1600, 900)) resized.save(self.banner.path, quality=50) So I think that this compresses the image (plz tell me if I made mistake with code above). So now I want to be able to save this image in multiple formats I want the one uploaded image to be saved in these formats: webp jpeg2000 jpeg I am thinking of creating more fields on my model banner, like the field banner_webp, and then I would just convert it to webp and during save I would save the converted image to that field. The problem is that I don’t know how to convert image using Pillow, or how to do what I am asking. Thanks for help. -
Show a field data into header section of a pdf file
I am quite new to using this library call Django Reportlab where I'd like to show "supplier" details into the header section of the pdf file. Here is the code def generate_pdf(request): pdf_buffer = BytesIO() doc = SimpleDocTemplate(pdf_buffer, pagesize=landscape(letter)) styles = getSampleStyleSheet() elements = [] paragraph_text = 'Victorious Step Sdn.Bhd. (667833-T)' columns = [ {'title': 'Date', 'field': 'created_date'}, {'title': 'Part No', 'field': 'partno'}, {'title': 'Supplier Name', 'field': 'supplier'}, {'title': 'Status', 'field': 'limit'}, ] table_data = [[col['title'] for col in columns]] orders = Order.objects.all() for tr in orders: table_row = [str(tr.created_date.strftime("%d-%m-%Y")), tr.part.partno, tr.supplier] table_data.append(table_row) table = Table(table_data, repeatRows=1, colWidths=[doc.width / 7.0] * 7) table.setStyle(TableStyle([ ('BOX', (0, 0), (-1, -1), 0.20, colors.dimgrey), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, -1), 10), ])) elements.append(table) elements.append(Spacer(1, 50)) doc.build(elements) pdf = pdf_buffer.getvalue() pdf_buffer.close() response.write(pdf) return response I am trying to show the supplier data after the paragraph_text = 'Victorious Step Sdn.Bhd. (667833-T)' . Can anyone assist me with how to do that? Thanks in advance. -
Record user's voice and save it to db in Django
I want to build a Django app in which a user can record his/her voice. I have used the following link: https://github.com/Stephino/stephino.github.io/blob/master/tutorials/B3wWIsNHPk4/index.html in order to capture user's voice and it works perfectly for me, but I do not know exactly how to save it to database. I do not know how to build my Model and also a form to do this. Does anybody have any idea? (The obligatory framework is Django and in terms of db my preference is Postgresql) -
Django model abstract model with constrains not being inherited: 'constraints' refers to field 'xxx' which is not local to model 'Foo'
I am using Django 3.2 I have come across a strange behaviour which appears to be a bug; Fields used in constraints defined in a ABC are not inherited by child classes. myapp/models.py class BaseFoo(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,related_name='%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE,related_name='%(class)s') created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True constraints = [ models.UniqueConstraint(fields=['content_object', 'user'], name="'%(class)s_unique"), ] class Foo(BaseFoo): class Meta(BaseFoo.Meta): abstract = False No problem when I makemigrations, but, When I attempt to migrate the schema (`python manage.py migrate), I get the following error: myapp.Foo: (models.E016) 'constraints' refers to field 'content_object' which is not local to model 'Foo'. HINT: This issue may be caused by multi-table inheritance. Why is Foo not inheriting the fields clearly defined in the parent ABC? - and how do I fix this (assuming it's not a bug)? -
Django - how to change view based on option chosen in select dropdown from template
I am attempting to display a graph that is responsive to an option chosen by the user from a select form. However, I'm finding that the graph isn't acting responsive when I choose other options besides 'BTC'. relevant main.HTML: <div class = "container"> <form method = "POST" action = ""> <select name = "coin-select"> {% for coin in coin_lst %} <option value="{{ coin }}">{{ coin }}</option> {% endfor %} </select> </form> </div> <div class = "container"> {% autoescape off %} {{ graph }} {% endautoescape %} </div> relevent view.py: def initial_data(request): coin_lst = [] for x in focused_df.coin: if x not in coin_lst: coin_lst.append(x) def close_vs_redditComments(): if request.method == 'POST': coin = str(request.POST.get("coin-select")) else: coin = 'BTC' closeVSredditComment = make_subplots(specs=[[{"secondary_y": True}]]) closeVSredditComment.add_trace(go.Scatter(x = df[df.coin == coin]['time'], y = df[df.coin == coin]['close'], name = "closing price"), secondary_y = False) closeVSredditComment.add_trace(go.Scatter(x = df[df.coin == coin]['time'], y = df[df.coin == coin]['reddit_comments'], name = "reddit comment volume"), secondary_y = True) return(plot(closeVSredditComment, output_type = 'div')) context = { 'coin_lst': coin_lst, 'graph': close_vs_redditComments() } return render(request, 'main.html', context) What am I missing here? -
Possibility to display current partner.id in odoo view
I want to get the current partner's id in my stock.picking view. I foud something like this <field name="myId" domain="[('partner_id','=',id)]" /> but it's wrong.Is it even possible to have the current partner's id? -
Django access html info from form post method
this is my first Django Project so I just wanted to know if what I want to do is viable. I have an html with two fors right now and other additional info In Form1, it calls ajax method to populate the list of products that is included in Form2. What I want to do is in Form2 (this form contains the product list, the Unidades input and the button) post method, get the fields that are in red (they are not inside Form2) Is there a way to achieve this? Or the only way is to put this fields inside Form2. I also attach mi post method, keyinvoice number is the first field in red section im trying to get but obviously brings a None class CurrentSaleAddProduct(LoginRequiredMixin, View): login_url = reverse_lazy('users_app:user-login') def post(self, request, *args, **kwargs): productselect = self.request.POST.getlist('productselect') keyunits = self.request.POST.get("keyunits", None) keyinvoicenumber = self.request.POST.get("invoice_number", None) print(keyinvoicenumber) for p in productselect: product_selected = Product.objects.search_id(p) stock_product_selected = Stock.objects.search_id(p) obj, created = CurrentSaleItems.objects.get_or_create( product=product_selected, defaults={ 'count': Decimal(keyunits), 'total': Decimal(keyunits)*stock_product_selected.price_sale }) if not created: obj.count = obj.count + Decimal(keyunits) obj.total = obj.total + \ Decimal(keyunits)*stock_product_selected.price_sale obj.save() """ car = CarShop.objects.get(id=self.kwargs['pk']) if car.count > 1: car.count = car.count - 1 car.save() # … -
Loading Django static files from React component
I am fairly new to React/Django/web development in general. I know there are a lot of questions on SO about how to load static files in Django templates, but I couldn't find anything helpful on how to do this in React components. Scenario: I am building a React-Django app, and one of the features is to render a PDF document based on some user input. I am able to render the pdf successfully with react-pdf if the file is stored somewhere in the react app's source tree. However, I want to serve these pdf files from the backend. Currently, I have a Django model with a FilePathField that points to where these pdfs are on my filesystem. What is the best practice for using this file path to render the pdf in React? Also, is this approach even correct? -
Django : donwloading server files on client side
I am running a Django project on a company server also that stores some .pdf and .docx files. Only workers have acces to this Django app throught their local machines and they need to download files from the server to their machines. I used webbrowser open, but files were opened on server machine in stead of clients one. Can you please help me with this issue? Thanks! -
How can i make 2 attributes unique in a table (Django)
It is possible to have a unique row, and make create_or_update on it? image: I want to have unique attributes for idTest + EmailStudent -
Reverse for 'order_successful' with no arguments not found despite sending an argument. DJANGO
I am new to django. I am making a website for a customer. I am integrating a paypal client side module and followed a video from youtube for the purpose. On order completion, I am trying to go to a page and I am passing it product id so it can retrieve it from the database and display a nice thank you page. But I am getting the following error: NoReverseMatch at /product-details/payment Reverse for 'order_successful' with no arguments not found. 1 pattern(s) tried: ['order_success/(?P[^/]+)$'] Following is my page checkout.html from where I am calling the function: <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = '{{price}}' var quantityBought = '{{quant}}' var prodId = '{{prod.id}}' var fName = '{{firstName}}' var lName = '{{lastName}}' var apt = '{{apt}}' var street = '{{street}}' var city = '{{city}}' var …