Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Resetting django_sessions
I was playing around with storing session ids for anonymous users in django models using django.contrib.sessions.models and tested all browsers on my machine creating different keys sometimes based on the real and incognito sessions. I followed it up by deleting my database and creating a new one as part of my tests and development emptying out all tables. I am noticing now that when I revisit the site from the same computer/browser, django does NOT create and store a new session id even though the table is empty which means that the server is storing the information that I previously visited the site as an anon user somewhere other than the django_sessions table. I tested clearing out my cookies and history but that did not help. Does anyone know where that information is stored, why, and how can I reset it? This is an issue mainly because I am using the session id as foreignkey and if i do end up deleting the database after deployment for any reason, i dont want the program to not work properly. Using python 3.8 and django 3.0.2 Thanks. -
Is there a way to combine a function that passes object information to a url and CreateView in Django?
I'm still learning Python and Django, so please be courteous. I am trying to make a shopping cart element where a product detail view, that displays product information, has an add to cart feature. My thought process was to make a page that contains the information of a specific object but also allows for the page to be a CreateView that doesn't display a place to input information but has preset object information to create a clone of the product changing one variable to a certain User. That User can then go to a personal shopping cart where it just lists all the products under his/her Username. The problem is, I can't combine these two things together and it's clearly based on a lack of ability (It's either the dynamic_lookup_view gives information or the CreateView gives a form, not both). I've tried using get_context_data and forms of mixins, even placing the function in the class. Some guidance or a pearl to the right track would be greatly appreciated. Here is my views.py class ProductCreateView(CreateView): template_name = '../templates/product/product_detail.html' fields = [ 'title', 'description', 'category', 'price', 'summary', 'image', 'user', ] model = Product def dynamic_lookup_view(request, id): obj = get_object_or_404(Product, id=id) context = … -
Are there any equivalents of isfile() or isdir() in Django Template Language?
I want to achieve something like {% for file in fileList %} {% if file isfile %} <a href="{% url 'GA:download' file %}">{{file}}</a><br> {% endif %} {% endfor %} or should I just change the context I gave to the template? My views.py looks like this def index(request): fileList = os.listdir(settings.MEDIA_ROOT) context = {'fileList':fileList} return render(request, 'gallery/index.html', context) -
Update foreign key of one model based on another model
I have a student model: class Student(User): religion = models.ForeignKey( Religion, on_delete=models.SET_NULL, null=True) caste = models.ForeignKey(Caste, on_delete=models.SET_NULL, null=True) date_of_birth = models.DateField(default=timezone.now) parent_name = models.CharField(max_length=255, default=None) address = models.CharField(max_length=255, default=None) phone_number1 = models.CharField( "Phone Number 1", max_length=10) phone_number2 = models.CharField( "Phone Number 2 (optional)", max_length=10, blank=True) classes = models.ForeignKey( Class, on_delete=models.SET_NULL, default=None, null=True, blank=True) def __str__(self): return self.first_name+" "+self.last_name # Control model features class Meta: verbose_name = 'Student' verbose_name_plural = 'Students' And an admission model: class Admission(models.Model): admission_date = models.DateField() classes = models.ForeignKey( Class, on_delete=models.SET_NULL, null=True) student = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True) Also a class model that takes in all the information of the class the student is in: class Class(models.Model): class_name = models.CharField( max_length=10, default=None ) division_name = models.CharField( max_length=10, default=None ) class_teacher = models.ForeignKey( Teacher, on_delete=models.SET_NULL, default=None, null=True, blank=True) institute = models.ForeignKey( Institute, on_delete=models.SET_NULL, default=None, null=True, blank=True) def __str__(self): return self.class_name+" "+self.division_name+" "+self.institute.name # Control model features class Meta: verbose_name = 'Class' verbose_name_plural = 'Classes' I want to achieve the following: change student info based on the admissions model. When I update the Admission info, it should take the class and update the class in the student model based on the class provided in the admission model. How can … -
how to convert raw into Django ORM query?
i have a raw query like SELECT A. * FROM `protein id` A INNER JOIN(SELECT features FROM `protein id` GROUP BY features HAVING COUNT(*) > 1) B ON A.features = B.features i had run the raw query in cursor function but it will return only count not values cursor.execute('''SELECT A. * FROM `protein id` A INNER JOIN(SELECT features FROM `protein id` GROUP BY features HAVING COUNT(*) > 1) B ON A.features = B.features''') thanks for the contributions -
django UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0
I deploy a django application to Docker. Everything works fine in local enviroment(Windows 10, django 2.2.10, Pyhon 3.7). Howerver, when deploy to Docker, I got UnicodeDecodeError. here are the Trackback: Traceback (most recent call last): File "run_uvicorn.py", line 26, in <module> main() File "run_uvicorn.py", line 14, in main configurations.setup() File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/configurations/__init__.py", line 31, in setup _setup() File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/configurations/__init__.py", line 17, in _setup django.setup() File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/contrib/auth/models.py", line 95, in <module> class Group(models.Model): File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/db/models/base.py", line 156, in __new__ new_class.add_to_class(obj_name, obj) File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/db/models/fields/related.py", line 1588, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/db/models/fields/related.py", line 1057, in create_many_to_many_intermediary_model 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/utils/functional.py", line 192, in __mod__ return str(self) % rhs File "/home/ec2-user/.local/share/virtualenvs/spots-6d0OxoJW/lib/python3.7/site-packages/django/utils/functional.py", line 156, … -
why supervisor gunicorn shows fatal error command not found?
when i check status it is shwoing this guni:gunicorn FATAL can't find command '/home/ubuntu/myvenv/js/bin/gunicorn' and my gunicorn conf is like this [program:gunicorn] directory=/home/ubuntu/js/main_jntu command=/home/ubuntu/myvenv/js/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/js/app.sock main_jntu.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn after this when i check status it shows an error like this guni:gunicorn FATAL can't find command '/home/ubuntu/myvenv/js/bin/gunicorn' -
Issue while integrating bootstrap template in a django project
I am trying to integrate bootstrap template with one of my Django project. I mostly succeeded in doing so and was able to render all the images and other stuff of the template to my django project. But the actual formatting of the template was lost while integrating. I found the below error while doing so, need help to understand and find remedy to the error. Below is the error from my cmd. File "C:\Users\DELL\Anaconda3\lib\site-packages\django\utils\_os.py", line 46, in safe_join 'component ({})'.format(final_path, base_path)) django.core.exceptions.SuspiciousFileOperation: The joined path (S:\stackpath.bootstrapcdn.com\bootstrap\4.4.1\js\bootstrap.min.js) is located outside of the base path component (C:\Users\DELL\community@with_final_template 7 Feb 2020\static) [09/Feb/2020 10:46:44] "GET /static/https%3A/stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js HTTP/1.1" 500 59 Not Found: /favicon.ico [09/Feb/2020 10:46:44] "GET /favicon.ico HTTP/1.1" 404 6333 -
i want to count the number of order per day in weekly base with dynamically via order updated field using django
my model is class Order(models.Model): STATUS =( ('Processed','Processed'), ('Cancelled','Cancelled'), ('Pending','Pending'), ) client = models.ForeignKey(User, on_delete=models.CASCADE) OrderDate = models.DateField(default=timezone.now) delivery_date = models.DateField(null=True, blank=True) Regular = models.DecimalField(max_digits=19, decimal_places=3, default=1.000) Super = models.DecimalField(max_digits=19, decimal_places=3, default=1.000) Diesel = models.DecimalField(max_digits=19, decimal_places=3, default=1.000) Status = models.CharField(max_length=100, choices=STATUS,default='Pending') Special_note = models.TextField() message = models.TextField(blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) total = models.DecimalField(max_digits=19, decimal_places=2, default=1.000) def str(self): return '(Order ID: ' + str(self.id) + ')'+self.Status -
a Django problem: Invalid block tag on line 17: 'static'. Did you forget to register or load this tag?
I am reading ,in 4.2 section I got a bug,but I code exactly as it appears in the book.And I did wrire<% load staticfiles %>. django version 2.1 python version 3.7 this is the file directory index.html this is settings.py this is also settings.py this is console and it shows that there is a bug this is what browser shows -
Django : How do I customize PasswordChageForm?
I'd like to change the label of the PasswordChageForm, but I can't access it. I try : views.py class UpdatePasswordView(PasswordChangeView): model = models.User context_object_name = "user_obj" template_name = "users/user_update_password.html" def get_object(self, queryset=None): return self.request.user def form_valid(self, form): user = form.save(commit=False) user.save() return redirect(reverse("users:profile", kwargs={'pk': user.pk})) forms.py class PasswordChangeForm(forms.ModelForm): class Meta: model = models.User fields = ( "old_password", "new_password1", "new_password2", ) widgets = { "old_password": forms.PasswordInput(attrs={"style": "width:100%"}), "old_password": forms.PasswordInput(attrs={"style": "width:100%"}), "old_password": forms.PasswordInput(attrs={"style": "width:100%"}), } def __init__(self, *args, **kwargs): super(PasswordChangeForm, self).__init__(*args, **kwargs) self.fields['old_password'].label = "닉네임" self.fields['new_password1'].label = "언어" self.fields['new_password2'].label = "화폐" but the error getting message: django.core.exceptions.FieldError: Unknown field(s) (old_password, new_password1, new_password2) specified for User Could anybody kindly help me please? -
Why is my data not valid? (serializer.is_valid() return False)
Serializer class AddressSerializer(serializers.ModelSerializer): Address1 = serializers.CharField(source='address1') Address2 = serializers.CharField(source='address2') City = serializers.CharField(source='city') State = serializers.CharField(source='state') Zip = serializers.CharField(source='zipcode') class Meta: model = Address fields = ('Address1', 'Address2', 'City', 'State', 'Zip') Model class Address(models.Model): address1 = models.CharField(max_length=50) address2 = models.CharField(max_length=50, null=True) city = models.CharField(max_length=50) state = models.CharField(max_length=50) zipcode = models.CharField(max_length=50) So in the shell(manage.py), when I run: address = Address(address1='123 Sesame St', address2=None, city='Jurassic City', state='California', zipcode='90210') address.save() serializer = AddressSerializer(address) content = JSONRenderer().render(serializer.data) stream = io.BytesIO(content) data = JSONParser().parse(stream) serializer = AddressSerializer(data=data) serializer.is_valid() Why does serializer.is_valid() return false? It is possible that when data gets submitted Address2 could be null. Django Rest Framework -
Django include templates in markdown
I have Django templates written in Markdown. I'd like to implement template tag to include rendered markdown. {% include_md 'mytemplate.md' } I wrote template tag to render my template: import markdown from django.template import Library, loader, Context @register.simple_tag(takes_context=True) def include_md(context, template_name): t = loader.get_template(template_name) return t.render(Context({ #... })) but I need to put somewhere in the middle of my function something like: markdown.markdown(template_content) Unfortunately, template loader doesn't return content of template. So what is a best way to achieve rendering? I woudln't like to implement my own opening template methods with open(). -
django-admin.py startproject mysite isn't working, no solutions worked
admin.py startproject mysite` before and it worked fine but now when I try to use it nothing happens I've tried solutions from the other articles on this but none worked. Please help -
{{ blog.pub_date_pretty }} Attribute Error?
Trying to do this code to make time appear with less info but, I'm getting an Error def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') -
Page not found (404) Update Product
I don't know what is wrong with my setup My urls .py from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), path('shop/Create_Product/', views.Create_Product, name='Create_Product'), path('shop/product/Edit_Product/', views.Edit_Product, name='Edit_Product'), ] Forms.py from django import forms from django.contrib.auth.models import User from .models import Product class CreateProduct(forms.ModelForm): class Meta: model = Product fields = ["category", "name", "image", "description", "price", "available", 'slug'] prepopulated_fields = {'slug': ('name',)} class EditProduct(forms.ModelForm): class Meta: model = Product fields = ["category", "name", "image", "description", "price", "available"] prepopulated_fields = {'slug': ('name',)} Models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) Views.py @staff_member_required def Edit_Product(request, id=None): instance = get_object_or_404(Product, id=id) if request.method == "POST": form = EditProduct(request.POST, instance=instance) if form.is_valid(): product = form.save(commit=False) product.save() return redirect('shop/product/detail.html') else: form = EditProduct(instance=instance) return render(request,'shop/product/Edit_Product.html', {'form': form, 'product': instance}) Please can anyone help with this I am a real noob in django and I looked … -
ModuleNotFoundError: No module named 'test_proj.settings'
I am trying to deploy django app on cPanel 78.0.45. See Setup Python App Configuration here. djangoapp is the application root . The structure of djangoapp directory is as follows: __pycache__/ passenger_wsgi.cpython-37.pyc log passenger_wsgi.py public tmp test_proj/ /*the name of django app*/ test_proj/ __init__.py __pycache__ settings.py urls.py wsgi.py manage.py Script of passenger_wsgi.py is: import imp import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'test_proj/test_proj/wsgi.py') application = wsgi.application Script of wsgi.py is: """ WSGI config for test_proj project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_proj.settings') application = get_wsgi_application() Script of manage.py is: #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_proj.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) Now the problem is that when I hit the Application URL it shows this. I checked the log to trace the problem, it throws the following exception: App 36033 output: ModuleNotFoundError App 36033 output: : … -
How to loop django model in javascript loop?
I've encountered a small problem but I believe it should be easy to resolve. I pass django model as the context to my template. Model has id/title etc. I can't itterate it in my template via JS as it throws the reference error. views.py res = [] res.extend([x.movie for x in reserved.reservations.all()]) #// movie is the model context={ "user_info":user_info, "reserved":set(res) template: function reservations(){ const all_reserved = {{reserved|safe}} for(x=0;x<all_reserved.length;x++){ console.log(all_reserved[x].title) } } -
tbody updated by ajax not handling event django
Hi I have a tbody element in a html page which loads inbox messages. columns are pk, sender, and title. my model has these 4 fields. pk, sender, title, content. there are two ajax calls. one fires when i click on a row and that shows the content of the designated message in a text area element next to the table. the other one fires when i click on a sender name so that loads the table with messages from that sender. the problem is when i click on a sender name and the table is filled with their messages, none of ajax methods run anymore when i click on either sender or rows. even though all the attributes of original and s and s are appended exactly. any suggestion? Thanks -
How to make Django view run further after sending back its response?
My interface must give users an option to start a long web-scrapping operation, which could take from some minutes to a couple of hours. As this operation runs, it will persist data to the database. It's coded in this fashion: def my_view(request): batch = BatchTable.objects.create(user=request.user) # Batch model registers who started the operation try: long_running_operation(batch) # How can THIS be made to run after response being sent? except Exception as ex: batch.fail = str(ex) batch.failed = datetime.now() batch.save() return JsonResponse({'success': 'True', 'message': 'Batch started'}) def long_running_operation(batch): list_response = requests.get('https://agiven.web.service/rest/api/objects') object_list = list_response.json() batch.total = len(object_list) batch.save() for object_entry in list_response.json(): object_response = requests.get(f'https://agiven.web.service/rest/api/objects/{object_entry.id}') object_dict = object_response.json() object_dict['batch'] = batch # to link the entry to the batch in which it was read and created ObjectTable.objects.create(**object_dict) # to persist object data in the bd batch.progress += 1 batch.save() batch.finalized = datetime.now() batch.save() my_view() is hit by an AJAX request, but of course this request will hang until long_running_operation() has finished. Is there some way of sending the response first from my_view() and continuing execution by only then calling long_running_operation()? -
MultipleObjectsReturned display when form is submitted
i have a model with FileField, when i submit a form uploading images it submits for the first time. But when i want to upload another image i get this error: get() returned more than one Image -- it returned 2! class Image(models.Model): imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) first_upload_image = models.FileField(upload_to ='pictsagram/',null=True) second_upload_image = models.FileField(upload_to ='pictsagram/',null=True) def home(request): all_images = Image.objects.filter(imageuploader_profile=request.user.id) try: upload_images = Image.objects.get(imageuploader_profile=request.user.id) except Image.DoesNotExist: upload_images = None all_users = Profile.objects.all() next = request.GET.get('next') if next: return redirect(next) context = { 'all_images': all_images, 'all_users': all_users, 'upload_images': upload_images, } return render(request,'home.html', context,) def upload(request): form = PostForm(request.POST,request.FILES) if request.method == "POST": print(request.FILES) if form.is_valid(): post = form.save(commit=False) post.imageuploader_profile = request.user post.save() return redirect('/') else: form = PostForm() return render(request, 'upload.html', {"form": form}) {% if upload_images.first_upload_image %} <img src="{{ upload_images.first_upload_image.url }}" class="img-fluid d-block w-100" alt="orange tree" /> {% endif %} {% if upload_images.second_upload_image %} <img src="{{ upload_images.second_upload_image.url }}" class="img-fluid d-block w-100" alt="orange tree" /> {% endif %} -
How to insert tuples to a table (postgres) in django?
I have a list of tuples, where every tuple element belongs to a particular column, for example: [("mike",19,"graduate"),("niko",22,"software engineer")....] model/table: Name | Age | occupation how do I insert every tuple into a table (I have the required model created already). Just don't know how to insert into the database. Please help and forgive me if I come off as an amateur. I am a beginner. -
Prefetch_related on queryset.get()
Today I have written a DRF view method using prefetch_related: def post(self, request, post_uuid, format=None): post = Post.objects.prefetch_related('postimage_set').get(uuid=post_uuid) postimage_set = post.postimage_set.all() for image in postimage_set: ... return Response('', status.HTTP_200_OK) And I fear that I am using prefetch_related wrongfully with this. Does it make sense to use prefetch_related here or will this fetch all posts as well as all postimages and then filter this set to just one instance? I'm super thankful for any help on this. -
listed the episodes in the detail page
hello in the streaming we see a dropdown list of episodes but in normal case the detail page does not list anything I try to use the blocks to add the list but it does not work if someone can give me an example or a video, or the documentation page thank you -
What is the best solution to add 2 Django plots next to eachother?
So I'm building my first Django dashboard for personal finance. I have created my first graph which shows balance and I would like to add two boxes for total expenses and income which will take into account the datepicker. Should I make it a new app or add it into the same app and my main problem is, I don't really understand how to add new columns because when I add new plots or content then Django just adds them under the current plot. I've read something about subplots but seems complicated. Any advice? plotly.py app = DjangoDash('test', serve_locally=False, suppress_callback_exceptions=True) app.layout = html.Div( children=[ html.Div([ dcc.DatePickerRange( id='date_selector', #month_format='MMM Do, YY', #min_date_allowed=datetime(2014, 1, 6), #max_date_allowed=datetime(2019, 12, 20), #initial_visible_month=datetime(2019, 12, 20), start_date=start_date, end_date=end_date ) ], ), html.Div( children=[ html.Div( dcc.Graph( id='testing123', figure=go.Figure() ), style={'marginRight': 20, 'marginLeft': 20, 'marginTop': 20, 'marginBottom': 0} ), html.Div( id='app_content' ), ], style={'display': 'inline-block', 'width': '100%'} ) ] ) @app.callback( Output('testing123', 'figure'), [Input('date_selector', 'start_date'), Input('date_selector', 'end_date')] ) def update_testing123(start_date, end_date): start_date = datetime.strptime(start_date.split(' ')[0], '%Y-%m-%d').date() end_date = datetime.strptime(end_date.split(' ')[0], '%Y-%m-%d').date() data_sum_inc = globals()['data_sum_inc'].loc[start_date:end_date] data_sum_exp = globals()['data_sum_exp'].loc[start_date:end_date] data_balance = globals()['data_balance'].loc[start_date:end_date] income_graph = go.Scatter( x=data_sum_inc.index, y=data_sum_inc['income'], text=data_sum_inc.index, mode='lines', line={'color': 'rgba(52, 178, 51, 0.5)'}, name='Income', ) expense_graph = go.Scatter( x=data_sum_exp.index, y=data_sum_exp['expense'], …