Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django looking for wrong path for template file
My django project works in localhost perfectly. And i was trying to deploy it on Ubuntu-Apache. I did git clone And i got this error TemplateDoesNotExist at / Erorr here -> http://devpp.me/ Hum ? and i pay attention to this error message django.template.loaders.filesystem.Loader: /templates/base_layout.html (Source does not exist) This Error came from {% extends 'base_layout.html'%} (/home/ubuntu/django/blog/djangonautic/articles/templates/articles/article_list.html) I hoped Django to search templates in the parent folder ({root}/templates). The right path of it is /home/ubuntu/django/blog/djangonautic/templates/base_layout.html (File is there i checked) Why my Django dosen't looking for it in (root) templates ? in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates', 'front/build'], ... I Guess it is because. Virtualenv I created this in Ubuntu (didn't created in local) Apache configure I was following https://medium.com/saarthi-ai/ec2apachedjango-838e3f6014ab this post. something wrong in settings.py But i don't think this is wrong cause in local it works well... Tell me anything you need to debugging i will answer quickly -
Select form doest show option preview
I found out that the css that I placed makes the preview to the option in the select forms disappear. I can't seem to find a solution online on how to fix this. This is the css part that causes the said issue: .form-control{ height: 50px; padding: 20px; border-radius: 0 10px 0 10px; } As you can see below, when I remove this, the preview to the select option goes back. With the css .form-control: Without the css .form-control: Here is "without the css" when I select an option: I'm using django so this is how to placed the form in my html template: {{ form | crispy }} Any help is greatly appreciated! -
Django-allauth facebook login failure "Social Network Login Failure"
I'm using django-allauth for integrating facebook login into my website. My website is https://thelittlechamp.com/ In the nav bar there is facebook login button you can try once. While trying to login it says "Social Network Login Failure". I dont know why i am seeing this error. Someone please give mesuggestions where i might have done wrong. I have the settings as below: Site registered in django admin. In facebook setting: -
Coding Test(Python) .....Must required. But we can write also in Java
CODING TEST The module to be developed is a pricing engine for a cycle. A cycle can be thought of as high level components - frame handle bar with brakes seating, wheels, chain assembly Each of the above high level components will have parts, for instance, a wheel has spokes, rim, tube, tyre. The pricing module should be able to calculate the price of the cycle given its configuration. For example, price a cycle with tubeless tyres, steel frame, 4 gears. The pricing of the parts is time sensitive, means the cost of a tyre will change with time and the module should support this. A tyre can cost 200Rs from Jan 2016 - Nov 2016, and its price can change to Rs 230 from Dec 2016 onwards. The pricing module should be a command line executable, no graphical ui needed. It can take its input as command line parameters or as a json text file, whatever is convenient to specify in. The inputs to the module will be the list of constituent parts, date of pricing and it will output the price of the entire cycle and also price for each high level component - frame, wheels etc. Modular … -
Make it so either 2 fields are Null or neither of them are in django?
I am making a model for my django app where I want to store some measurements, these measurements will have a reading that must not be Null, and a GPS position stored as Latitude and Longitude. I want to accept measurements where there hasn't been a GPS fix yet, so Latitude and Longitude should be null. And in theory, the sensor will never send a Latitude without a longitude or vice versa. Still, there is nothing in the django app that actually forbids that from happening, is it possible? -
Heroku: how can I access or display data sent in a POST request?
I have a Django app on Heroku that receives POST request data from Javascript and Python API calls. For debugging, how can I display the exact message content characters that were received by Django side? -
Making a Django web app work with gunicorn
I am interesting in putting nginx and gunicorn in front ob of a Django web app (https://github.com/fiduswriter/fiduswriter). This web runs fine with the usual python manage.py runserver command, but for gunicorn I would need to have the wsgi.py file, which I cannot find anywhere. Therefore, I ask myself whether there is any way to bypass that issue for using gunicorn here. -
Model with a one to one field does not save after save(commit=False)
I have the code blow but other fields of patient_specification will not be saved. The code does not show any error and runs normally. When i read the patient_specification data from db they are not changed and all except patient field are the default values. # models.py class Patient(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) national_code = models.BigIntegerField(default=1, unique=True) class PatientSpecification(models.Model): patient = models.OneToOneField(Patient, on_delete=models.CASCADE, unique=True) weight = models.IntegerField(default=1) height = models.IntegerField(default=1) age = models.IntegerField(default=1) # forms.py class PatientForm(forms.ModelForm): class Meta: model = Patient fields = '__all__' class PatientSpecificationForm(forms.ModelForm): class Meta: model = PatientSpecification exclude = ('patient', ) # views.py def newPatient(request): if request.method == 'POST': form_p = PatientForm(request.POST) form_ps = PatientSpecificationForm(request.POST) if all([form_p.is_valid(), form_ps.is_valid()]): patient = form_p.save() patient_specification = form_ps.save(commit=False) patient_specification.patient = patient patient_specification.save() return render(request, 'sfl/home.html', {}) else: print('not valid') else: form_p = PatientForm() form_ps = PatientSpecificationForm() return render(request, 'sfl/new_patient.html', {'form_p': form_p, 'form_ps': form_ps}) I also tried to replace save(commit=false) with PatientSpecification() or patient_specification.patient = patient with patient_specification.patient = Patient.objects.get(national_code=patient.national_code) but no success, patiet_spacification does not save normal fields. I also tried with django shell but same problem exist. Where is the problem? Thanks -
User in not extending to other models in django
I have created user model using AbstractBaseUser and BaseUserManager. The user model is connected with OneToOneField other three models(Employee, WorkExperience, Eduction). If I create a superuser, the user is extending to all three models. But if I create staffuser or admin user, the user is only extending to Employee model not to other three models. models.py: class UserProfileManager(BaseUserManager): """ Creates and saves a User with the given email and password. """ def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email,username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser): """ Creates a customized database table for user """ email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] objects = UserProfileManager() def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their … -
Files not installing for Django/Python web app
I'm trying to open a web app locally on my laptop and the files aren't installing. I tried these two methods of installing the files: $ pip3 install -r requirements.txt $ pipenv install -r ./requirements.txt But in both ways, I get the following error: An error occurred while installing scipy==1.1.0 ... ERROR: Couldn't install package: psycopg2 ... Package installation failed... So I then manually installed the files on the command line. But, when I do $python3 manage.py runserver then I get this error: ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x7fbb65b6b790> Traceback (most recent call last): File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/core/management/base.py", line 361, in check all_issues = self._run_checks( File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/dhanush/.local/share/virtualenvs/sisu-test-release-uLyEUBTr/lib/python3.8/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) ... ImportError: numpy.core.multiarray failed to import I've spent all day trying to get this web app running. Thanks for your help! -
sending value(a string) from html input to python script (views.py) with Django
I have a sentence that was made in java in html (var Output). I want to send this var to views.py to analyse. I saw several similar posts in "stackoverflow" and follow the instructions. still I do not get the response. here is part of my code: Hope you could help me please; ODMS2FixEnd.html <div> .... <form id="Sertegh" name="OUTPUT" method= 'get' action="{% url 'Calculator' %}"> {% csrf_token %} <input id="outputtext1" name="outputtext1"> </form> ... </div> <script> function.... document.getElementById("outputtext1").value = OutPut; ... </script> urls.py ... url(r'^myprojects/ODMS2FixEnd', blog_views.ODMS2FixEnd, name= 'Calculator'), ... views.py: def ODMS2FixEnd(request): if 'outputtext1' in request.GET: StringInput0 = request.POST.get('outputtext1') print(StringInput0) #just to check print("OK") #just to check return render(request, 'ODMS2FixEnd.html', {'StringInput0'}) else: print("NOOOOOOO") #just to check return render(request, 'ODMS2FixEnd.html') -
Django Allauth facebook login error " App isn't using a secure connection to transfer information"
I am trying to integrate facebook login to my website https://thelittlechamp.com. You can try by clicking the facebook login button in the nav bar. While trying to log in it says "Facebook has detected thelittlechamp isn't using a secure connection to transfer information". I am using django-allauth library. I couldnt figure out the main reason behind the error. If someone know please help me. -
Django React Image wont display
So I recently was trying to deploy my website and I was able to get everything working. However, the images are broken for some reason. I can actually add images to the database fine (easily able to add and change the image itself). However, when I click on the link I go nowhere instead of seeing the image and just see the part of my site that pops up whenever the URL entered isn't part of the API (no error, instead nothing basically shows up). The strange part is that the uploaded images actually get added to my images folder in my project but it seems like Django can't find them afterwards (you can see the image is in the database in my images folder). Here is some of my code: SETTINGS.PY STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR,'build/static'), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' REST_FRAMEWORK = { 'DEFAULT_AUTHETICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ] } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'EZtrade') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] URLS.PY urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('admin/', admin.site.urls), path('api/', include('articles.api.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), re_path('.*',TemplateView.as_view(template_name='index.html')), url(r'^media/(?P<path>.*)$', serve, {'document_root': … -
How to delete django background task programmatically?
I have some background task which will be called when I run some function from view and the background task gets registered in the admin/database. Which works fine but what I want is if I delete the task then the background task related with this task withpk should also get deleted. How can I do it ? tasks.py @background(schedule=20) def my_task(pk): task = Task.objects.get(pk=pk) # my tasks views.py def some_process(): pk = obj.pk my_task(pk, repeat=3600, repeat_until='some_datetime',verbose_name="{}".format(obj.name)) def delete_task(): obj = MyModel.objects.get(pk=obj.pk) obj.delete() # while this object gets deleted I want to delete the background task related to this object background_task_of_this_obj= BackgroundTask.objects.get(pk=obj.pk).delete() -
how to send signals to remove multiple objects depend on a m2m field django | (1452, 'Cannot add or update a child row: a foreign key constraint fails
i want to remove multiple objects while a M2M field filled for example : class ModelA(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) product = models.CharField(max_length=30,unique=True) def __str__(self): return self.product class ModelB(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) unnecessary = models.ManyToMany(ModelA) i need to whenever ModelB filled then remove the selected product name , i tried this ; def m2m_product_remove(sender,*args,**kwargs): ModelA.objects.filter(pk__in=kwargs.get('pk_set')).delete() m2m_changed.connect(m2m_product_remove,sender=ModelB.unnecessary.through) but it raise this error : (1452, 'Cannot add or update a child row: a foreign key constraint fails -
Django ckeditor upload image link expires after some hours
I am using Django-storages for storing static content in the cloud and CKEditor for a text editor and used a RichTextUploadingField field. The problem is when I upload an image via CKEditor, the image link expires after some hours. The below image for reference. And the field in the application. bio = RichTextUploadingField(blank=True, null=True) If I upload an image via ImageField, the link never expires its works fine. the problem occurs only in the CKEditor image uploader. Any idea why the link expires? -
Querying related model with parent model id
I have two models: class UserPost(models.Model, Activity): user = models.ForeignKey("auth.User", on_delete=models.CASCADE, related_name='userpost', null=True) title = models.CharField(max_length=300) url = models.URLField(null=True) The second model would be: class UserPostComment(models.Model, Activity): post = models.ForeignKey(UserPost, on_delete=models.CASCADE, related_name='userpostcomment') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='userpost_comment_user') comment = models.CharField(max_length=1000, blank=True, null=True) TO get the UserPostComment model using the foreignkey post. I did: UserPostComment.objects.get(post_id=post_id) This query only works when I have one UserPostComment entry. When there are more than one comment, It fails. I would get: MultipleObjectsReturned at /comment/268/ get() returned more than one UserPostComment -- it returned 2! Any idea how to fix this? -
Django TypeError : __init__() takes 1 positional argument but 2 were given
here is a class code from views.py class Ask(CreateView): template_name = 'f/ask.html' form_class = QuestionForm success_url = '/f/ask/' def get_context_data(self, **kwargs): content = super().get_context_data(**kwargs) return content it says init() takes 1 positional argument but 2 were given, but that code I took from book, so I dont it is wrong or something/ -
how to search account in django_python3_ldap in django
Currently I'm using the django_python3_ldap to authenticate in our network. now i want to add delegate function in my project. The approver have ability to delegate the action to the other user. So I like to add function where user will search the network account list using the sAMAccountName. then select the user in the search result. I find this code in this link and i dont know to use the code provided and how can i search using the sAMAcountname. Link Code : def custom_format_search_filters(ldap_fields): # Add in simple filters. ldap_fields["memberOf"] = "foo" # Call the base format callable. search_filters = format_search_filters(ldap_fields) # All done! return search_filters My Code : from django.shortcuts import render, redirect from django_python3_ldap import ldap from django_python3_ldap.utils import format_search_filters def LDAPSearch(request): if request.method == 'GET': return render(request, 'component/search.html') else: keyword = request.POST.get('keyword') # Add in simple filters. ldap_fields["memberOf"] = keyword # Call the base format callable. search_filters = format_search_filters(ldap_fields) print(search_filters) context = { "keyword" : keyword, "searchresult" : search_filters } return render(request, 'component/search.html', context) -
Why am i getting "the image attribute has no file associated with it" when i try to upload video or image?
I am trying to upload images and videos depending on what i choose to upload but i keep getting this error that the image attribute has no file associated with it. My models.py file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length = 120) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField( upload_to = "profile_pics", blank =True,null =True) likes = models.ManyToManyField(User, related_name='likes', blank=True) video = models.FileField(upload_to='profile_vids', blank=True, null=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse('blog:post-detail', kwargs={'pk' : self.pk}) My views.py file: from django.shortcuts import render, get_object_or_404,redirect from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView, ) from .models import Post, Comment from .forms import CommentModelForm from django.urls import reverse_lazy def home(request): context = { 'posts': Post.objects.all() } return render(request,"blog/home.html",context) class PostListView(LoginRequiredMixin, ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(LoginRequiredMixin, ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' #ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.objects.filter(author = … -
call class variable python django
I'am new to OOP in python and trying to use a class variable within the django framework. I need to call the class variable required and input it in the Charfield method like tihs: class customerForm(forms.Form): def __init__(self, required=True): self.required = required name = forms.CharField(label='Name', max_length=20) first_name = forms.CharField(label='First Name', max_length=50, required=) last_name = forms.CharField(label='Last Name', max_length=50, required=) company_name = forms.CharField(label='Company Name', max_length=50, required=) address = forms.CharField(label='Address', max_length=100, required=) city = forms.CharField(label='City', max_length=50, required=) How can I do this? -
Django: Adding and Saving new Data in Account Update for User Profile
I am trying to add new information such as Facebook account related to a user. I have not added it in the registration form as it is not mandatory and no need to be there but if user wanted to add it, it can be found in account update as an option empty fields to be filled. My issue is, I have added the facebook account to be in the account update profile but after I submit the update button, the page is refreshed and the data is not saved and it is not available in DB. Here is the models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) Here is the views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') … -
Trying to add an attribute to a Django crispy form input field
I'm attempting to add an attribute to a django crispy form using Django-Widget-Tweaks. I followed instructions, however, instead of adding the 'disabled' attribute to the existing field, it's adding a whole new field to the form with the same name, id, class, etc and includes my'disabled' attribute (lol). Here's my widget tweak code... {% crispy registration_form %} {{ registration_form.net_profit|attr:"disabled" }} Thisis a link to the inspected html code that is generated. Sorry, I couldn't figure out how to copy the code. Any help is appreciated! -
Why is ajax not working to prevent page refresh?
I have been a like system on my django project in which a user can like and unlike posts, a system very similar to intagram. I tried to add ajax to my code so that when the like/unlike button is pressed the page is not reloaded, but when this code was runned, the buttons where doing no job, I think this error is on the href of the html or in the ajax url. views.py def home(request): contents = Post.objects.all() args = { 'contents': contents, } return render(request, 'home.html', args) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(author=user, post_id=post_id) if not created: if like.value == 'Like': like.value == 'Unlike' else: like.value = 'Like' like.save() return redirect('home') urls.py urlpatterns = [ path('', views.home, name='home'), path('like/', views.like_post, name='like-post'), ] home.html <form action="{% url 'like-post' %}" method="POST"> {% csrf_token %} <input type='hidden' name="post_id" value="{{ content.id }}"> {% if user not in content.liked.all %} <a class="btn like" href="javascript:" data-content="{{content.pk}}">Like</a> {% else %} <a class="btn unlike" href="javascript:" data-content="{{content.pk}}">Unlike</a> {% endif %} </form> <script type='text/javascript'> $(document).ready(function(){ $(".like").click(function() { var contentpk = $(this).data('content.pk'); $.ajax({ url: "{% url 'like-post' %}", … -
Django template not showing form instance value
I am new to django and building an user (named "Developer") settings update page. I used model form and passed the settings instance via views.py hoping them to show up in the rendered template for users (named "Developer") to edit. But the instance value is not populated into the template in form.as_p. I have tested the {{project_form.instance.pk}} is passing the correct project instance, so I am expecting the project name to show up as default value in the form for user input project name, but it is showing blank. models.py (simplified) class Project(models.Model): project_name = models.TextField(unique=True) class Developer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE, default=Project.get_default_project) institution = models.ForeignKey(Institution, on_delete=models.CASCADE, null=True, blank=True) forms.py class ProjectForm(ModelForm): class Meta: model = Project fields = ['project_name'] class DeveloperForm(ModelForm): class Meta: model = Developer fields = ['user','project','institution'] views.py def developerSettingsUpdate(request): from .forms import ProjectForm, DeveloperForm developer = request.user.developer project = developer.project if request.method == 'POST': project_form = ProjectForm(request.POST, instance=project) developer_form = DeveloperForm(request.POST, instance=developer) if project_form.is_valid(): project_form.save() if developer_form.is_valid(): developer_form.save() else: project_form = ProjectForm(instance=project) developer_form = DeveloperForm(instance=developer) return render(request, 'decg/developer_settings.html', { 'developer_instance': developer, 'project_instance': project, 'project_form': project_form, 'developer_form': developer_form, }) developer_settings.html <div> {{ developer_instance }} {{ project_instance }} {{ developer_form.instance.pk }} {{ project_form.instance.pk }} …