Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot display API Json data to display on Django Template
I am trying to get data from a JSON, which was fetched from an API I created to display on my Django Template. The API is just a simple API which store a post hit counts and its id, the json is formatted as below: [ { "object_pk": 3, "hits": 15 }, { "object_pk": 1, "hits": 21 } ] Here is my views.py file: class BlogListView(ListView): model = Post template_name = "home.html" class BlogDetailView(HitCountDetailView, DetailView): model = Post template_name = "post_detail.html" count_hit = True data = { "hits": get_cloudapi_data(), } class ResumePageView(TemplateView): template_name = "resume.html" And my service.py file, which have the get_cloudapi_data() function: def get_cloudapi_data(): url = "my-api-address" r = requests.get(url) hitcount = r.json() return hitcount Below is my HTML template, post_detail.html used for displaying this data: {% extends "base.html" %} {% load hitcount_tags %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p> {% get_hit_count for post %} views</p> <p> {{ post.body }}</p> {% for hit in hits %} <p>{{ hit.object_pk }}</p> <p>{{ hit.hits }}</p> {% endfor %} </div> {% endblock content %} It only shows the title, body and the hit count retrieve with the hitcount app not my API data I have printed out the … -
Django instantiate a file field using model form
I am unable to instantiate a file field from the model form model.py class ModelA(models.Model): image_fileA = ResizedImageField() pdf_fileB = models.FileField() pdf_fileC = models.FileField() forms.py class FormA(ModelForm): class Meta: model = modelA fields = ['image_fileA', 'pdf_fileB', 'pdf_fileC'] widgets = { 'image_fileA': forms.FileInput(), 'pdf_fileB': forms.FileInput(), 'pdf_fileC': forms.FileInput(), } views.py def viewA(request, pk): template = 'app/edit.html' a = modelA.objects.get(id=pk) form = FormA(instance=a) if request.method == 'POST': form = FormA(request.POST, request.FILES, instance=a) if form.is_valid(): form.save() return redirect('page') context = {'a': a, 'form': form, } return render(request, template, context) edit.html <form action="" method="POST" enctype='multipart/form-data'> {% csrf_token %} {%if a.image_fileA%} <img src="{{a.image_fileA.url}}"> {{form.group_logo}} {%else%}Not Available{%endif%} {% if a.pdf_fileB%} <a href="{{a.pdf_fileB.url}}"></a> {{form.pdf_fileB}} {%else%}Not Available{%endif%} {% if a.pdf_fileC%} <a href="{{a.pdf_fileC.url}}"></a> {{form.pdf_fileC}} <button type="submit">Save</button> </form> What I have tried I had to use if else...~~~ to enable file upload in case the file was not available. Have also attached a URL link to enable one to see uploaded files. Errors I expect all fields to have form instances but when i try to save the form without editing I get the following error 'File' object has no attribute 'content_type' Hence the form is only saved when all fields are edited. Can somebody guide where am doing it wrongly. … -
Django url link error Reverse for 'category' with keyword arguments '{'category.id': 1}' not found. 1 pattern
Im trying to create a product filter, filtering it by category, so I decided to send the category id trough an URL and then filter all products by the specified ID, but im getting troubles to implement it, please healp. Reverse for 'category' with keyword arguments '{'category.id': 1}' not found. 1 pattern(s) tried: ['category/<int:category\\.id\\Z'] Views def category(request, category_id): products = Product.objects.filter(category=category_id) return render(request, 'product/category.html', {'products': products}) Model class Category(models.Model): name = models.CharField(max_length=255, unique=False, blank=True) slug = models.SlugField(unique=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse("product:category", kwargs={"category.id": self.id}) Urls urlpatterns = [ path('', views.index, name="index"), path('detail/<int:product_id', views.detail, name="detail"), path('category/<int:category.id', views.category, name="category") ] HTML Template, I tried two ways,none of them worked: {% for category in categories %} {{category.id}} <a href="{{category.get_absolute_url}}"></a> {% comment %} <a href="{% url 'product:category' category_id=category.id %}"></a> {% endcomment %} {% endfor %} Product Model class Product(models.Model): name = models.CharField(max_length=255, unique=False, blank=True) slug = models.SlugField(unique=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, unique=False) -
Django migrations.exceptions.InvalidBasesError (in production)
I run a script with Docker in localhost, there is no problem but when I try to run it in a server, I always get the invalidbase migration error when I run the setup.sh which starts with: python manage.py makemigrations python manage.py migrate ... django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'project1.MetaFlatPage'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; see https://docs.djangoproject.com/en/3.2/topics/migrations/#dependencies for more I run docker compose run web python manage.py makemigrations and output is: "PostgreSQL is up. No changes detected" then run docker compose run web python manage.py makemigrations got the same error above. There are two different docker yml files; dev and production and they are slightly different. I don't know if this relevant but I can share those files too. -
Django Form Disabled Select Option Values Not Submitted Even When They are Enabled with JavaScript Before Submission
My HTML displays about 20 or more forms via modelformset_factory and each having a preselected staff name (so this is disabled in forms.py). Staff name is primary key to Staff model, so I don't want all their names be available for selection. Logged in user have some staff assigned and so they are only required to enter phone number and address. The disabled fields are enabled with Javascript before the form is submitted but I still get {'staff_name': ['This field is required.']} error when the form is submitted. Here are my codes: forms.py class StaffForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['staff_name'].disabled = True views.py class StaffModelFormSet(BaseModelFormSet): def clean(self): super().clean() print(self.errors) class StaffEntryView(LoginRequiredMixin, FormView): def post(self, request, *args, **kwargs): StaffFormSet = modelformset_factory(Staff, form=StaffForm, formset=StaffModelFormSet) submitted_form = StaffFormSet(request.POST) if submitted_form.is_valid(): self.form_valid(submitted_form) print("This form is valid, Sir!") else: self.form_invalid(submitted_form) print("This is not a valid form.") template.html <form method="post" class="form-control" id="staff_form" name="staff-form" onsubmit="enablePath();"> <!-- form details goes here --> <tbody> {% for form in formset %} <tr class="table-striped"> <td>{{ form.staff_name }}</td> <td>{{ form.phone }}</td> <td>{{ form.address }}</td> </tr> {% endfor %} </tbody> script.js function enablePath(e) { var options = document.getElementsByTagName('select'); for (var i=0, iLen=options.length; i<iLen; i++) { options[i].disabled = false; } -
Css is connecting to html but is not rendering correctly
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static '\css\index.css'%}" /> <title>LUXURY STARTS HERE</title> </head> <body> <section class="content"> <h1>LUXURY VILLAS</h1> <video width="500px" autoplay muted loop src="{% static '\video\production ID_4069480.mp4'%}" ></video> <div class="overlay"></div> <a href="">EXPLORE</a> </section> </body> </html> @import url("https://fonts.googleapis.com/css2?family=Luxurious+Roman&display=swap"); .content { position: absolute; top: 0; right: 0; width: 100%; min-height: 100vh; padding: 0; display: flex; align-items: center; background: gold; font-family: "Luxurious Roman", cursive; z-index: -1; } .content video { position: absolute; width: 100%; height: 80%; object-fit: cover; } .content .overlay { position: absolute; background: black; width: 100%; height: 100%; opacity: 0.5; } .content h1 { font-size: 50px; position: absolute; opacity: 0.7; color: gold; top: 10%; left: 10%; z-index: 1000; } .content a { position: absolute; top: 60%; left: 50%; font-size: 30px; z-index: 1000; text-decoration: none; color: white; width: 5em; font-family: monospace; transition: 0.5s; } .content a:hover { color: gold; letter-spacing: 6px; background: rgb(0, 0, 0); opacity: 0.75; border: 5px solid rgb(0, 0, 0); } Hello I am trying to connect my css to my html but for so on known reason it connects but gives me very weird dark colors. I am trying to … -
How to calculate fees,total and subtracting it from the initial balance in a separate App
VIEWS @login_required(login_url='/login/') def send(request): posts =Transactions.objects.filter(user=request.user) form = TransactionForm() if request.method=="POST": form = TransactionForm(request.POST, request.FILES) if form.is_valid(): form.instance.user=request.user # x=(form.cleaned_data['recipient_sending_amount']) form.save() return redirect('/success/') else: messages.error(request, 'Failed, Resend') context = {'form':form, 'posts':posts} return render(request, 'index_user/send-money.html', context) MODELS class Transactions(models.Model): user = models.ForeignKey(CustomUser,related_name='users',on_delete=models.CASCADE) recipient_account_type = models.CharField(max_length=230) recipient_name = models.CharField(max_length=100) recipient_acount_number = models.PositiveIntegerField() recipient_routing_number = models.PositiveIntegerField() recipient_bank_name = models.CharField(max_length=200) recipient_swift_code = models.CharField(max_length=100) recipient_sending_amount = models.DecimalField(max_digits=15, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) transaction_ID =models.CharField(default=ID,max_length=10) description = models.CharField(max_length=1000) transaction_status = models.CharField(max_length=100, choices=transfer_status, default='COMPLETED') fees =models.IntegerField(default=32,blank=True) total =models.IntegerField(default=0,blank=True) status =models.CharField(max_length=100,choices=status, default='COMPLETED',blank=True) colour =models.CharField(max_length=100,choices=colour, default='Blue',blank=True) FORMS class TransactionForm(forms.ModelForm): class Meta: model = Transactions fields = ['recipient_account_type','recipient_name','recipient_acount_number','recipient_routing_number','recipient_bank_name', 'recipient_swift_code','recipient_sending_amount','description','fees',] I HAVE ANOTHER FIELD IN ACCOUNT APP IN MY CustomUser MODEL NAMED account_balance WHICH I WANT TO SUBSTRACT THE TOTAL FROM -
django foreign key Cannot assign must be a instance error
I have a database with the table cargo_empleado that has an id=1 and cargo_empleado='gerente', I also have an Empleado table, in the Empleado table I want to create an employee, I have a form to create an employee, the employee table has as foreign key cargo_empleado, when I put in the form that the employee belongs to the job id=1, it gives me the error: Cannot assign "'1'": "Empleado.cargo_empleado" must be a "CargoEmpleado" instance. models.py class CargoEmpleado(models.Model): nombre_cargo = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'Cargo_empleado' class Empleado(models.Model): rut = models.CharField(primary_key=True, max_length=9) nombres = models.CharField(max_length=100, blank=True, null=True) apellidos = models.CharField(max_length=100, blank=True, null=True) correo_electronico = models.CharField(max_length=100, blank=True, null=True) usuario = models.CharField(max_length=50, blank=True, null=True) contrasena = models.CharField(max_length=255, blank=True, null=True) activo = models.IntegerField() cargo_empleado = models.ForeignKey(CargoEmpleado, models.DO_NOTHING, db_column='cargo_empleado') id_empresa = models.ForeignKey('Empresa', models.DO_NOTHING, db_column='id_empresa', blank=True, null=True) id_unida = models.ForeignKey('UnidadInterna', models.DO_NOTHING, db_column='id_unida') class Meta: managed = False db_table = 'Empleado' views.py def crearusuario(request): if request.method=="POST": if request.POST.get('rut') and request.POST.get('nombres') and request.POST.get('apellidos') and request.POST.get('correo_electronico') and request.POST.get('usuario') and request.POST.get('contrasena') and request.POST.get('activo') and request.POST.get('cargo_empleado') and request.POST.get('id_empresa') and request.POST.get('id_unida'): usersave= Empleado() usersave.rut=request.POST.get('rut') usersave.nombres=request.POST.get('nombres') usersave.apellidos=request.POST.get('apellidos') usersave.correo_electronico=request.POST.get('correo_electronico') usersave.usuario=request.POST.get('usuario') usersave.contrasena=request.POST.get('contrasena') usersave.activo=request.POST.get('activo') usersave.cargo_empleado=request.POST.get('cargo_empleado') usersave.id_empresa=request.POST.get('id_empresa') usersave.id_unida=request.POST.get('id_unida') cursor=connection.cursor() cursor.execute("call SP_crear_usuario('"+usersave.rut+"','"+usersave.nombres+"', '"+usersave.apellidos+"', '"+usersave.correo_electronico+"', '"+usersave.usuario+"', '"+usersave.contrasena+"', '"+usersave.activo+"', '"+usersave.cargo_empleado+"', '"+usersave.id_empresa+"', '"+usersave.id_unida+"')") messages.success(request, "El empleado … -
How can I change the background color of a column based on the value of another column
I'm using Django framework. I have a table that contains some columns. I need to change the background of the aht column based on the agent_target column so if the value lower than or equal the target the background should be green, else it should be red. {% for item in data %} <tr> <td class="text-center align-middle">{{ item.loginid }}</td> <td class="text-center align-middle">{{ item.agentname }}</td> <td class="text-center align-middle">{{ item.team }}</td> <td class="text-center align-middle">{{ item.queue_name }}</td> <td class="text-center align-middle">{{ item.sumduration}}</td> <td class="text-center align-middle">{{ item.countduration}}</td> <td class="text-center align-middle aht">{{ item.aht}}</td> <td class="text-center align-middle target">{{ item.agent_target}}</td> </tr> {% endfor %} When I try to access the value of the AHT column using the below js it returns undefined value console.log(document.getElementById("aht").value) -
Adding Context to Class Based View Django Project
I have a problem with showing a queryset of a specific model in my Gym project. I have tried many different query's but none is working the models: class Workout(models.Model): name = models.CharField(max_length = 30,blank=True, null=True) class Exercise(models.Model): workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='exercises',blank=True, null=True) name = models.CharField(max_length = 30, blank=True, null=True) class Breakdown(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='excercise',blank=True, null=True) repetitions = models.IntegerField() I am trying to showing the repetitions in the Breakdown model which has a ForeignKey relation with Exercise which has a ForeignKey relation with Workout views.py class home(ListView): model = Workout template_name = 'my_gym/home.html' context_object_name = 'workouts' class workout_details(ListView): model = Exercise template_name = 'my_gym/start_workout.html' context_object_name = 'exercises' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['breakdown'] = Exercise.objects.filter(breakdown=self.breakdown) return context urls.py urlpatterns = [ path('', home.as_view(), name='home'), path('workout/<int:pk>/', workout_details.as_view(), name='workout'), ] template: {% for e in exercises %} {{ e.name }} {{ breakdown.repetitions }} {% endfor %} My question what is my mistake here that is either getting me an error or not showing the required data set. my objective is the choose from the home page a Workout from list and next page to be the list of exercises with the repitions related to it. -
which architecture is good for my mobile Chat app in this situation?
I am developing an android app connecting to django backend. My django server in AWS already has own mysql database. (firebase is used for sns authentication) Now I have to add chat functions to this app. It includes group chatting but probably many users may use 1:1 chatting. My question is which architecture is good for mobile Chat app? Options I am thinking now .. Chat messages are stored in mysql database in AWS, and server notify message by only using FCM(Firebase cloud messaging). All text, image or voice urls would be in payload for FCM. A user can only log in on one device at a time. (If this option has no critical performance issue, I think it is a simple way, because I already have backend with database, and I don’t need to care whether user’s Mobile App is in foreground or background. If App needs to show messages when chatting room(channel) is mounted on screed, otherwise just uses notification tray) Use Firebase Realtime database only for chatting functions. It is real time, but I need to create an additional DB in Firebase, and I am not sure how to handle message when app is in background. Chat … -
Put multiple divs on same line using CSS
I'm currently working with Django, and i'm doing a view, where multiple objects from a list are displayed. Right now, each of those objects is on an own line. But i want to have e.g. 2 on one line, so the list is less long on the page. This is my Code so far: html: {% for plant in plants %} <div class="plant"> <img src="{{plant.icon}}"> <div> <label>{{plant.common_name}}</label> <input type="number" name="percentage"/> </div> </div> {% endfor %} CSS: .plant_beet_form { width: 100%; margin: 0 auto; font-size: 3rem; } .plant div { width: 70%; margin: 0 auto; } .plant input{ margin: 0 auto; width: 100%; font-size: 2.5rem; } .plant img { width: 10rem; height: 10rem; margin-bottom: 1rem; } .plant { width: 30%; margin: 0 auto; margin-bottom: 2rem; } I already tried using display:grid and grid-template-rows: 1fr 1fr, but this didn't work either. Any idea? Thank you -
Is there a way I can follow to add my other django app from my other project to my new project? [duplicate]
Please I need a help on how to attach my other app with my new django app. -
How to fix 'workout_details' object has no attribute '_state' Error
I have a problem with showing a queryset of a specific model in my Gym project. Here is the models: class Workout(models.Model): name = models.CharField(max_length = 30,blank=True, null=True) class Exercise(models.Model): workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='exercises',blank=True, null=True) name = models.CharField(max_length = 30, blank=True, null=True) class Breakdown(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='excercise',blank=True, null=True) repetitions = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) I am trying to showing the Breakdown details of every Exercise, but I got this error after several trials. Here is the urls: urlpatterns = [ path('', home.as_view(), name='home'), path('workout/<int:pk>/', workout_details.as_view(), name='workout'), Here is the views: class home(ListView): model = Workout template_name = 'my_gym/home.html' context_object_name = 'workouts' class workout_details(DetailView): model = Exercise.workout template_name = 'my_gym/start_workout.html' context_object_name = 'exercises' # class workout_details(DetailView): # model = Breakdown # template_name = 'my_gym/start_workout.html' # context_object_name = 'breakdown' Here is the template: {% for excercise in excercises %} {{excercise.name}} {% for b in breakdown %} {{b.repetitions}} {% endfor %} {% endfor %} My question what is my mistake here that is either getting me an error or not showing the required data set. my objective is the choose from the home page a Workout from list and next page to be the list of exercises with the repitions related to … -
Table Buttons to Submit Changelist Form in Django
I currently have the following admin page with a set list_editable fields in my ActivityLogAdmin model. When I click "Save" on the bottom of the admin page, the request.POST data gets submitted to my form. I have the following method under my ActivityLogAdmin class: def get_changelist_form(self, request, **kwargs): return ActivityLogChangeListForm However, I'm trying to add one custom button for each entry in my change list, so when I click it, the POST data should also be passed to a view so I can handle that data. However, I can't seem to pass this request.POST data of when I click the button to the view. Here's my attempt: def approve(self, obj): url = reverse('admin:activity_log_approve', args=[str(obj.id)]) return mark_safe(f'<button name="approve_button" type="submit"><a href="{url}">Approve</a></button>') approve.short_description = 'Edit status' urlpatterns = [ url(r'^(.+)/approve/$', wrap(self.approve_view), name='events_activity_log_approve'), def approve_view(self, request, object_id, extra_context=None): print(request.POST['approve_button']) #Is None :( Tried with request.POST only as well form = ActivityLogChangeListForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/panel/events/activitylog') Do you guys know what I'm doing wrong? It's been a loong time since I worked with Django and I've wasted 2 days already on that :( Thanks a lot in advance! -
Django date timed events
I need something like this an employee get from date to date a task if date is happend go back to default like previous task or something. any ideas ? -
how can I output a variable to a django template via HttpResponse?
I need to output the correspondents variable to the django template via HttpResponse, but I can't think of how to do it correctly. views.py: def send_chat(request): resp = {} User = get_user_model() if request.method == 'POST': post =request.POST u_from = UserModel.objects.get(id=post['user_from']) u_to = UserModel.objects.get(id=post['user_to']) messages = request.user.received.all() pk_list = messages.values(u_from.pk).distinct() correspondents = User.objects.filter(pk__in=list(pk_list)) insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message']) try: insert.save() resp['status'] = 'success' except Exception as ex: resp['status'] = 'failed' resp['mesg'] = ex else: resp['status'] = 'failed' return HttpResponse(json.dumps(resp), content_type="application/json") models.py: class chatMessages(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE,related_name="sent") user_to = models.ForeignKey(User, on_delete=models.CASCADE,related_name="received") message = models.TextField() date_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.message -
Django form post doesn't contain any values
I have a simple unbound form: class TeamMemberMapForm(forms.Form): remote_id = forms.CharField(widget=forms.HiddenInput()) project = forms.ModelChoiceField(queryset=Project.objects.none()) Initial values are populated in the get_context_data: form.fields['remote_id'].value = remote_id form.fields['remote_id'].initial = remote_id form.fields['remote_id'].disabled = True form.fields['project'].queryset = Project.objects.\ filter(owned_by_company=self.request.user.owned_by_company, active=True) On the frontend, I can select the values, by rendering the form like so. This is fine. {% block form %} <form method="post">{% csrf_token %} <fieldset class="uk-fieldset"> <!-- {{ form.errors }} --> <!-- {{ form.non_field_errors }} --> {{ form.as_p }} </fieldset> <button class="uk-button uk-button-primary" type="submit"> {% if object %} Save {{ object }} {% else %} Create new entry {% endif %} </button> </form> {% endblock %} Next, the view. I take the request and populate the form: def post(self, request, remote_id, remote_name, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # Do whatever In the end, the form never validates. Inspecting the populated form from the POST shows that the values are never received. <tr> <th><label for="id_remote_id">Remote id:</label></th> <td> <ul class="errorlist"><li>This field is required.</li></ul> <input class="uk-input uk-text " type="text" name="remote_id" required id="id_remote_id"> </td> </tr> <tr> <th><label for="id_project">Project:</label></th> <td> <ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul> <select class="uk-select" name="project" required id="id_project"> <option value="">---------</option> </select> </td> </tr> The post object … -
Add Title or Title Tag to url path
I'm hoping somebody can help me with this issue. Im having trouble adding my page/ article title to the url path. I've tried a number of ways can't seem to get it. If anyone could help that would be great. My current Url path is "https://stackoverflow.com/article/1" Would like it to be "https://stackoverflow.com/article/1/example-question-help", or some variation of that. Below you can find how my views and url files are set up. path('article/<int:pk>/', ArticleDetailView.as_view(), name='article-detail'),' class ArticleDetailView(DetailView): model = Post template_name = 'article_detail.html' def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu context["total_likes"] = total_likes context["liked"] = liked return context -
django error foreign key Cannot assign must be a instance
I am creating a stored procedure, I need to create a user in django, I have a foreign key called cargo_empleado that causes me an error my models.py class CargoEmpleado(models.Model): nombre_cargo = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'Cargo_empleado' class Empleado(models.Model): rut = models.CharField(primary_key=True, max_length=9) nombres = models.CharField(max_length=100, blank=True, null=True) apellidos = models.CharField(max_length=100, blank=True, null=True) correo_electronico = models.CharField(max_length=100, blank=True, null=True) usuario = models.CharField(max_length=50, blank=True, null=True) contrasena = models.CharField(max_length=255, blank=True, null=True) activo = models.IntegerField() cargo_empleado = models.ForeignKey(CargoEmpleado, models.DO_NOTHING, db_column='cargo_empleado') id_empresa = models.ForeignKey('Empresa', models.DO_NOTHING, db_column='id_empresa', blank=True, null=True) id_unida = models.ForeignKey('UnidadInterna', models.DO_NOTHING, db_column='id_unida') class Meta: managed = False db_table = 'Empleado' my views.py def crearusuario(request): if request.method=="POST": if request.POST.get('rut') and request.POST.get('nombres') and request.POST.get('apellidos') and request.POST.get('correo_electronico') and request.POST.get('usuario') and request.POST.get('contrasena') and request.POST.get('activo') and request.POST.get('cargo_empleado') and request.POST.get('id_empresa') and request.POST.get('id_unida'): usersave= Empleado() usersave.rut=request.POST.get('rut') usersave.nombres=request.POST.get('nombres') usersave.apellidos=request.POST.get('apellidos') usersave.correo_electronico=request.POST.get('correo_electronico') usersave.usuario=request.POST.get('usuario') usersave.contrasena=request.POST.get('contrasena') usersave.activo=request.POST.get('activo') usersave.cargo_empleado=request.POST.get('cargo_empleado') usersave.id_empresa=request.POST.get('id_empresa') usersave.id_unida=request.POST.get('id_unida') cursor=connection.cursor() cursor.execute("call SP_crear_usuario('"+usersave.rut+"','"+usersave.nombres+"', '"+usersave.apellidos+"', '"+usersave.correo_electronico+"', '"+usersave.usuario+"', '"+usersave.contrasena+"', '"+usersave.activo+"', '"+usersave.cargo_empleado+"', '"+usersave.id_empresa+"', '"+usersave.id_unida+"')") messages.success(request, "El empleado "+usersave.nombres+" se guardo correctamente ") return render(request, 'app/crearusuario.html') else: return render(request, 'app/crearusuario.html') error: Cannot assign "'funcionario'": "Empleado.cargo_empleado" must be a "CargoEmpleado" instance. Please someone help me! -
Django template, send two arguments to template tag and return safe html value is there possible?
im passing 2 values {% checkdatainicio data.one data.two %} and my return is: '<span style="color:#bdc3c7">'+data+"</span>" i want to return it safe in html -
Django admin how to show currency numbers in comma separated format
In my models I have this: class Example(Basemodel): price = models.IntegerField(default=0) and in my admin I have this: @admin.register(Example) class ExampleAdmin(admin.ModelAdmin): list_display = ('price',) I want the price field to be shown in comma-separated format instead of the typical integer format and I want to do that on the backend side. For example: 333222111 should be 333,222,111 Any can recommend me a solution? -
Django one to many saving model is giving error
I have an exam model and I am trying to add a form to add multiple Quiz instance in the parent model. I am getting the following error raise ValueError( ValueError: Cannot assign "": "exam_quiz.quiz" must be a "Quiz" instance. class ExamQuizAdminForm(forms.ModelForm): class Meta: model = exam_quiz exclude = ['registrationDate','examdate'] quiz = forms.ModelMultipleChoiceField( queryset=Quiz.objects.all(), required=False, label=_("Quiz"), widget=FilteredSelectMultiple( verbose_name=_("Quiz"), is_stacked=False)) def __init__(self, *args, **kwargs): super(ExamQuizAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['quiz'].initial = \ self.instance.quiz def save(self, commit=True): exam_quiz = super(ExamQuizAdminForm, self).save(commit=False) exam_quiz.save() exam_quiz.quiz_set.set(self.cleaned_data['Quiz']) self.save_m2m() return exam_quiz class ExamQuizAdmin(admin.ModelAdmin): form = ExamQuizAdminForm list_display = ('examname','month','year') -
NoReverseMatch at / when trying to add href in Django
I have a list of items and I am trying to add a link to the item's title to direct the user to the item's own page. However, I am getting Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listing/(?P<listing_id>[0-9]+)\\Z'] error and I couldn't figure out what I did wrong. The error is in line<h2><a href="{% url 'listing' listing.id %}">{{auction.title}}</a></h2> of index.html urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create_listing, name="create"), path("listing/<int:listing_id>", views.listing, name = "listing"), ] views.py: def listing(request,listing_id): listing = AuctionItem.objects.get(id = listing_id) return render(request, "auctions/listing.html",{ "listing":listing }) index.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% for auction in auctions %} <div class = "frame"> <img src="{{auction.image}}" style= "width: 30vw;"> <h2><a href="{% url 'listing' listing.id %}">{{auction.title}}</a></h2> <div id="text"><strong>Price:</strong> ${{auction.price}}</div> <div id="text"><strong>Description:</strong> {{auction.description}}</div> <div id="text"><strong>Category:</strong> {{auction.category}}</div><br> <div id="date">Created {{auction.date}}</div> </div> {% empty %} <li>No item.</li> {% endfor %} {% endblock %} -
I have successfully deployed the django web app to heroku but it was giving application error
I have successfully deployed the Django web app to Heroku but it was giving an application error. heroku logs 2010-09-16T15:13:46.677020+00:00 app[web.1]: Processing PostController#list (for 208.39.138.12 at 2010-09-16 15:13:46) [GET] 2010-09-16T15:13:46.677023+00:00 app[web.1]: Rendering template within layouts/application 2010-09-16T15:13:46.677902+00:00 app[web.1]: Rendering post/list 2010-09-16T15:13:46.678990+00:00 app[web.1]: Rendered includes/_header (0.1ms) 2010-09-16T15:13:46.698234+00:00 app[web.1]: Completed in 74ms (View: 31, DB: 40) | 200 OK [http://myapp.heroku.com/] 2010-09-16T15:13:46.723498+00:00 heroku[router]: at=info method=GET path="/posts" host=myapp.herokuapp.com" fwd="204.204.204.204" dyno=web.1 connect=1ms service=18ms status=200 bytes=975 2010-09-16T15:13:47.893472+00:00 app[worker.1]: 2 jobs processed at 16.6761 j/s, 0 failed ... I also try to set DEBUG = True from Django's settings.py but no errors were showing.