Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to make a staff user by default
I am making a library system with signup pages (admin and user), so when I make an admin user I want to make it in staff, so how can I use (is_staff)? this is my registration function... def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account created successfully') return redirect(loginpage) context = {'form':form} return render(request, 'pages/register.html', context) -
Detail view context
how can i get all images of item into context i tried {% for image in item.images.all %} in template but it doesn't work. i dunno how to filter it , ty for ur answer models class Item(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/', null=True) size = ArrayField(models.CharField(max_length=255)) price = models.PositiveIntegerField() on_sale = models.BooleanField(default=0) discount = models.PositiveIntegerField(null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('single_product', kwargs={'slug': self.slug}) def get_sale(self): price = int(self.price * (100 - self.discount) / 100) return price class ItemImage(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, related_name='images') images = models.ImageField(upload_to='photos/%Y/%m/%d/', null=True) def __str__(self): return self.item.name views class ItemDetail(DetailView): model = Item context_object_name = 'item' template_name = 'essense/single-product-details.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) -
urlpatterns conflict <str:username>/
I have a problem with url paths. As I understand the path users/ is perceived as <str: username>/ named users. Is it possible to solve this problem without creating a new application? urlpatterns=[ path('',PostList.as_view(), name='index'), path('<str:username>/new/',News.as_view(), name='new'), path('<str:username>/', user_posts, name='profile'), path('<str:username>/<int:post_id>/', post_view, name='tak'), path('<str:username>/<int:post_id>/add_comment/', comment_add, name='add_comment'), path('<str:username>/<int:post_id>/edit/', Update.as_view(), name='edit'), path('users/',user_list,name='user_list'), path('users/<str:username>/',user_detail,name='user_detail'), ] -
django-xlwt ['“download” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
i'm trying to export some data from database , i've used xlwt package , my python version is 3.7.0 it seems xlwt doesnt support python 3.7 !?and my django version is 3.2 class Post(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) title= models.CharField(max_length=80) date = models.DateTimeField(auto_now_add=True) my views to download the data def daily_download(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{0}".xls'.format( timezone.datetime.now().strftime('%Y%m%d')) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('vistors') row_num = 0 font_tyle = xlwt.XFStyle() font_tyle.font.bold = True columns = ['user','date','title'] for col_num in range(len(columns)): ws.write(row_num,col_num,columns[col_num],font_tyle) font_tyle = xlwt.XFStyle() rows = Vistor.objects.all().values_list('admin__username','date','title') for row in rows: row_num +=1 for col_num in range(len(row)): ws.write(row_num,col_num,str(row[col_num]),font_tyle) wb.save(response) return response but it raise this error ['“download” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] i also changed file name to a simple string but doesnt work , is there something else i should change please ?! or any other method to achieve it if xlwt expired -
Can Peewee use highlight(), which is SQLite's FTS5 (full text search) auxiliary function?
SQLite's FTS5 supports highlight(). That auxiliary function returns tags for results from full text search queries: see the official documentation. Peewee's code on Github, in the <sqlite_ext.py> module also mentions highlight(), although in passing. Built-in auxiliary functions: bm25(tbl[, weight_0, ... weight_n]) highlight(tbl, col_idx, prefix, suffix) snippet(tbl, col_idx, prefix, suffix, ?, max_tokens) I've found no example code in Peewee's documentation or reference to highlight(), even though Peewee already has support for bm25() and rank() as present FTS5 auxiliary functions. Unless I've missed something, how do I use FTS5 highlight() with Peewee in my Python code? (I'm using Django, if that matters.) -
why are styles not getting applied to Django URLField
I have a model for the profile in it there are different fields like CharField and also URLField but on the page, the styles are getting applied to the input of other fields but are not getting applied to the input of URLField here is my models.py: and here is my forms.py: class ProfileForm(ModelForm): class Meta: model = Profile fields = [ "name", "email", "username", "location", "bio", "short_intro", "profile_image", "social_github", "social_twitter", "social_linkedin", "social_youtube", "social_website", ] def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({"class": "input"}) and here is my HTML: {% extends 'main.html' %} {% block content %} <!-- Main Section --> <main class="formPage my-xl"> <div class="content-box"> <div class="formWrapper"> <a class="backButton" href="{% url 'account' %}"><i class="im im-angle-left"></i></a> <br> <form action="{% url 'edit-account' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input class="btn btn--sub btn--lg my-md" type="submit" value="Submit" /> </form> </div> </div> </main> {% endblock %} and here is an example of gif of what's happening: -
Django Query - Annotate With Boolean Value From Date Comparison
I want to write a query which will have an annotation of expired based on a comparison of a date in the model and the date/time of now and receive a boolean value depending on the outcome. I can't find how this is done. I have tried the below so far: .annotate(expired=F( F('date_updated') > datetime_now)) Can someone let me know the way to achive this? -
How use vanilla JavaScript to add ajax request on Django instead of Jquery
All tutorials cover the implementation of AJAX in Django only using the JQuery library. $.ajax({ url: form.attr("data-validate-username-url"), data: form.serialize(), dataType: 'json', success: function (data) { if (data.is_taken) { alert(data.error_message); } } }); But I want to use the vanilla JavaScript to handle everything, anyway to do that? -
Django-import-export doesn't skip unchanged when skip_unchanged==True
I'm building an app using Django, and I want to import data from an Excel file using django-import-export. When importing data I want to skip unchanged rows, for this, I'm using skip_unchanged = True in the resource class (like below) but I get unexpected behavior. In my model, I have an attribute updated_at which is a DateTimeField with auto_now=True attribute, it takes a new value each time I upload the Excel file even if the values of rows have not changed in the file. Below are portions of my code. models.py class HREmployee(models.Model): code = models.IntegerField() name_en = models.CharField(max_length=55) status = models.CharField(max_length=75) # IH in HR file # other fields to be imported from the file ... # fields that I want to use for some purposes (not imported from the file) comment = models.TextField() updated_at = models.DateTimeField(auto_now=True) resources.py class HREmployeeResource(ModelResource): code = Field(attribute='code', column_name='Employee Code') name_en = Field(attribute='name_en', column_name='Employee Name - English') status = Field(attribute='status', column_name='Employee Status') # other fields to be imported ... class Meta: model = HREmployee import_id_fields = ('code', ) skip_unchanged = True So, can anyone help me to fix this unexpected behavior, please? -
django to find static css files for my HTML page
I'm trying to reach some of my css files but I can't seem to get the directory right. For example I have a link in my home.html: <link href="assets/plugins/revo-slider/css/settings.css" rel="stylesheet" type="text/css"/> I've converted it to: <link href="{% 'assets/plugins/revo-slider/css/settings.css' %}" rel="stylesheet" type="text/css"/> But that's the incorrect directory because I recently moved the file to where it is now as shown below. my folder structure is as follows: project/ ├────── Index/ │ ├──_static/ │ │ ├── css/ (.css files) │ │ ├── js/ (javascript files) │ │ ├── img/ (images files) │ │ ├── media/ (video files) │ │ └── plugins/ (.css plugin files) │ │ │ └── templates/ │ └── index/ │ ├── home.html │ └── about.html ├── manage.py └── project folder with settings.py,url.py my settings.py includes: line 5: BASE_DIR = Path(__file__).resolve().parent.parent line 90: STATICFILES_DIRS = [ "/index/static", ] I've checked the similar questions and youtube tutorials but I've seen some which suggested I add: os.path.join(BASE_DIR, 'static') in line 91 but i've seen conflicting codes through Youtube tutorials, first step is getting the directory right in my html though, if anyone can help it'd be great -
I dont know if i should use models.Foreignkey or just Charfield to store oauth token
I need to store the username and twitter token when he/she logs in and then later use it for whatever purpose, should i use FK for the twiter token field? -
How to filter not only by outerref id in a subquery?
I have a problem with filtering by boolean field in a subquery. For example, I have two models: Good and Order. class Good(models.Model): objects = GoodQuerySet.as_manager() class Order(models.Model): good = models.FK(Good, related_name="orders") is_completed = models.BooleanField(default=False) I want to calculate how many completed orders has each good. I implemented a method in Good's manager: class GoodQuerySet(models.QuerySet): def completed_orders_count(self): subquery = Subquery( Order.objects.filter(good_id=OuterRef("id")) .order_by() .values("good_id") .annotate(c=Count("*")) .values("c") ) return self.annotate(completed_orders_count=Coalesce(subquery, 0)) This method counts all existing orders for a good, but it works when I call it like this: Good.objects.completed_orders_count().first().completed_orders_count To get the correct value of completed orders I tried to add filter is_completed=True. The final version looks like this: class GoodQuerySet(models.QuerySet): def completed_orders_count(self): subquery = Subquery( Order.objects.filter(good_id=OuterRef("id"), is_completed=True) .order_by() .values("good_id") .annotate(c=Count("*")) .values("c") ) return self.annotate(completed_orders_count=Coalesce(subquery, 0)) If I try to call Good.objects.completed_orders_count().first().completed_orders_count I got an error: django.core.exceptions.FieldError: Expression contains mixed types. You must set output_field. -
Ability to find certain pages through search
I want to have a search bar that search all the views that are static and supplies search results for example this page here has the function I need: https://cagenix.com/ . If you click the magnifying glass it opens a search bar and allows you to search all their static pages and supplies the user with results. Is there any way to do this in Django views? -
Django Rest Framework Grouping results by Foreign Key value
I am trying to do a child list model. This model has parent foreign key and child foreign key. What I want to do is to gather the ones with the same parent value under a single group. If the parent 1 has 3 child, the result should look like this: { first_name: "bla bla" last_name: "bla bla" children: [ { first_name: "bla bla"} { first_name: "bla bla"} { first_name: "bla bla"} ] } Is there any way to do this in child list serializer? I just couldn't make it. I want to go to the url address according to the parent value and make a grouping as above. First solution that came to mind is using the related name field. I tried to do this, but I was unsuccessful. I can write similar codes, I have already written for other apps on this project. However, when the subject comes to the list of children, my brain is failing me. I can't find the right thing to do, I can't understand. Models class ChildProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True, verbose_name=AccountStrings.ChildProfileStrings.user_verbose_name, related_name="user_child") city = models.ForeignKey( City, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=AccountStrings.ChildProfileStrings.city_verbose_name, related_name="city_child_profiles") hobbies = models.CharField( max_length=500, null=True, blank=True, verbose_name=AccountStrings.ChildProfileStrings.hobbies_verbose_name) class ParentProfile(models.Model): … -
Blank page on mobile when Debug is off
I built an app on Django & React which displays a blank page on mobile browsers & Safari (desktop) as soon as I set DEBUG=False in my Django settings.py file. I inspected the browser consoles network tab and noticed that Safari seems to be unable to read my react javascript bundle. I inspected the network tab on Safari with both Debug on and off to see if there are any differences in how the file is served and found this: Debug=False (app not loading) As you can see, the response Content-Disposition is telling me that the file's extension is .js.gz - this ends up showing the "corrupted" version of the file which I linked in the first screenshot. Debug=True (app works as expected) When setting debug to true, it loads a different version of the same file. The filename is slightly different and the file extension is .js I use webpack to bundle these files and a package called django-webpack-loader to inject them into my HTML template. Code in settings.py that might be relevant: # django-webpack-loader if DEBUG: WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': '', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 'TIMEOUT': 10, }, } if not DEBUG: WEBPACK_LOADER = { 'DEFAULT': { … -
NameError: name 'appointment' is not defined
My code should Post data into their respective db tables But on Post request I'm getting NameError: name 'appointment' is not defined [18/Jul/2021 12:27:31] "POST /api/appointment/make/ HTTP/1.1" 500 108215 I checked already asked questions like that but I'm unable to reproduce the solution. views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def makeAppointments(request): user = request.user data = request.data membersToHeldMeeting = data['membersToHeldMeeting'] if membersToHeldMeeting and len(membersToHeldMeeting) == 0: return Response({'detail': 'No Appointment Has Been Set'}, status=status.HTTP_400_BAD_REQUEST) else: # (1) Create Appointment createappointment = MakeAppointment.objects.create( user=user, reasonOfAppointment=data['reasonOfAppointment'], meetingWillBeConductedOn=data['meetingWillBeConductedOn'], paymentMethod=data['paymentMethod'], taxPrice=data['taxPrice'], consultancyServiceFee=data['consultancyServiceFee'], totalFee=data['totalFee'] ) # (2) Create AppointmentDetails appointmentdetails = AppointmentDetails.objects.create( appointment=appointment, #error coming from this line,why this is undefined im not able to understand that , appointmentReason=data['appointmentDetails']['appointmentReason'], dateOfBirth=data['appointmentDetails']['dateOfBirth'], gender=data['appointmentDetails']['gender'], maritalStatus=data['appointmentDetails']['maritalStatus'], phoneNumber=data['appointmentDetails']['phoneNumber'], emergencyContactNo=data['appointmentDetails']['emergencyContactNo'], medicalHistory=data['appointmentDetails']['medicalHistory'], previousTreatmentDetails=data['appointmentDetails']['previousTreatmentDetails'], allergicTo=data['appointmentDetails']['allergicTo'], address=data['appointmentDetails']['address'], city=data['appointmentDetails']['city'], postalCode=data['appointmentDetails']['postalCode'], country=data['appointmentDetails']['country'], ) # (3) Create all appointments and set appointment to MembersOfPanelToHeldMeeting relationship for i in membersToHeldMeeting: panelmember = PanelMember.objects.get(_id=i['panelmember']) allmeetings = MembersOfPanelToHeldMeeting.objects.create( panel=panelmember, appointment=appointment, name=panelmember.name, totalFee=i['totalFee'], image=panelmember.image.url, ) serializer = MakeAppointmentSerializer(createappointment, many=False) return Response(serializer.data) Respective Models `models.py` class MakeAppointment(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) reasonOfAppointment = models.TextField(null=True, blank=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) taxPrice = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) consultancyServiceFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) totalFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False) … -
Page not updating after adding image to django admin
I've created a model HomeImage. I have FOR LOOP in my template, where I render images to a page from my database. What I did is that you can add images through admin site and my problem is, that after I add image to admin it doesn't render added image/s. I have to shutdown the running server and run it again to see those images I added. I would like to have my page updated after I add image through admin site. Is there any solution? class HomeImage(models.Model): thumbnail = models.ImageField(upload_to="images/") -
Validate HTML tags if they are valid HTML tag or not python?
I am using Django to build website and I want to check if I am using a valid HTML tag or not. This is my code. class Actions: view_class = None action_name = None action_code = None action_icon = None action_attr = None action_title = "icon" # icon,text ,both with_url = False actions_template = "core/core/actions/action.html" action_css = [] action_js = [] action_class = "btn btn-secondary hide action-item" action_position = "above_form" # above_form, above_grid, both ,on_form , on_grid action_tag = "a" def render_actions(self, request): return render_to_string( self.actions_template, { "action_name": self.action_name, "action_code": self.action_code, "action_icon": self.action_icon, "action_class": self.action_class, "action_title": self.action_title, "action_tag": self.action_tag, "with_url": self.with_url, "action_attr": self.action_attr, "with_modal": self.with_modal, "form_name": form_name, "action_url": reverse_lazy(self._related.__class__.__name__.lower()) if self.with_url else "", }, ) For example if action_tag value is buttun the code should raise error, if action_tag value is button or any valid HTML tag there is no error raised. How can I do this offline not online. -
Unable to send json in ajax to django without jquery
I am trying to use AJAX with Django but without jQuery, almost I am successful in doing so but only urlencoded data can be sent from AJAX to Django and unable to send data in JSON format, but I am able to get a response from Django to AJAX in JSON format too. I have tried a lot as you can see comments in these files: senddata.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Send AJAX data</title> </head> <body> <h2>Send AJAX data by using the button</h2> <button id="btn-submit" class="btn btn-outline-dark">SEND</button> <script> var sendbtn = document.getElementById('btn-submit') sendbtn.addEventListener('click', sendBtnHandler) function sendBtnHandler() { console.log('sendBtn is clicked') const xhr = new XMLHttpRequest() xhr.open('POST', 'http://localhost:8000/contact/send', true) // xhr.getResponseHeader("Content-type", "application/json"); // xhr.getResponseHeader("Content-type", "application/x-www-form-urlencoded"); // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xhr.onprogress = function () { console.log("on progress, wait a while until data is fetched") } xhr.onload = function () { console.log('success') console.log(this.responseText) } let params = `{"name":"mayur90","salary":"12213","age":"23"}` let b = 2 let d = 4 // let params = `a=${b}&c=${d}` xhr.send(params) // xhr.send(b) console.log(params) } </script> <!-- Optional JavaScript; choose one of the two! --> <!-- Option … -
How to set up my Django models for this ManyToMany scenario?
I gather keywords with their monthly values over a period of time. Then I want to relate certain keyword combinations (average the values for example) for certain topics. So here is a basic table structure with some sample data so you can picture what I am dealing with: Table 1 - columns 1,2,3 are "unique together" keyword | location boolean (inUSA true/false) | Date | Value dog | true | 01/01/2020 | 10 dog | true | 02/01/2020 | 20 dog | true | 03/01/2020 | 10 dog | false | 01/01/2020 | 10 cat | false | 01/01/2020 | 10 Table 2 Topic | has many keywords | extra info dogs in USA | should reference 3 entries dogs everywhere | 4 entries dogs and cats outside of USA | 2 entries dogs out of USA | 1 entry cats out of USA | 1 entry Keywords can belong to many topics, topics can have many keywords. Can a simple ManyToMany relationship between 2 models work? Or do I need something more complicated? I tried setting it up with 2 models, but having 3 primary keys for table1 (dog,inUSA,date) gets too complicated and I don't know if Django can … -
Django form field validation not working and no errors
I have a form in Django for which I need to validate the phone number. No validation is taking place after the "next" button is executed. I have made a print to check if validation is called and I can see that it is not called and I have made sure that validators.py is in the same app folder as my form. forms.py from django import forms from .validators import phoneNumberValidation class customerLocalDeliveryForm(forms.Form): customerName = forms.CharField(label = 'Name', max_length=20, required=True) customerEmail = forms.EmailField(label = 'Email', max_length=50, required=True) customerMobile = forms.CharField(label = 'Mobile', max_length = 20, required = True, validators=[phoneNumberValidation]) comments = forms.CharField(label = 'Comments', max_length = 300, widget=forms.Textarea, required = False) deliveryTime = forms.ChoiceField(choices = (), required=True) def __init__(self, *args, **kwargs): self.deliveryTimeList = kwargs.pop('deliveryTimeList') super().__init__(*args, **kwargs) self.fields['deliveryTime'].choices = self.deliveryTimeList In my validators.py which is in the same folder as my form. I have no idea why this validation is not called as I don't see the print in my console when I tested the validation from the webpage. from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ def phoneNumberValidation(value): print('here is the value') print(value) if len(value) <= 7: print('we are here') raise ValidationError(_("The phone number must be 8 digits")) … -
facing problem to push data to backend from local storage in react
I tried alot to fix that but I need little help to figure out what I'm doing wrong. When I make post request POST /api/appointment/make/ Request gets failed with status code 500 Internal Server Error: /api/appointment/make/ Traceback (most recent call last): File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\panel\views\appointment_views.py", line 19, in makeAppointments membersToHeldMeeting = data['membersToHeldMeeting'] KeyError: 'membersToHeldMeeting' [17/Jul/2021 23:52:27] "POST /api/appointment/make/ HTTP/1.1" 500 106441 First take a look at backend urls path('api/appointment/make/', views.makeAppointments, name='appointment-add'), Related view @api_view(['POST']) @permission_classes([IsAuthenticated]) def makeAppointments(request): user = request.user data = request.data membersToHeldMeeting = data['membersToHeldMeeting'] if membersToHeldMeeting and len(membersToHeldMeeting) == 0: return Response({'detail': 'No Appointment Has Been Set'}, status=status.HTTP_400_BAD_REQUEST) else: # (1) Create Appointment createappointment = MakeAppointment.objects.create( user=user, reasonOfAppointment=data['reasonOfAppointment'], meetingWillBeConductedOn=data['meetingWillBeConductedOn'], paymentMethod=data['paymentMethod'], taxPrice=data['taxPrice'], consultancyServiceFee=data['consultancyServiceFee'], totalFee=data['totalFee'] ) # (2) Create … -
how to display all the data from database in django html table
I want to display the data from database using html table in django. im using mysql and already connected to django. here is my view : def table_list(request): tablelst = CompanyRate.objects.all() context = {'tablelst': tablelst} return render(request, 'articleapp/table_list.html', context) Model: class CompanyRate(models.Model): date = models.CharField(max_length=255, blank=True, null=True) notice_name = models.CharField(max_length=255, blank=True, null=True) event = models.CharField(max_length=255, blank=True, null=True) basic_amount = models.CharField(max_length=255, blank=True, null=True) num_of_company = models.CharField(max_length=255, blank=True, null=True) avg_of_1365 = models.CharField(max_length=255, blank=True, null=True) hd_rate = models.CharField(max_length=255, blank=True, null=True) hd_num = models.CharField(max_length=255, blank=True, null=True) hj_rate = models.CharField(max_length=255, blank=True, null=True) hj_num = models.CharField(max_length=255, blank=True, null=True) hm_rate = models.CharField(max_length=255, blank=True, null=True) hm_num = models.CharField(max_length=255, blank=True, null=True) url = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'company_rate' articleapp/urls.py urlpatterns = [ path('table_list/', TemplateView.as_view(template_name='articleapp/table_list.html'), name='table_list'), ] main urls.py urlpatterns = [ path('articles/', include('articleapp.urls')), ] table_list.html {% extends 'base.html' %} {% block content %} <table class="table table-hover table-responsive"> <tbody> {% for article in query_results %} <tr> <td>{{ article.id }}</td> <td>{{ article.date }}</td> <td>{{ article.notice_name }}</td> <td>{{ article.event }}</td> <td>{{ article.basic_amount }}</td> <td>{{ article.num_of_company }}</td> <td>{{ article.avg_of_1365 }}</td> <td>{{ article.hd_rate }}</td> <td>{{ article.hd_num }}</td> <td>{{ article.hj_rate }}</td> <td>{{ article.hj_num }}</td> <td>{{ article.hm_rate }}</td> <td>{{ article.hm_num }}</td> <td>{{ article.url }}</td> </tr> {% endfor %} <tbody> </table> … -
How to fix 404 error on DJANGO for external URL
I am using DJANGO for the first time to make a project for a website. I am getting a 404 error message. Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/external/ Using the URLconf defined in firstwebsite.urls, Django tried these URL patterns, in this order: admin output [name='script'] external The current path, external/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Views.py from django.shortcuts import render import requests import sys from subprocess import run,PIPE def button(request): return render(request, 'home.html') def output(request): data=requests.get("/Users/myname/PycharmProject/ex2.py/coders.py") print(data.text) data=data.text return render(request, 'home.html', {'data':data}) def external(request): inp= request.POST.get('param') out= run([sys.executable,'/Users/myname/tester/tester/test.py',inp],shell=False,stdout=PIPE) print(out) return render(request, 'home.html',{'data1':out}) <!DOCTYPE html> <html> <head> <title> Python button script </title> </head> <body> <button onclick="location.href='{% url 'script' %}'">Execute Script</button> <hr> {% if data %} {{data | safe}} {% endif %} <form action="/external/" method="post"> {% csrf_token %} Input Text: <input type="text"name="param" required><br><br> {{data_external}}<br><br> {{data1}} <br><br> <input type='submit' value="Execute External Python Script"> </form> </body> </html> URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views … -
How do we combine multiple tables to create a report table displaying all the columns with an auto-incrementing, regex defined ID of its own?
I have 3 models: class Student(models.Model): roll_number=models.IntegerField(primarykey=True) name=models.CharField(max_length=50) email=models.EmailField(max_length=60) city=models.CharField(max_length=20) class Course(models.Model): roll_number=ForeignKey(Student, on_delete=CASCADE) course=ForeignKey(CourseChoices, on_delete=CASCADE) class Fee(models.Model): roll_number=ForeignKey(Student, on_delete=CASCADE) total_fee=models.DecimalField(max_digits=7, decimal_places=2, default=0) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Final_amount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Amount_received=models.DecimalField(max_digits=5, decimal_places=2, default=0) Balance=models.DecimalField(max_digits=5, decimal_places=2, default=0) batch=models.CharField(validators=[batch_pattern]) Now, whatever data these tables hold, I want to display them together as: Track ID--Roll No.--Name--Email--City--Course--Total Fee--Discount--Final Amount--Amount Received--Balance--Batch These are the Column heads I want. The 'Track ID' should be the report's own primary key which I want to define using regex. Also, I want every instance to appear in this report with different Track ID. For example, if a student pays a partial fee, it will get recorded in a row with a Track ID. Whenever he/she pays the rest of the amount, should get recorded with the relevant Track ID as per its place in the sheet. I hope I'm explaining well what I intend to achieve here. If I'm not clear, kindly let me know and I'll explain everything with an example or something. Hope I get some help on this here.