Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't upload multiple large files
I am developing an application with Django, AWS S3 and hosted on Heroku. At one point users have to upload multiple large files, totaling around 150MB each time. I have tried various approaches. 1st attempt: directly call the save method of the Django form: Result: the request takes more than 30 seconds and returns a timeout. 2nd attempt: temporarily save the file to a Heroku directory and read it from Celery task. Result: Cannot save because it throws FileNotFoundError: [Errno 2] No such file or directory on production. 3rd attempt: pass the uploaded files (in memory files) to a celery task but the bytes cannot be serialized and passed to the task neither with json or with pickle. Could anyone help me please? Thanks advance. -
Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['wiki/edit/(?P<entry>[^/]+)/$']
I'm trying to build an wiki page, already searched through other posts but couldn't solve my problem, someone can help? I'm getting the following error: Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['wiki/edit/(?P[^/]+)/$'] Basically what it is, is an edit page to edit an wiki entry, the button to edit the entry is located at entry.html, this is supposed to send the entry name as a parameter to edit.url then i edit it and send through POST the new content to override the actual content of the entry. Here is my views.py def edit(request, entry): if request.method == 'POST': content = request.POST.get('edit') util.save_entry(entry, content) return render(request, "encyclopedia/entry.html", { "entry": markdown2.markdown(util.get_entry(entry)), "title": entry }) else : return render(request, "encyclopedia/edit.html", { "entry": entry }) Here is my urls.py from django.urls import path, re_path from . import views app_name = "encyclopedia" urlpatterns = [ path("", views.redirect, name="redirect"), path("wiki", views.index, name="index"), path("wiki/search/", views.search, name="search"), path("wiki/newentry", views.new, name="new"), path("wiki/edit/<str:entry>/", views.edit, name="edit"), path("wiki/<str:entry>", views.entry, name="entry") ] And my edit.html {% extends 'encyclopedia/layout.html' %} {% block title %} Edit Page {% endblock %} {% block body %} <form action="{% url 'encyclopedia:edit' %}" method="POST"> {% csrf_token %} <label for="edit">Edit {{ entry }}</label> <textarea id="edit" … -
The href in template and the Url are not working in Django
I am new to django. I have made a table cell clickable but when i click that cell, nothing happens. template : {% for each in object_list %} <tr> <td id="{{ each.id }}" data-href="http://127.0.0.1:8000/{{ each.region }}/{{ each.id }}"></td> </tr> {% endfor %} needed part of view: class MeterDetailView(DetailView): model = Meter template_name = 'meter/specificMeter.html' def get_context_data(self, **kwargs): pk = kwargs.get('pk',None) obj = Meter.objects.get(pk=pk) url : path('<int:region>/<int:pk>/', views.MeterDetailView.as_view(), name='detail'), what is wrong?Thank you all. -
How to get InMemoryUploadedFile into FileField?
Context: pip freeze: asgiref==3.2.10 dist==1.0.3 Django==3.1.2 PyMySQL==0.10.1 pytz==2020.1 sqlparse==0.4.1 python --version: Python 3.6.7 email.html: {{ recipient_form }} {{ body_form }} {{ attachments_form }} urls.py urlpatterns = [ path('email/<int:email_id>', email.index, name='email') ] views.py: def index(request, email_id=None): context = { 'bucket': settings.BUCKET_URL, # where files are stored 'recipient_form': RecipientForm(prefix='recipient'), 'body_form': BodyForm(prefix="body"), 'attachments_form': AttachmentForm(prefix='attachments') } if email_id is not None and Email.objects.filter(pk=email_id).exists(): email = Email.objects.get(pk=email_id) if request.method == 'POST': recipient_form = RecipientForm(request.POST, prefix='recipient') body_form = BodyForm(request.POST, prefix='body') attachments_form = AttachmentForm(request.FILES, prefix='attachments') if recipient_form.is_valid() and body_form.is_valid() and attachments_form.is_valid(): # here is where things got messy.. recipient = recipient_form recipient.email = email recipient.save() body = body_form body.email = email body.save() attachments = attachments_form attachments.email = email attachments.save() return render(request, 'email.html', context) forms.py # ... class AttachmentForm(ModelForm): class Meta model = Attachment fields = ['file'] # ... models.py #... def attachment_handler(instance, filename): upload_to = 'attachments' return os.path.join(upload_to, filename) class Attachment(models.Model): email = models.ForeignKey(Email, on_delete=models.CASCADE) file = models.FileField(upload_to=attachment_handler, null=True, blank=True) datestamp = models.DateTimeField(auto_now_add=True, null=True) #... Goal: Upload multiple files in a FileField through preferably ModelForm. If not possible, only one per Attachment So far: I can upload a single file with no error through the ModelForm but it doesn't persist as seen in the built-in admin panel … -
Django - Inline search for users in admin
I need to create an "inline search" in my admin page, and I don't know where to start from. The idea is replace that "----" for the search bar, or just let to type in the "User: " bar, that doesn't matter. If possible, I wanted to do the same thing in the "Account: " bar. Note: when you click the bar, it opens a column with data etc. Click here to see the printscreen, please. # admin.py class UserCreateForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name' , 'last_name', 'email', 'is_staff', 'is_superuser' ) class UserAdmin(UserAdmin): add_form = UserCreateForm prepopulated_fields = {'username': ('first_name' , 'last_name')} add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'is_staff', 'is_superuser' ), }), ) class AccountAdmin(admin.ModelAdmin): search_fields = ['name', 'email', 'phone', 'id', 'document', 'subscriber_code'] list_filter = ['status'] class UserAccountAdmin(admin.ModelAdmin): search_fields = ['account__id', 'account__name', 'user__first_name', 'account__subscriber_code'] list_filter = ['is_superuser'] # userAccount.py from django.db import models from django_mysql.models import JSONField, Model from django.utils import timezone from django.contrib.auth.models import User from .account import Account from .resource import Resource class UserAccount(models.Model): id = models.AutoField( db_column='uacId', primary_key=True ) user = models.ForeignKey( User, db_column='uacUseId', on_delete=models.CASCADE, null=True ) account = models.ForeignKey( Account, db_column='aucAccId', on_delete=models.CASCADE, null=True ) … -
How can I solve the 29 unapplied migration(s) for app(s): admin, api, auth, authtoken, contenttypes, sessions, social_django
I was setting up Doccano on my desktop to perform sequence labeling tasks. I followed the instructions from a website on how to setup Doccano. Everything was working fine until I got to the last code below where I experienced migration errors. $ git clone https://github.com/chakki-works/doccano.git $ cd doccano $ pip install -r requirements.txt $ cd app $ python manage.py createsuperuser This is the error below after running the last code above on git bash You have 29 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, api, auth, authtoken, contenttypes, sessions, social_django. Run 'python manage.py migrate' to apply them. Traceback (most recent call last): File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: auth_user The error says to Run 'python manage.py migrate. When I ran the code in my terminal I got an [Errno 2] No such file or directory. Please see below. Thanks … -
Can you load data and process it while your application is loading in django
I have a django application that I'm responsible for. My stack is: Python 3.6, Django 2.2.14, Pandas, Plotly.py, Jquery, Html, CSS I'm using prebuilt classes to create the various charts and graphs. I don't have control over these classes and I can't really refactor them. The classes preprocess ALL charts and graphs that will be used throughout the web app. They are created all at once while the first page loads. Since I cannot redesign this app to create the charts and graphs as needed, I'm wondering if its possible to load them before hand and then pass a reference to them when the application initializes. -
How to measure number of hours user spent in a day on the website using django?
How to measure number of hours user spent on my website in a day and show it graphical in a bar graph. -
How to use RelatedFieldWidgetWrapper in django 3
What should I put in rel and admin site? This is the field in my form: tutor_temporal = forms.ModelChoiceField(queryset=Tutor_temporal.objects.all(),label='Tutor No Registrado', required=False, widget=RelatedFieldWidgetWrapper(widget=forms.Select(attrs={'class': 'input is-small is-rounded '}),rel=Tutor_temporal._meta.get_field('id').rel,admin_site= admin_site)) The problem is that when I try that, throws this AttributeError: 'AutoField' object has no attribute 'rel', because apparently is deprecated. -
Django: Slug url is ignored
For some reason when i go /app/stream/singles/4/audioFull/ i get a 'Page not found' error. My urls.py: from .Views import single_stream from django.urls import path, include urlpatterns = [ path('', single_stream.Full.as_view()), path('singles/', include([ path('<slug:song>/', include([ path('', single_stream.Full.as_view()), path('audioFull', single_stream.Full.as_view(), name='stream-single-full'), path('audio-snippet', single_stream.AudioSnippet.as_view(), name='stream-single-snippet'), path('video-snippet', single_stream.VideoSnippet.as_view(), name='stream-video-snippet') ])) ])) ] I have registered the app and all of that. Going to app/stream works but the slug field <slug:song>/ does not work at all. -
How to upload file in AWS S3 with django app?
I am facing a problem uploading the user profile picture. Now when I create a user in Django admin and upload a file from the admin dashboard it works correctly and no errors. It goes to my AWS S3 bucket as it should go, but this is obviously not feasible, I have been looking for the solution for 3 to 4 days but no success or any satisfactory results. I obviously won't be providing the dashboard access to the user. The database used is MongoDB, with a database engine as djongo. Here is my settings.py INSTALLED_APPS = [ 'profileupload', 's3direct', 'storages', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', ] STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AWS_SECRET_ACCESS_KEY = 'MY_SPECIAL_KEY' AWS_ACCESS_KEY_ID = 'MY_SPECIAL_KEY_NAME' AWS_STORAGE_BUCKET_NAME = 'S3_BUCKET' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' My urls.py from django.urls import path, include from .views import signup_form urlpatterns = [ path('signup', signup_form, name='signup'), ] My models.py class profile(models.Model): profile_id = models.AutoField(primary_key=True,unique=True) profile_username = models.CharField(max_length=100,unique=True) profile_name = models.CharField(max_length=150) profile_email = models.EmailField(max_length=200) profile_create_time = models.DateField(auto_now_add=True) profile_dob = models.DateField() profile_password = models.CharField(max_length=50, null=True) profile_picture = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return str(self.profile_username) My views.py def signup_form(request): if request.method == 'POST': if request.POST.get('profile_username') and … -
hello i hope you have a good day i have problem i have an store project use django
i have an account app and have order add when customer make a order they should fill an form and if they make another order they should fill the same form i want to make customer when make account and make his first order and fill the form dose not fill this form again and save this form in his profile and make orders as much he need. and if you need any files support just told my -
Customizing the Submissions List View in Wagtail
I'm trying to subclass the SubmissionsListView for the Wagtail admin. I'm following the instructions from this tutorial and this one. Here's my code: class CustomSubmissionsListView(SubmissionsListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if not self.is_export: # generate a list of field types, the first being the injected 'submission date' field_types = ['user'] + [field.field_type for field in self.form_page.get_form_fields()] data_rows = context['data_rows'] DocumentModel = get_document_model() for data_row in data_rows: fields = data_row['fields'] for idx, (value, field_type) in enumerate(zip(fields, field_types)): if field_type == 'document' and value: doc = DocumentModel.objects.get(pk=value) url = reverse('wagtaildocument:edit', args=(doc.id,)) # build up a link to the image, using the image title & id fields[idx] = format_html( "<a href='{}'>{}</a>", url, doc.title, value ) return context The error I'm getting is: File "/home/dave/sandbox/clients/devnw/devnw/web/products/models.py", line 161, in get_context_data if not self.is_export: AttributeError: 'CustomSubmissionsListView' object has no attribute 'is_export' I cannot figure out what is going on. The `is_export' does exist on the parent module. Any pointers? -
Django python pagination always displaye the first 2, and last 2 pages
I have some pagination for a table. I have it so that it will only show 3 pages either side of the current page. However if I am on the 5th page, The first page disappears. I am trying to set it up so that the first two and last two pages of the pagination are always visible regardless of what the current page is. code: {% if is_paginated %} <div class="pagination"> {% if current_page.has_previous %} <a class="page-link" style="font-size: 24px; padding: 2px;" href="?page={{ current_page.previous_page_number }}">&#171;</a> {% else %} <a class="page-link" style="font-size: 24px; padding: 2px;" href="">&#171;</a> {% endif %} {% for i in current_page.paginator.page_range %} {% if current_page.number == i %} <a class="page-link active" href="">{{ i }}</a> {% else %} {% if current_page.number|add:-4 == i %} <a class="page-link" href="">...</a> {% endif %} {% if current_page.number|add:3 >= i and current_page.number|add:-3 <= i %} <a class="page-link" href="?page={{ i }}">{{ i }}</a> {% endif %} {% if current_page.number|add:4 == i %} <a class="page-link" href="">...</a> {% endif %} {% endif %} {% endfor %} {% if current_page.has_next %} <a class="page-link" style="font-size: 24px; padding: 2px;" href="?page={{ current_page.next_page_number }}">&#187;</a> {% else %} <a class="page-link" style="font-size: 24px; padding: 2px;" href="">&#187;</a> {% endif %} </div> {% endif %} Screenshot: -
Uncaught ReferenceError: postid is not defined during creating comment system with django and ajax jquery
Well I am trying to create commenting system with django ,ajax ,jquery but I am having an issue it giving Uncaught ReferenceError: postid is not defined error in console. But i don't get it how can i fix it. Please it a humble request if you know the answer than must answer. I have literally tried a lot to fix but i couldn't fix it out. html comment form: <form id='commentform' class='commentform' method='POST'> {% csrf_token %} {% with allcomments as total_comments %} <p>{{ total_comments }} comment{{total_comments|pluralize}}</p> {% endwith %} <select name='post' class='d-none' id='id_post'> <option value="{{ post.id }}" selected="{{ post.id }}"></option> </select> <label class='small font-weight-bold'>{{comment_form.parent.label}}</label> {{comment_form.parent}} <div class='d-flex'> <img class='avatar_comment align-self-center' src="{% for data in avatar %}{{data.avatar.url}}{%endfor%}"> {{comment_form.body }} </div> <div class='d-flex flex-row-reverse'> <button type='submit' class='newcomment btn btn-primary' value='commentform' id='newcomment'>Submit</button> </div> </form> ajax comment form for replying of specific comment. <script> function myFunction(id) { if (document.contains(document.getElementById("newcommentform"))) { document.getElementById("newcommentform").remove(); } var d1 = document.getElementById(id); console.log(d1,'this is ') d1.insertAdjacentHTML('afterend', '<form id="newcommentform" class="commentform" method="post"> \ {% csrf_token %} \ <select name="post" class="d-none" id="id_post"> \ <option value="' + postid + '" selected="' + postid + '"></option> \ </select> <label class="small font-weight-bold"></label> \ <select name="parent" class="d-none" id="id_parent"> \ <option value="' + id + '" selected="' + … -
Need a server that be able to upload Django app using TensorFlow
I am new in Django and web development. I have a Django project that is using Tensorflow v.2.3. I tried to make it online by "pythonanywhere.com," but it appears that this server has serious issues with the TensorFlow library. So, I would like to know if you might have any suggestion for my project. -
I am using Django password reset view but I am getting error after the password confirm page." parameter 'form' should contain a valid Django Form."
accounts\urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from .import views app_name ='accounts' urlpatterns = [ url(r'login/$', auth_views.LoginView.as_view(template_name='accounts/login.html'),name='login'), url(r'logout/$',auth_views.LogoutView.as_view(),name='logout'), url(r'Signup/$',views.SignUp.as_view(),name='signup'), path('password_reset', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset_form.html',email_template_name='accounts/password_reset_email.html',subject_template_name='accounts/password_reset_subject.txt', success_url='password_reset_done') ,name='password_reset'), path('password_reset_done/',auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'),name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>',auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html',success_url='password_reset_complete'),name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'),name='password_reset_complete'), ] accounts\views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from . import forms class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html' Error I am getting after submitting the confirm page BootstrapError at accounts/password_reset_confirm/NA/password_reset_complete Parameter "form" should contain a valid Django Form. Request Method: GET Django Version: 3.0.3 Exception Type: BootstrapError. Exception Value: Parameter "form" should contain a valid Django Form. Exception Location: C:\Users\gags2\anaconda3\envs\carDjangoEnv\lib\site- packages\bootstrap4\renderers.py in init, line 144 -
Django AttributeError at /company-registration/
I have a User model, an ApplicantProfile model, and a CompanyProfielModel. A user can be of two types, an applicant or a company. models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) date_joined = models.DateTimeField(auto_now_add=True) is_applicant = models.BooleanField(default=False) is_company = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = MyUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True class ApplicantProfile(models.Model): GENDER_MALE = 0 GENDER_FEMALE = 1 GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')] user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) image = models.ImageField(upload_to=image_directory_path, storage=image_storage, null=True, blank=True) bio = models.TextField(max_length=500, null=True, blank=True) address = models.TextField(max_length=200, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) phone = PhoneNumberField(null=True, blank=True) website = models.URLField(max_length=255, null=True, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, null=True, blank=True) interest = models.TextField(max_length=255, null=True, blank=True) linkedin = models.CharField(max_length=255, null=True, blank=True) github = models.CharField(max_length=255, null=True, blank=True) twitter = models.CharField(max_length=255, null=True, blank=True) facebook = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.user.name class CompanyProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) image = models.ImageField(upload_to=image_directory_path, storage=image_storage, null=True, blank=True) about = models.TextField(max_length=500, null=True, blank=True) location = models.CharField(max_length=100, null=True, blank=True) start_date = models.DateField(null=True, blank=True) website = models.URLField(max_length=255, null=True, blank=True) logo = models.ImageField(upload_to=image_directory_path, storage=image_storage, null=True, blank=True) def __str__(self): return self.user.name I … -
Using django to store multiple instances inside a table which uses a foreign key from another table
I am making an accounting solution using Python Django for a medium-sized business (B2C and B2B) and currently I am stuck while coming up with a way to add more than one product in a single invoice. I have a Customer model that stores customer's detail, an Invoice model that, when created, generates an invoice id which I use in my InvoiceDetail model to add more than one product to a single invoice. The problem is that I have to manually create instances every single time I add a product to that invoice which asks me the invoice id to link the detail of invoice to that particular invoice id I have tried making a forms.py file to manually generate a form and then use request object to extract all the details but that did not work either as I needed to first have an invoice_id which would then be used a foreign key in the InvoiceDetail I am using generic Create, Update and Delete views currently Here is my Customer model: class Customer(models.Model): customer_id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=100, help_text='Name of your customer') phone = models.CharField(max_length=11, validators=[phone_num_validator]) email = models.EmailField(max_length=100, blank=True, validators=[email_validator]) address = models.CharField(max_length=200) company = models.CharField(max_length=200) … -
How do I get ride of this error, "Unknown column 'history_change_reason'"?
Hello stackoverflow community, I am running into this error when I try to write to my database. I can't seem to find column history_change_reason in my database through mysqlWorkbench. Anyone else dealt with this before? File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/base.py", line 822, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/base.py", line 861, in _do_insert using=using, raw=raw) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/query.py", line 920, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 963, in execute_sql cursor.execute(sql, params) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) OperationalError: (1054, "Unknown column 'history_change_reason' in 'field list'") -
How to get a information from a model in Django via it's user id in the url?
I'm trying to fetch the Player information that has a certain user_id directly in my url. I know I can get info by the Player id by simply passing a number, but how can I get the player based on its user_id? Is this possible? fetch(`http://localhost:8000/api/players/PASS_USER_ID_HERE_NOT_PLAYER_ID`) class Player(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) national_id = models.CharField(max_length=10, unique=True, blank=False) class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = '__all__' -
SEO and Django with title and description tags
I have a base.html for the base template for my files. Inside of it, I have tag where I define both title and description tags. I also have my home page that is home.html that doesn't need a specific title or description and the general one for the whole website would do. I also have detail.html which is the HTML that I use for every blog post where I am trying to improve SEO with using these tags <meta name="description" content="{{ blog.formatted_summary|striptags }}"> <title>{{ blog.title|safe }}</title> First off in HTML, it is not in the tag as it is already used. Secondly, I am basically defining both title and description twice and I can't think why that would be a good idea. How do I insert the title and description into the base.html so if it is a blog post that I can specify to take the body or the summary as a description without defining the properties again? -
passenger_wsgi.py error in apache django vps
I have am trying from last three days to configure simple django application on my vps using plesk with centos 8 , and its been very frustrated to do it. I am receiving passenger_wsgi.py error . I have followed this tutorial How to allow installing and install Django applications? and this How to set up Django Hosting on the latest Plesk Onyx both worked out in centos 7 but not in 8. This is my server logs 2020-10-22 17:35:17Error162.158.165.79500GET / HTTP/1.0 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 4.53 KApache access 2020-10-22 17:45:44Error162.158.166.232500GET / HTTP/1.0 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 4.53 K Apache access 2020-10-22 17:45:45Error162.158.166.154500GET / HTTP/1.0 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 4.53 Apache access Error ID: 6cd697b9 Details: Web application could not be started by the Phusion Passenger application server. Its because of internal server error but how to resolve this ? this is the passenger_wsgi.py file import sys, os ApplicationDirectory = 'tayyab' ApplicationName = 'djangoProject' VirtualEnvDirectory = 'venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) … -
How to show only 1 image from an image list/set on the homepage in django html homepage template?
I am trying to show only 1 image from a list of images on the homepage. I am using django and its template engine. I use a formset to upload images onto the database, now the problem is when I loop through the list in the homepage, it shows all the images, I want to show only the first image from the set in the homepage. How to implement that? This is the code I have. {% for image in post.postimage_set.all %} <img class="" style="content: center" height="300" width="300" src="{{ image.images.url }}" /> {% endfor %} Thank you! -
Access to M2M self 'through' object
Specifying a through='' model for django's ManyToManyField seems fairly straight-forward, however when setting to 'self', I'm not understanding how queries should realistically look. Say for example I have these models: class Person(models.Model): name = models.CharField(max_length=120) friends = models.ManyToManyField('self', through='Friendship') class Friendship(models.Model): person_one = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="person_one_friendships") person_two = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="person_two_friendships") date_created = models.DateTimeField(auto_now_add=True, blank=True) This becomes complicated because of fields person_one and person_two. When doing reverse lookups, I'd need to query against both fields for finding the friendship between two persons. Here's an example of where it should be really easy to retrieve the through object of Friendship between two persons, but instead I have to use Q() objects or use both reverse lookups: person = Person.objects.filter(name="Kevin").first() for friend in person.friends.all(): # Approach 1: Use Q() objects on Friendship model person_1_q = Q() person_1_q |= Q(person_one=person) person_1_q |= Q(person_two=person) person_2_q = Q() person_2_q |= Q(person_one=friend) person_2_q |= Q(person_two=friend) friendship = Friendship.objects.filter(person_1_q, person_2_q).first() # Approach 2: Use both reverse_lookups on Person object friendship = friend.person_one_friendships.filter(pk=person.pk).first() if not friendship: friendship = friend.person_two_friendships.filter(pk=person.pk).first() Both approaches seem like a lot more work than necessary. Am I overlooking something?