Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django check_token(user, token) fails in view but works in test/shell_plus?
Getting the strangest behavior. This fails in normal Django code (view): user = User.objects.get(...) uid = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) print("CHECK TOKEN:", default_token_generator.check_token(to, token)) # this prints True! send_email_function(user, uid, token) # When using password reset email, token is denied Then when using the token to reset password, the password reset view claims the token is invalid. If I make a management command that calls the same code to send a password reset email: the token works! This works in shell_plus, same code basically: >>> from django.contrib.auth.tokens import default_token_generator >>> from django.utils.encoding import force_bytes >>> from django.utils.http import urlsafe_base64_encode >>> user = User.objects.last() >>> token = default_token_generator.make_token(user) >>> default_token_generator.check_token(user, token) True I've printed out the SECRET_KEY in each case and that seems fine. Inspecting the make_token function has lead me to trying to set a password and last_login which have not helped. Very confusing! -
How to add + buttons on the Many to many TabularInline fields
How can I add the "+" sign to add the Many to Many field , below is the picture which shows the TabularInline with the name : SUBTOPIC-COURSE RELATIONSHIPS. What I want is to be able to add a subtopic via here directly on this page This is how my code is admin.py: class SubTopicInline(admin.StackedInline): model = models.SubTopic.course.through class CourseAdmin(admin.ModelAdmin): inlines = [SubTopicInline] admin.site.register(models.Course, CourseAdmin) Then the models: class Course(TimeStampedModel, models.Model): """ Course model responsible for all courses. :cvar uid: UID. :cvar title: Course title. :cvar description: Description of the course. :cvar course_cover: Image for the course. :cvar category: Course Category. :cvar user: Author of the course. :cvar review: Course review. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Meta: verbose_name_plural = "Courses" class SubTopic(TimeStampedModel, models.Model): """ Subtopic for the course. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) sub_topic_cover = models.ImageField( _('Sub topic Cover'), upload_to='courses_images', null=True, max_length=900) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) course = models.ManyToManyField(Course, related_name='sub_topic', blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Sub topic" class Lesson(TimeStampedModel, models.Model): """ Lesson for the sub topic. """ … -
question about django rendering , jsonresponse
I'm working on an employee view. with this view I have 2 containers. 1 is for employe names, and the other should show the info as soon as I press a name. I'm trying to figure it out for 3 days but can't figure it out can someone please help me index view where it will render def index(request): employe = Employe.objects.all() context = { 'employe': employe, } return render(request, 'managements/index.html', context) the jsonresponse view is here def employeInfo(request): data = json.loads(request.body) employeId = data['id_s'] action = data['action'] print(employeId) print(action) if action == 'get': check = Employe.objects.get(id=employeId) checkinfo, create = Employe.objects.get_or_create(object, id=employeId) print('check:', check, 'checkinfo', checkinfo) return JsonResponse('context', safe=False) the template is here, I tried few combinations nvm for that. <div class="flex-container"> <div class="flex-child magenta" > <div data-method="POST" id="label1"> Medewerker info</div> {% csrf_token %} {% if action %} <ul>{{name.employe_info}}</ul> <ul>{{surname.checkinfo}}</ul> <ul>{{checkinfo.id}}</ul> <ul>{{rank.id}}</ul> <ul>{{employeInfo.name}}</ul> <ul>{{email.id}}</ul> <ul>{{phone.id}}</ul> <ul>{{name.id}}</ul> {% endif %} <tr> <div class="flex-child green"> <div id="label2"> Medewerke</div> {% for profile in employe %} <button id="hehe" data-id_s={{profile.id}} data-action="get" class=" btn-sm btn-outline-secondary info-employe"> <a>{{ profile.name}}</a></button> {% endfor %} </div> </tr> I've been trying for 3 days and no progress. thank you in advance -
Django set Boolean to False when clicking a button
The following code (just to learn Django) allows to mark the user's ticket as "Solved" with an HTML button. When the button is clicked, ticked_solved is set to True, ticket_waiting is set to False. This is also recognized in the template, which I have tested. But then in the dashboard the object would have to change to False/True as well, which as you can see in the screenshot is not the case. I do all this with a form, which is probably not the smartest option either. \\ models.py class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() ticket_waiting = models.BooleanField(default=True) ticket_solved = models.BooleanField(default=False) def __str__(self): return str(self.title) \\forms.py class TicketSolved(forms.Form): delete = forms.CharField( label='', max_length=0).widget = forms.HiddenInput() \\views.py def ticket_system_view(request, id): obj = Ticket.objects.get(id=id) form2 = TicketSolved(request.POST) if request.method == 'POST': if form2.is_valid(): obj.ticket_waiting = False obj.ticket_solved = True return render(request, 'ticket-system.html', {'obj': obj, 'form2': form2}) \\ .html {% if obj.user != request.user %} <p>Page Not Found</p> {% else %} <p>Ticket ID {{obj.id}}</p> {{ obj.title }} {{ obj.description }} {% endif %} <br></br> <form method="POST"> {% csrf_token %} {{ form2 }} <button type="submit">Status to Solved</button> </form> ----Just to test if it works: … -
The Checklist could not be changed because the data didn't validate
Trying to update the checklist, by changing the title, description and due date, but i am not getting any data to fill in the forms either so it is strange. Modles.py class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() check_completed = models.BooleanField(default=False) description = models.TextField(default="Checklist description") task = models.ForeignKey(Task, blank=True, null=True, related_name='checklist', on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, **kwargs) def get_url(self): return reverse('task_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title My views.py @login_required def update_checklist(request, slug): update_check = Checklist.objects.get(slug=slug) if request.method == 'POST': form = ChecklistForm(request.POST, instance=update_check) form.save() return redirect('task_detail', slug=slug) Urls.py urlpatterns = [ path('projects/', teams, name='teams'), path('projects/project/<slug>/', projects, name='projects'), path('projects/tasks/<slug>/', project_detail, name='project_detail'), path('projects/checklist/<slug>/', task_detail, name='task_detail'), # Create a new checklist item path('projects/checklist/new_checklist_item/<slug>/', new_checklist_item, name='new_checklist_item'), ] forms.py class ChecklistForm(forms.ModelForm): class Meta: model = Checklist fields = ['title', 'description', 'due_date'] And in my html i have <form method="POST" action="{% url 'update_checklists' title.slug %}" class="modal fade" id="task-edit-modal" tabindex="-1" aria-hidden="true"> {% csrf_token %} <label for="{{ form.title.id_for_label }}" class="col-3">Title</label> <input class="form-control col" type="text" id="{{ form.title.id_for_label }}" placeholder="Task name" value="{{ checklist.title }}" name="{{ form.title.html_name }}" /> </div> <div class="form-group row"> <label for="{{form.description.id_for_label}}" class="col-3">Description</label> <textarea class="form-control col" rows="3" placeholder="Task description" … -
My chrome page does not find localhost when using Selenium with python
I am trying to test my django application with Selenium. Its my first time so I just go through some tuto and got an easy test. Here it is : class HostTest(LiveServerTestCase, TestCase): def test_home(self): s=Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=s) driver.get('http://127.0.0.1:8000') self.assertIn("Accueil", driver.title) I have the chrome driver v97.0.4692. When I run the test, the web page open, close, and I have an assertion error in my console : AssertionError: 'Accueil' not found in '127.0.0.1'.. My url is fine, but when I look at the chrome page before it close, i have an ERR_EMPTY_RESPONSE. -
Django : If if-statement ist True -> Don't render the rest possible?
Hello for last time today, Is it possible to say that if the first If statement is true, then I don't want to render the rest of the content? Example below, if for example it is true that the user who is on the page is not the owner of the object, then "Page Not Found" is output. {% if obj.user != request.user %} <p>Page Not Found</p> {% endif %} {{ obj.title }} {{ obj.description }} In this example the if statement matches. But the rest of the content is rendered as well, of course. So that this is not the case, I would have to put everything as {% else %} in the If statement (or the other way around). Then the whole content would be in an If statement like so {% if obj.user != request.user %} <p>Page Not Found</p> {% else %} <p>Ticket ID {{obj.id}}</p> {{ obj.title }} {{ obj.description }} {% endif %} So my question: Can I say that if an If statement is true, the rest will not be rendered? -
In Djanog, how to pass value from one table to other
I trying to convert lead to account in a crm app. In Lead detail view, i have created a button to convert. But Im not sure how to get working. Below are my codes. model: class Lead(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) title = models.CharField(max_length=30, null=True, blank=True) phone = models.CharField(max_length=30, null=True, blank=True) mobile = models.CharField(max_length=30, null=True, blank=True) annual_revenue = models.IntegerField(null=True, blank=True) company_name = models.CharField(max_length=30, null=True, blank=True) email = models.EmailField(max_length=30, null=True, blank=True) website = models.CharField(max_length=30, null=True, blank=True) #address city = models.CharField(max_length=30, null=True, blank=True) country = models.CharField(max_length=30, null=True, blank=True) description = models.TextField(max_length=255, null=True, blank=True) class Account(models.Model): account_name = models.CharField(max_length=30, null=True, blank=True) annual_revenue = models.IntegerField(null=True, blank=True) phone = models.CharField(max_length=30, null=True, blank=True) website = models.CharField(max_length=30, null=True, blank=True) Views: class LeadConvert(generic.CreateView): def get_success_url(self): return "/leads" def ConvertLead(self, **kwargs): lead = self.queryset account = Account.objects.create( account_name = lead.company_name, phone = lead.phone_number, annual_revenue = lead.annual_revenue, website = lead.website ) account.save def get_queryset(self, **kwargs): queryset = Lead.objects.filter[id == id] return queryset -
How to get a derived class instance in a method of an abstract base class without explicit derived class importing in Django
End goal: I'm creating an abstract base class HierCachedModel(django.models.Model). It's purpose is to perform the overhead needed to maintain an otherwise persistent database cache of a series of functions that reside in 4 Model classes that are hierarchically related. Basically, it saves a cached value anytime any "cached function" in that class is accessed and it over-rides Model's save() and delete() methods to perform cache-related overhead operations such as a cascading deletion of all cached values under the "root" model instance. It also has a set of utility methods that can be called to perform "global" cache-related operations (like fill in missing cached values or delete all caches under a given set or root model objects). Everything works fine, except that the way I did it (and I'm sure it's simply from inexperience), I have to import the derived classes in the abstract base class file I created (hier_cached_model.py) or else I get errors about undefined classes whever I perform anything that traverses the hierarchy. Prior to this caching implementation, I had these classes (I'll do 3 classes as an example to simplify it): models.py: class Animal(Model): ... class Sample(Model): animal = models.ForeignKey(... related_name="samples") ... class Analysis(Model): sample = models.ForeignKey(... … -
how to make a dropdown selection in a CreateView field- Django
i'm adding a new field(location) to my PostCreateView and I want to be able to select that field if it's already in the database. (like idk New York) it does show up but obv its not a dropdown. views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'location'] success_url = '/' models.py class Location(models.Model): location = models.CharField(max_length=100) def __str__(self): return self.location def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() location = models.CharField(max_length=100, default="") def total_likes(self): return self.likes.count() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I've tried to add this widgets= { 'location': forms.Select(attrs={'class': 'form-control'}) } right underneath to my class PostCreateView, but I guess it doesn't work since I don't use forms.py and instead I use class PostCreateView inside of views.py -
Django Admin's change list view: display image from ImageField
I'm trying to display each model's image in the admin 'change list view' by 1) defining a method that displays an image from an ImageField; 2) inserting it in list_display in admin.py. So far, I've gone through many questions and I've seen many solutions involving format_html. This is what I've come up with: [models.py] class MyClass(models.Model): ... def show_photo(self): return format_html( "<img src={}>", 'self.photo.path' ) [admin.py] class CustomClass(admin.ModelAdmin): ... list_display = ('name','email','show_photo') But, no matter what, I get from Chrome this error: Failed to load resource: the server responded with a status of 500 (Internal Server Error), and the image is obviously broken. It's like format_html() is unable to find my files. I DO manage to display images in admin pages, though: if instead of providing a path such as self.photo.path to src in format_html(), I provide a web url, like http://imageserver.com/images/12345, or; through overriding methods like change_list or changelist_view and then inserting a {% static %} tag in the corresponding template, providing the image's absolute path with object.photo.path. Example: [admin.py] class... ... def change_view(self,request,object_id,form_url='',extra_context=None): p = MyClass.objects.get(id=object_id) extra_context = extra_context or {} extra_context['p'] = p.photo.path return super().change_view(request,object_id,form_url,extra_context=extra_context) [change_form.html] ... </ul> {% endif %}{% endif %} <img src="{% static p … -
How add access to cookie in Django views
Hello friends i am beginner and i have a code that i added it below . i have view that uses as refresh_token . my boss tell to me adde access to cookie but i do not know how to add it ?where to add it? can anyone give me a solution or send me a link about it? if have less knowledge about cookie and and complete request structure if can me a link for describe that i am thankful. enter image description here -
Why dropdown menu doesn't working? Where is the bug?
I'm trying to learn django and meanwhile ı have learned css, boostrap and html too but still I'm not so good at them. I have tried a lots of way for it but its not working properly. I didint understand why its not working and my brain got melted... enter code here<!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %} Newspaper App {% endblock %}</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href=" {% url 'home' %} ">Newspaper</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> {% if user.is_authenticated %} <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary"> Log In </a> <a href="{% url 'signup' %}" class="btn btn-primary ml-2"> Sign Up </a> </form> {% endif %} </div> </nav> <main> <div class="container"> {% block content %} {% endblock %} </div> </main> </body> </html> -
Django, Celery and Sequential Asynchronous tasks
I am building a system in Django that uses Celery and Django-Celery-Beat to run data creation and extraction tasks. I am pulling records from a datastore using it's API and from this creating multiple jsonl files as the final output - these files become the basis for all the subsequent tasks. Then images are made using information from the jsonl files and then these files are used to update other systems (namely Solr). All this works fine. It's the Celery part that has me stummped. These tasks need to be run sequentially and they each can't fail, and if they do the sequence needs to stop. I also need to lock the tasks from running twice as this will mess up the jsonl files, image creation, etc.... What I have looked into is using Celery and chains with immutable signatures, as the tasks don't return anything, they create files, images, etc.... But I can't seem to find a method to lock the tasks from running twice at the same time. So the questions has two parts What is the best method for running periodic tasks in Django that needs to run asynchronously but also sequentially within that task? Is Celery … -
Customizing inlineformset choice in Django template
I've got some forms I'm trying to customize. I render the fields manually - and it all works fine until get to a particular field (which is an InlineFormset itself). I'm trying to customize those options but can't seem to figure out how to do so. my forms.py looks like this: class SummativeScoreForm(forms.ModelForm): subdomain_proficiency_level = forms.ModelChoiceField( empty_label="Undecided", queryset=SubdomainProficiencyLevel.objects.none(), widget=forms.RadioSelect, required=False, ) def __init__(self, request, *args, **kwargs): super(SummativeScoreForm, self).__init__(*args, **kwargs) if self.instance: if request.user == self.instance.summative.employee: self.fields["subdomain_proficiency_level"].disabled = True self.fields[ "subdomain_proficiency_level" ].queryset = SubdomainProficiencyLevel.objects.filter( subdomain=self.instance.subdomain ) self.fields[ "subdomain_proficiency_level" ].label = f""" {self.instance.subdomain.character_code}: {self.instance.subdomain.short_description} """ class Meta: model = SummativeScore fields = "__all__" SummativeScoreInlineFormset = inlineformset_factory( Summative, SummativeScore, fields=("subdomain_proficiency_level",), can_delete=False, extra=0, form=SummativeScoreForm, ) My template for summative_score_form looks like this: <form method="post" novalidate> {% csrf_token %} {% include "myapp/includes/summative_score_response_formset_snippet.html" with formset=form %} <button type="submit" class="btn btn-primary"><i class="fal fa-clipboard-check"></i> Submit Updated Scores</button> </form> The summative_score_response_formset_snippet looks like this: {{ formset.management_form }} {% for formset_form in formset.forms %} {% if formset_form.non_field_errors %} <ul> {% for error in formset_form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} {% for hidden_field in formset_form.hidden_fields %} {% if hidden_field.errors %} <ul> {% for error in hidden_field.errors %} <li> (Hidden field {{ hidden_field.name }}) {{ error … -
Django rest don't see json data of GET XmlHTTPRequest
Recently, i have started playing with django rest framework, my goal is to perform a GET on a rest api with some kind of filtering. For this i have choose to pass filters params as json object. I do this with xmlhttprequest. The problem is the django side don't see my json data when i dump the request. I have try this method with curl and it is ok. But from code, it is not. I have dumped the http headers and see that the only valuable diff is that Content-Length is not set with xmlhttprequest, contrary to curl. I have tried to set it manually but it is refused by javascript engine, he say 'Refuse to set dangerous header', after digging into the internet, this look to be forbidden. I have tried to change to the POST method, and this time, it work, i see my filters data. So my question is, is there a settings, decorator, flag or whatever that can force httprequest to parse content data h when content-length is absent for GET request ? Thanks -
How to paginate different objects of the same endpoint in Django Rest Framework?
Lest supose that I have a model named Collection. I can create a collection, this collection have two important fields: share_with_company, share_list. class Collection(models.Model): name = models.CharField(max_length=200, blank=False, null=False) share_with_company = models.BooleanField(default=False) share_list = ArrayField(models.CharField(max_length=15), null=True, blank=True) owner = models.CharField(max_length=200, blank=False, null=False) currently I have an endpoint: /collections and this endpoint need to return something like it: { shared_with_company:{collections: ..., count: 5} shared_list:{collections: ..., count: 12} my_collections:{collections: ..., count: 20} //dont shared with anyone, created by the current user } but, in the frontend the user want to paginate just my_collections or just shared_list or shared_with_company. I like performance, so should I create a specifics endpoints to each type of collections? But, everytime the user load the collections page will show 12 (max per page) collections of each (my_collections, shared etc.), and then he will be able to paginate it. I don't know if this is the best way to do it, I think a lot of users send 3 requests everytime the page is loaded. Another approach: use an endpoint to load the initial page, and this enpoint will make one request to the first page and the paginations will be made with differents endpoints. I really don't know … -
Django displaying each object in a button
Good day, I have a page to test where tickets are created and where all created tickets (titles) are listed. Now you should be able to click on the title of a created ticket. The button then redirects to an extra page where all the information of the specific ticket is. I've always had trouble displaying user specific stuff, so what needs to be done so that the href="" of each link redirects in HTML to the specific ticket? I did the following \\forms.py {% for i in request.user.addtitle_set.all %} <div> {% if i.user == request.user %} {{ i.title }} {% endif %} <form action="{% url SOMETHING_HERE i.id}" style="display: inline"> <button type="submit">Delete</button> </form> </div> <br /> {% endfor %} \\urls.py path('dashboard/user/ticket', ticket_view), path('dashboard/user/ticket/<int:id>/', ticket_system_view, name="view_ticket"), \\ models.py class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() creator_adress = models.GenericIPAddressField(null=True) start_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.title) \\views.py @login_required def ticket_view(request, id, *args, **kwargs): try: obj = Ticket.objects.get(id=id) except Ticket.DoesNotExist: return redirect('/') if request.method == 'POST': form = TicketForm(request.POST, instance=Ticket(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard/user/ticket') else: form = TicketForm() return render(request, 'ticket.html', {'form': form}) def ticket_system_view(request, id, *args, … -
ModuleNotFoundError: No module named 'app.project'
Mb I am idiot but I wanna know what I do wrong enter image description here enter image description here enter image description herestack.imgur.com/qtMOg.png -
Show list of another model in detail view
I want to show another model inside the detail view as a list. I have tried using "get_context_data" inside the DetailView but it does not show up inside the template. The model that I want to show is called "Questions". This is my code right now class ArticleDetailView(LoginRequiredMixin, DetailView): model = Article def get_context_data(self, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) context['questions'] = Questions.objects.filter(author=self.request.user) return context In my template I call for {{questions}} but nothing shows up. -
TypeError: bad argument type for built-in operation. I can't see the error
I have an error here which I can't figure out. This is for export a PDF Traceback (most recent call last): File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, *callback_kwargs) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\purchase\views.py", line 290, in view_sales_order_pdf textob.textLine(line) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\reportlab\pdfgen\textobject.py", line 445, in textLine self._code.append('%s T' % self._formatText(text)) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\reportlab\pdfgen\textobject.py", line 412, in _formatText for f, t in pdfmetrics.unicode2T1(text,[font]+font.substitutionFonts): Exception Type: TypeError at /view_sales_order_pdf/ Exception Value: bad argument type for built-in operation def view_sales_order_pdf(request): buf = io.BytesIO() c = canvas.Canvas(buf, pagesize=A4, bottomup=0) textob = c.beginText() textob.setTextOrigin(mm, mm) textob.setFont("Helvetica", 14) sales_orders = SalesOrder.objects.all() lines = [] for sales_order in sales_orders: lines.append(sales_order.so_number) lines.append(sales_order.customer) for line in lines: textob.textLine(line) c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='sales_order.pdf') -
Django handling database table names differently in Ubuntu vs Windows
I've built a Django application locally and I'm now trying to deploy it (or at least test) on an AWS EC2 instance using Ubuntu 20.04 (t2.micro). When hosted locally, the application works fine. When hosted on AWS, I get a ProgrammingError (1146, "Table 'database_name.exampleAppName_modelname' doesn't exist"). What I've tried On the server, using MySQL in the command line I've done: USE database_name; SHOW tables; Which lists tables as expected as: +----------------------------------------------+ | Tables_in_database_name | +----------------------------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | django_session | | **exampleappname_modelname** | The cause of the error seems to be fairly obvious in that Django is querying 'exampleAppName' but the database contains 'exampleappname' instead. However, when I run the same MySQL commands locally, I get exactly the same list of tables. And when I run the Django app locally there are no errors. I checked the names Django is automatically assigning the tables on the server and locally using the shell: ModelName._meta.db_table In both cases, this returns: 'exampleAppName_modelname', which leads to my question. What I'd like to know If the 'db_table' name auto-assigns the … -
how to connect bootstrap form to Django database to create a model instance
I am new to bootstrap and django both, so please don't mind my skills. I have made a custom bootstrap form for my todo app that will add item in the database which looks like this add task field here is the bootstrap code: <form method="post" class="form-control"> {% csrf_token %} {{ form.as_p }} <p class="lead"> Create your task: </p> <div class="form-row"> <div class="col-7"> <input type="text" class="form-control" placeholder="Enter your task here:" name="task"> </div> <div class="col-2"> <input type="time" class="form-control" placeholder="Enter your time here:" name="time"> </div> <div class="col-2"> <select class="custom-select mr-sm-2" id="inlineFormCustomSelect" name="status"> <option selected>Choose...</option> <option value="1">In Complete</option> <option value="2">Completed</option> </select> </div> <div class="col-1"> <button type="button" class="btn btn-outline-primary">Confirm</button> </div> <div class="row mt-3"></div> </div> </form> the model and the form are below: class Task(models.Model): choices = ( ('Completed', 'Completed'), ('In Complete', 'In Complete'), ) name = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) task = models.CharField(max_length=200, null=False, blank=False) time = models.TimeField(auto_now_add=False, blank=True) status = models.CharField(max_length=200, choices=choices, null=True, blank=False) def __str__(self): return self.task from django.forms import ModelForm from .models import * from django import forms class TaskForm(ModelForm): class Meta: model = Task fields = '__all__' and the view is: def create_task(request): form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = … -
Django The ChecklistItem could not be created because the data didn't validate
Creating a small function to add a new checklist item and i keep getting same error. Views.py @login_required def task_detail(request, slug): ''' Detailed view of all tasks on given project ''' context = {} checklist = get_object_or_404(Checklist, slug=slug) context.update({'checklist':checklist}) form = NotesForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n for is valid") author = Profile.objects.get(user=request.user) new_note = form.save(commit=False) new_note.user = author new_note.checklist = checklist new_note.save() return redirect('task_detail', slug=slug) context.update({ 'form': form, 'title': checklist, }) return render(request, 'projects/checklist.html', context) @login_required def new_checklist_item(request, slug): if request.method == 'POST': form = CheckListItemForm(request.POST) form.save() return redirect('task_detail', slug=slug) The checklist item is on the same page as the task_detail view, above urls.py urlpatterns = [ path('projects/', teams, name='teams'), path('projects/project/<slug>/', projects, name='projects'), path('projects/tasks/<slug>/', project_detail, name='project_detail'), path('projects/checklist/<slug>/', task_detail, name='task_detail'), # Create a new checklist item path('projects/checklist/new_checklist_item/<slug>/', new_checklist_item, name='new_checklist_item'), ] Then the form class CheckListItemForm(forms.ModelForm): class Meta: model = ChecklistItem fields = ['item'] Want to create a new checklist item on the page, What am i doing wrong on the view, am i missing something? the html <!-- Form for creating new checklist --> <form method="POST" action="{% url 'new_checklist_item' title.slug %}" class="modal fade" id="checklist-item-add-modal" tabindex="-1" aria-hidden="true"> {% csrf_token %} <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> … -
Align models with TabularInline django admin with models
How best can I align well my models which are in a reverse relationship with the help of TabularInline, I tried the following below but failed : class SubTopicInline(admin.TabularInline): model = models.SubTopic class CourseAdmin(admin.ModelAdmin): inlines = [SubTopicInline] admin.site.register(models.Course, CourseAdmin) This is the error thrown : ERRORS: <class 'courses.admin.SubTopicInline'>: (admin.E202) 'courses.SubTopic' has no ForeignKey to 'courses.Course'. Then below is my models : class Course(TimeStampedModel, models.Model): """ Course model responsible for all courses. :cvar uid: UID. :cvar title: Course title. :cvar description: Description of the course. :cvar course_cover: Image for the course. :cvar category: Course Category. :cvar user: Author of the course. :cvar review: Course review. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Meta: verbose_name_plural = "Courses" class SubTopic(TimeStampedModel, models.Model): """ Subtopic for the course. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) sub_topic_cover = models.ImageField( _('Sub topic Cover'), upload_to='courses_images', null=True, max_length=900) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) course = models.ManyToManyField(Course, related_name='sub_topic', blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Sub topic" class Lesson(TimeStampedModel, models.Model): """ Lesson for the sub topic. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, …