Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
origin 'http://localhost' has been blocked by CORS policy on amazon-s3
I am trying to upload the data to S3 but CORS error occurs. https://s3.ap-northeast-1.amazonaws.com/my-dev-bot-resource-bucket/4252342.jpg?uploads' from origin 'http://localhost:8005' has been blocked by CORS policy CORS token is set in html <input type="hidden" name="csrfmiddlewaretoken" value="Zo84NgB4sm97d5NVtSXufVq7FpZmaiermOe96GSZgU4Mon8qaYbZsb9siW7gqBLg"> and I set CORS header [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD", "PUT", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Is there anything I need to check?? -
autoselect multiple select values when receiving data from database
I have a bootstrap-select with the attribute multiple data-max-options="2", let's use some example from the official docs <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta2/js/bootstrap-select.min.js"></script> <select class="selectpicker" multiple data-max-options="2"> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </select> Generally speaking, what I would do with single selects is: <select class="selectpicker" multiple data-max-options="2"> {% if meal.sauce == "Mustard" %} <option value="Mustard" selected>Mustard</option> <option value="Ketchup">Ketchup</option> <option value="Relish">Relish</option> {% elif meal.sauce == "Ketchup"%} <option value="Mustard">Mustard</option> <option value="Ketchup" selected>Ketchup</option> <option value="Relish">Relish</option> {% else %} <option value="Mustard">Mustard</option> <option value="Ketchup">Ketchup</option> <option value="Relish" selected>Relish</option> {% endif %} </select> In this way, depending on what we have in the database when we want to edit the select, it will be autoselected with the result of the database. The problem comes when we select more than one sauce and then we want to edit in another page. With a simple sauce, the edit is simple: meal.sauce == "Mustard" or whatever. With multiple select, I don't know how to implement the logic: meal.sauce == "Ketchup, Mustard" ? -
How to hide the icon from folium.Marker django
I am working on a map with folium. I have the HeatMap I want thanks to the code below. I want to add some metadata when the mouse hover over the place but the only way I have found is with the folium.Marker function but it also display a huge marker I would like to hide (it's ruining my HeatMap ...). m = folium.Map(location=[-17.4889,-149.90017], zoom_start=4, tiles='CartoDB Dark_Matter', control_scale=(True)) data_popup = SigCoord.objects.values_list('longitude', 'latitude', 'ile', 'site', 'programme', 'terme') for i in range(len(data_popup)) : m.add_child(folium.Marker(location = (data_filter[i][0], data_filter[i][1]), tooltip = "Ile : " + str(data_popup[i][2]) + '<br>' + "Site : " + str(data_popup[i][3]) + '<br>' + "Programme : " + str(data_popup[i][4]) + '<br>' + "Nombre de données sur ce site : " + str(data_popup[i][5]), icon = folium.Icon(icon='cloud', color='red'))) plugins.HeatMap(data_filter).add_to(m) folium.LayerControl().add_to(m) m = m._repr_html_() Do you have any idea of how can I do that or if there is another function I can use instead ? Thank you ! -
404 error when looking for page on Django site
I'm trying to create a media page on my site through Django. I'm following a course and I'm pretty stumped. I'm following exactly what the guy is doing but I keep getting the following error: Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order: admin/ ^media/(?P<path>.*)$ My settings.py: MEDIA_ROOT = BASE_DIR/'media' MEDIA_URL = '/media/' urls.py: from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) The problem arises as soon as I enter this line: + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) I haven't written anything in the views.py folders yet because the course hasn't required me to on this project so far. I'm just a newbie so I don't really have any clue what's happening when the code looks correct but I'm still running into the issue. Any help is appreciated. -
Django signals how to notify user on new reply?
Right now my author get notification through signals if anyone replied or comment. Let explain you this line of code little bit if instance.user.id != instance.blog.author.id: only triggering signals if user is not blog author. here is my code: models.py class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,blank=True,null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,blank=True,null=True) @receiver(post_save,sender=BlogComment) def NotiFicationSignals(instance,created,**kwargs): if created: if instance.user.id != instance.blog.author.id: #notifiy author noti_to_author = Notifications.objects.create(duplicate_value="author",sender=instance.user,receiver=instance.blog.author,text_preview=f"Recived new comment from {instance.user}") Now I want to create notifications object for commenter if any reply added on his comment. -
Cannot assign object must be of instance
I have these Models: class InvestorProfile(SealableModel): investor_type = models.CharField(max_length=200, choices=investor_type_choices) account = models.ForeignKey('app.Account', related_name='add_account_investorprofile', blank=False, null=False, on_delete=models.CASCADE) class Account(SealableModel): contact = models.OneToOneField('app.Contact', on_delete=models.CASCADE) class Contact(SealableModel): firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=200) and I want to add a Contact, Account, and an InvestorProfile respectively when importing InvestorProfile using django-import-export. The way I'm doing it is with django-import-export's after_import_instance. def after_import_instance(self, instance, new, row_number=None, **kwargs): """ Create any missing Contact, Account, and Profile entries prior to importing rows. """ try: # check if the investor type is company, ind, etc. # retrieve the correct object depending on the investor type # do the logic below if self.investorprofile__add_associated_account__contact__email: # create contact first contact, created = Contact.objects.seal().get_or_create(email=self.investorprofile__add_associated_account__contact__email) # add firstname and lastname contact.firstname = self.investorprofile__add_associated_account__contact__firstname contact.lastname = self.investorprofile__add_associated_account__contact__lastname # save contact.save() # # check if account exists account, created = Account.objects.seal().get_or_create(contact=contact) # # check if investorprofile exists investorprofile, created = InvestorProfile.objects.seal().get_or_create(add_associated_account=account, investor_type=self.investorprofile__investor_type) instance.investorprofile = investorprofile except Exception as e: print(e, file=sys.stderr) Everything looks fine until I encounter this in the error message view: INVESTORPROFILE__ADD_ASSOCIATED_ACCOUNT Cannot assign "'sample@email.com'": "InvestorProfile.add_associated_account" must be a "Account" instance. which is confusing since this line returns an account object. # # check if account exists … -
How django forms works?
I'm using CreateForm like below. I expect it makes error but It works well. I don't understand why It works. Django User dosen't have email2 fields. class CreateForm(UserCreationForm): email2 = forms.EmailField(label = 'email2') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs.update({'class': 'form-control', 'ALIGN': 'center'}) self.fields[field].help_text = '' self.fields[field].error_messages = '' class Meta: model=User fields=("username","email","email2", "last_name","password1","password2") labels = { 'username' : 'id', 'last_name' : 'name', 'email' : 'certification email', } Before __init__, Dose form add Meta email2? what is sequence of this form? -
How do I uninstall django from windows? I get permission error like the pic. Also I get these import errors and exceptions in Pycharm using django. I
PermissionError: [WinError 5] Access is denied: 'c:\program files\python310\lib\site-packages\django-3.0.14.dist-info\AUTHORS' ![1]: https://i.stack.imgur.com/E4Tfk.png -
Django Gunicorn restart updating fields
I've noticed strange behavior whenever I upload to the server with local changes I have. The database for Django takes all my objects and sets the "updated_by" and "update" fields to the time that I updated the server... Maybe I'm not correctly uploading changes to my server. What I'm using: Ubuntu 18.04.6 Nginx Gunicorn Mysql Python 3.6.12 Django 3.2.9 I generally run: git pull pipenv run python3 manage.py migrate sudo systemctl restart gunicorn sudo systemctl restart nginx I don't run pipenv run python3 manage.py migrate unless I have migrations to run, doesn't affect outcome. Here's the field on my model associated with the weird updating: updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='updated_by', verbose_name='Last edited by') Any ideas on what I may be doing wrong, or what might be causing this? -
Django dynamic URL in template not working
I have a table where I'd like each row to link to a different "view" page. Essentially the final url should look something like: siteurl.com/view/<campaign_id>/<user_emp_id>/ I've tried doing href={% url 'view/'|add:'{{campaign.id}}'|add:'/'|add:'{{user.pid}}'|add:'/' %} with no luck. I've also attempted other variations of this with no success as well. The error I receive is: Reverse for 'view/{{campaign.campaign.id}}/{{user.pid}}/' not found. 'view/{{campaign.campaign.id}}/{{user.pid}}/' is not a valid view function or pattern name. The url in urls.py is defined as re_path(r'^view/(?P<campaign_id>\w+)/(?P<user_pid>\w+)/$', views.view, name='view') This works just fine when typing it in manually but I'm having a lot of trouble trying to link to it in the template itself Any ideas on how I could accomplish this? -
How to make always active session for postgresql?
Previously, I had a django application/database on the same server. Now I have made one server with application, one server with database(Debian 11; Postgresql 12.9 (Install via Homebrew)) Problem: after a few hours there are problems with connecting to the database... postgres log: 2022-01-24 23:27:00.315 UTC [9982] LOG: received smart shutdown request 2022-01-24 23:27:00.323 UTC [9982] LOG: background worker "logical replication launcher" (PID 9996) exited with exit code 1 2022-01-24 23:27:00.324 UTC [9991] LOG: shutting down 2022-01-24 23:27:00.344 UTC [9982] LOG: database system is shut down /var/log/syslog: Jan 24 23:27:00 d systemd[1]: Stopping User Manager for UID 1000... Jan 24 23:27:00 d systemd[8909]: Stopped target Main User Target. Jan 24 23:27:00 d systemd[8909]: Stopping D-Bus User Message Bus... Jan 24 23:27:00 d systemd[8909]: Stopping Homebrew generated unit for postgresql@12... Jan 24 23:27:00 d systemd[8909]: dbus.service: Succeeded. Jan 24 23:27:00 d systemd[8909]: Stopped D-Bus User Message Bus. Jan 24 23:27:00 d systemd[8909]: homebrew.postgresql@12.service: Succeeded. Jan 24 23:27:00 d systemd[8909]: Stopped Homebrew generated unit for postgresql@12. Jan 24 23:27:00 d systemd[8909]: homebrew.postgresql@12.service: Consumed 1min 22.614s CPU time. Jan 24 23:27:00 d systemd[8909]: Removed slice app-homebrew.postgresql.slice. Jan 24 23:27:00 d systemd[8909]: app-homebrew.postgresql.slice: Consumed 1min 22.614s CPU time. Jan 24 23:27:00 d systemd[8909]: Stopped … -
Why am I not getting any feedback as to whether my form is completed correctly or incorrectly? Python, Django
I'm working in Django with Python, and here are is my views.py def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() auth_login(request, user) print("success") return render(request, 'Upload.html', {}) # messages.success(request, "Regisration successful.") # print("hello") return render(request, "Home.html") else: print(form.errors) return render(request, 'Register.html', {'form': form}) form = NewUserForm() return render(request, 'Register.html', context={"form":form}) This is my HTML {% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href=" {% static 'website/Register.css' %} " media="screen"> {% endblock %} {% block content %} <section class="u-align-center u-clearfix u-section-1" id="sec-6951"> <div class="u-clearfix u-sheet u-sheet-1"> <div class="u-align-center u-form u-form-1"> <form action="#" method="POST" class="u-clearfix u-form-spacing-10 u-form-vertical u-inner-form" source="custom" name="form" style="padding: 10px;"> {% csrf_token %} <div class="u-form-email u-form-group"> <label for="email-87f0" class="u-label">Email</label> <input type="email" placeholder="Enter a valid email address" id="email-87f0" name="email" class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white" required=""> </div> <div class="u-form-group u-form-name"> <label for="name-87f0" class="u-label">Username</label> <input type="text" placeholder="Create a username" id="name-87f0" name="username" class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white" required=""> </div> <div class="u-form-group u-form-name u-form-group-3"> <label for="name-12e6" class="u-label">Password</label> <input type="text" placeholder="Create a password" id="name-12e6" name="password1" class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white" required=""> </div> <div class="u-form-group u-form-name u-form-group-4"> <label for="name-12e6" class="u-label">Verify Password</label> <input type="text" placeholder="Verify your password" id="name-12e6" name="password2" class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white" required=""> </div> … -
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>