Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Control if a field is unique in a django form
First error :I want to check if group_name field value is unique in a modelforms I tried this code but seems not working as if i put a new value in this field, there is no message but data as not been add to table Second error: i nether have any message. Maybe, I should not redirect pages ? my code in views.py: def group_create(request): group_form = GroupForm() if request.method == "POST": group_form = GroupForm(request.POST) if group_form.is_valid(): group_name = group_form.cleaned_data.get('group_name') if Group.objects.filter(group_name=group_name).exists: messages.error(request, 'this group already exists') else: group_form.save() messages.success(request, 'Group created') return redirect('group_list') return render(request, 'imports/group_create.html', { "group_form": group_form, }) my model: class Group(models.Model): group_id = models.AutoField(primary_key=True) groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='Parent', on_delete=models.CASCADE) group_name = models.CharField(max_length=100, null=False, blank=False, unique=True) my html: <div class="container-fluid"> <!-- Code pour message type toaster --> {% if messages %} <div class="row"> <div class="col-xs-12"> <ul class="alert" role="alert"> {% for message in messages %} <p {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</p> {% endfor %} </ul> </div> </div> {% endif %} <!-- fin messages --> <div class="row"> <div class="col-lg-2 col-md-2 col-sm-2 sidebar"> {% block sidebar %}{% endblock %} </div> <div class="col-lg-10 col-lg-offset-2 col-md-10 col-md-offset-2 col-sm-10 col-sm-offset-2 content"> {% block heading %}{% … -
In django oscar, How to store image on s3 bucket
I am a newbie in Django oscar but I have good experience with Django and Django rest. So I am exploring Django Oscar for my current project In which we are using all built-in models and all functionalities of it. And When we create a category or product, we also give an image which may be stored in its media file and it may store that link in its DB. I just want to change image storage location and I want to store all images on my s3 bucket and store bucket url in DB. So that I can get an image or load image from my bucket URL. But I am seriously stuck in this thing and search a lot of things but could not get any effective solution. If anyone has any idea then please help me with an example. your help will be appreciated for sure. Thank You. -
How to Default Value in a Form from another Form in Django
I have two forms, one CreateOrderForm and one CreateManifestForm. Submitting CreateOrderForm renders CreateManifestForm. There is an input in CreateOrderForm 'reference' which is user entered but then should default into the 'reference field of CreateManifestForm. I seem to be unable to figure out how to pass that value from form to form FORMS.PY class CreateOrderForm(forms.ModelForm): class Meta: model = Orders fields = ('reference', 'ultimate_consignee', 'ship_to', 'vessel', 'booking_no', 'POL',....) class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') VIEWS.PY def add_order(request): if request.method == "POST": form = CreateOrderForm(request.POST) if form.is_valid(): form.save() return redirect('add_manifest') else: form = CreateOrderForm() return render(request, 'add_order.html', {'form': form}) def add_manifest(request): if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): form.save() return redirect('add_manifest') form = CreateManifestForm() manifests = Manifests.objects.all() context = { 'form': form, 'manifests': manifests, } return render(request, 'add_manifest.html', context) As you can see there is a field in each form for 'reference' I would like to user enter it in CreateOrderForm and pass that value to default when creating the manifest. Any help is greatly appreciated and thank you in advance. -
How can I get percentage?
I try to get percentage, but I don't know how to do this for my models. I tried to use some code, but I get error. How can I get percentage for my models? models.py class Choice(models.Model): question = models.ForeignKey('Question', models.CASCADE) message = models.CharField(max_length=1024) ballots = models.IntegerField(null=True, blank =True) views.py def ReportList(request, id): q = Question.objects.select_related().get(id = id) queryset = Choice.objects.filter(question_id=id) if not queryset: return redirect ('error') return render(request, 'polls/report.html', {'queryset': queryset, 'q': q}) html {% for choice in queryset %} <tr> <td>{{ choice.message }}</td> <td>{{ choice.ballots }}</td> </tr> {% endfor %} I tried to use this code in models.py, but I think this is wrond way: def get_percentage(self): total_count = Choice.objects.annotate(sum('ballots')) cnt = Choice.ballots.__float__() perc = cnt * 100 / total_count return perc -
Getting random 500 error with Apache2 + mod_wsgi + django 'Remote end closed connection without response'
I have my django working correctly under apache2, but sometimes I get this message: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) Reloading solves the problem, but this is not a solution for a production server. I tried Updating Django and mod_wsgi This is the traceback I get https://drive.google.com/file/d/1zdSG8KB79POkaJ6Eu3N8Oh1y6CNEfFSk/view?usp=sharing Somebody with the same issue? -
How to get the id using a get_context_data?
I would like to get the total amount of followers attached to the models using in models : class Project(models.Model): owner = models.ForeignKey(User, related_name='project_created_by', on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField(max_length=150, blank=True, null=True) followers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True) created = models.DateTimeField(auto_now_add=True) last_modefied = models.DateTimeField(auto_now=True) def __str__(self): return self.name Here is the class class ProjectListView(ListView): template_name = 'projectmanagement/project.html' context_object_name = 'projects' def get_queryset(self): queryset = Project.objects.filter(owner=self.request.user).order_by("name") return queryset def get_context_data(self, *args, **kwargs): context = super(ProjectListView, self).get_context_data(*args, **kwargs) project = Project.objects.get(pk=12) context['followers'] = project.followers.filter(followers=project).count() return context -
How to avoid escape for Django tags in HTML
I'm reading an entire page's content from database and render them in a HTML file. Here are some examples. In database: In order to avoid escape of HTML tags, I use {{ page.content|safe }} But I couldn't render {% url 'home_view' %} -
Is there a dynamicly allocated Rest API?
I am looking for a dynamicly allocated rest framework, by which I mean I can allocate Rest API calls, models, relations, etc while the system is running, without having to write additional backend code. Best case would be where I can just create models, set permissions for users to read and write entries and edit the models directly int the website, similarly to the django admin interface, just with the additional feature of creating new models and api calls. Or just a system that lets me change a config files to create new models that is reloaded on the fly, so I can create a tool for that. Is there such a system, in the best case available for django? -
Passing and accessing value in Django form
I'm trying to pass info to my form and I have a bit of a struggle with that. My code looks as follows: views.py class ObjectUpdateView(UpdateView): template_name = 'manage/object_form.html' form_class = ObjectEditForm def get_success_url(self): #... def form_valid(self, form): return super(ObjectUpdateView, self).form_valid(form) def get_object(self): return get_object_or_404(Room, pk=self.kwargs['object_id']) def get_form_kwargs(self, **kwargs): objectid = self.kwargs['object_id'] object = Object.objects.get(id = objectid) container = object.container kwargs['container_id'] = container.id return kwargs forms.py class ObjectEditForm(forms.ModelForm): class Meta: model = Object fields = ['TestField'] def __init__(self, *args, **kwargs): super(ObjectEditForm, self).__init__(*args, **kwargs) self.Container_id = kwargs.pop('container_id') form_page.html {{fomr.kwarg.Container_id}} As you can see I'd like to access Container_id value in my form_page.html. Unfortunately, nothing is there. What I also noticed, that with __init__ I had to add, now values are empty in my form. Before I added __init__ all values were properly passed (well, except Container_id). Could you recommend how I can pass such value to be accessed in the form template? -
Draw/Visualize Bio-signals in Python
Anyone know of any good JavaScript or other framework I can use to draw and visualize bio-signals like ECG, ABP, SpO2, etc.? I am using Django so my preference is for Python packages but what's more important is for me to have a framework that support a comprehensive list of bio-signals. I've looked at BioSPPy but it only supports a handful of bio-signals. Any help would be appreciated. Thanks. -
error when installing from pipfile.lock in docker
I am trying to use docker in the project. It was working fine unless i used django channels and Pillow. Below was my working configuration Dockerfile FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 # set working directory which will be inside ubuntu WORKDIR /code #### Install a dependency #### # install psycopg2 RUN echo "https://mirror.csclub.uwaterloo.ca/alpine/v3.9/main" > /etc/apk/repositories RUN echo "https://mirror.csclub.uwaterloo.ca/alpine/v3.9/community" >>/etc/apk/repositories RUN apk update RUN apk add --update --no-cache postgresql-client jpeg-dev RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev \ && pip3 install psycopg2-binary \ && apk del .tmp-build-deps RUN pip3 install --upgrade pip RUN pip3 install pipenv COPY Pipfile* /code/ RUN pipenv install --system --deploy --ignore-pipfile COPY ./entrypoint.sh /code/entrypoint.sh COPY . /code/ ENTRYPOINT ["/code/entrypoint.sh"] my pipfile is [packages] django = "*" "psycopg2-binary" = "*" djangorestframework = "*" djangorestframework-jwt = "*" djoser = "*" graphene-django = "*" django-cors-headers = "*" django-graphql-social-auth = "*" django-money = "*" django-mptt = "*" pillow = "*" channels = "*" channels-redis = "*" the error i get is something like this if i remove the pillow, channels and channels-redis from pipfile, it works. How do i solve this issue? -
what is BaseUser and BaseUserAdmin in django
what is BaseUser in django . why is it used? What role does it play during the creation of custom user model and why attributes it present ? -
Troubles using aws s3 with Europe based buckets in django-storages
Question is regarding AWS S3 buckets in EU. I have a Django project hosted locally and decided to store media files in AWS s3 buckets. For doing this I use Django-storages app with the following settings in settings.py: AWS_ACCESS_KEY_ID = "xxxxxxx" AWS_SECRET_ACCESS_KEY = "xxxxxxxxxx" AWS_STORAGE_BUCKET_NAME = 'hadcasetest' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' MEDIA_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' THUMBNAIL_DEFAULT_STORAGE = DEFAULT_FILE_STORAGE THUMBNAIL_BASEDIR = "thumbnails" THUMBNAIL_MEDIA_URL = MEDIA_URL Well, it works when I use bucket from USA region and doesn't when I use buckets from Europe. I tried all possible locations in Europe – they all dont work. Type of error I get - S3ResponseError: 400 Bad Request Type of account I have on AWS- free account Question is what should I change to get access via Django -storages to Europe based buckets to use them in Django app? p.s. I can use AWS CLI to write in each buckets even in European ones but, Django-storages can not. Should I obtain specific EU credentials perhaps? Thank you! -
Django Grappelli auto lookup width
I have not been able to resize the autocomplete input width in Django Grappelli. The autocompelete search stops working if I put the field in the form and the width remains same. Inspection shows the width as 758px. Tried to change the widget attr as follows field_name = forms.CharField( widget=forms.TextInput(attrs={'style':"width:200px"}) ) field_name = forms.CharField( widget=forms.URLInput(attrs={'style':"width:200px"}) ) field_name = forms.URLField( widget=forms.URLInput(attrs={'style':"width:200px"}) ) Tried other widgets too. But all have the same effect. Is there any way to reduce the width on it. Thanks In Advance. -
How to agregate integerfield in django template if the model have a same field's value?
I have this model : class LoggedUserDepartement(models.Model): department = models.CharField(max_length=250, default='Care') date = models.DateField() login_count = models.PositiveIntegerField(default=0) I have this queryset in my views.py : department_count = LoggedUserDepartement.objects.all() and in my template i have done this : {% for item in department_count %} {{item.date }} {{item.login_count}} {{item.department}}<br> {% endfor %} This is the result that i get : June 8, 2019 3 css June 8, 2019 1 carefr June 9, 2019 2 css June 9, 2019 1 carefr So what i cannot do here is when i have the same value on the department field how can i merge the 2 items and aggregate the login count value and don't show the value of the date's field ? Instead of the result that i have now i want to get this one bellow : {% for item in department_count %} {{item.login_count}} {{item.department}}<br> {% endfor %} 5 css 3 carefr PS: The date field isn't required in this queryset but i will use it on another querysets in future so i cannot delete it. Any help will be appreciated. -
python: can't open file 'manage.py': [Errno 2] No such file or directory
i have created a project "post_blog" in which i have created an app "blogs" C:Users/arpchauh/PycharmProjects/post_blog/blogs>python manage.py runserver python: can't open file 'manage.py': [Errno 2] No such file or directory python: can't open file 'manage.py': [Errno 2] No such file or directory -
Multiple instance in one Django form for editing profile model objects
I used the profile method to be able to customize the user model. I also use this site to create a registration form in which both the user and the profile can be created at the same time. Now I want to write edite_user view. In this question I also find out that must use modelformset_factory to create edit_viewfor this goal. This is my files: #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500) degree = models.CharField() #forms class SignUpAdminForm(UserCreationForm): bio = forms.CharField(widget=forms.Textarea) degree = forms.CharField() #Also_their_is_another_fields_here class Meta: model = User fields = ( 'username', 'email', 'password1', 'password2', 'bio', 'degree', ) #Views.py def add_user(request): if request.method == 'POST': form = SignUpAdminForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.bio = form.cleaned_data['bio'] user.profile.bio = form.cleaned_data['degree'] user.save() return redirect('view_user') else: form = SignUpAdminForm() template = 'add_user.html' context = {'form': form} return render(request, template, context) def edit_user(request, id): user = get_object_or_404(User, id=id) if request.method == "POST": UserFormSet = modelformset_factory(user, form=SignUpAdminForm) if UserFormSet.is_valid(): edit_user = UserFormSet.save(commit=False) edit_user.save() return redirect('view_user') else: UserFormSet = modelformset_factory(User, form=SignUpAdminForm) template = 'edit_user.html' context = {'UserFormSet': UserFormSet} return render(request, template, context) But this view did not work.I Also see these links: 1,2,3 and 4; but they couldn't help me … -
Displaying users profile pic in blog
I am new to Django and programming basically here i am making this simple app everything is working alright when i save profile pic from registered user account from a admin page when i try to display the profile pic next to username of that user it is showing blank but username and email is displayed,I don't know where i did wrong,Any help would be appreciated.... models.py from django.db import models from django.contrib.auth.models import User 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' settings.py STATIC_URL = '/static/' #Media root will be full directory where we want django to store uploaded files MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' #crispy to use bootstrap4 CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'blog-home' LOGIN_URL = 'login' profile.html inside my templates {% extends "blog/base.html"%} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> </div> {% endblock content%} urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', … -
How to export filtered models into an excel file?
I have filtered models using QuerySet and displayed them on a page.I want to download an excel file which contains the above models on click of download button.(Sorry I am a beginner and Thanks) I am trying to create an excel file as soon as a user clicks search, and save it to the database and download it when user clicks download via an ID. I also tried to send QuerySet as the parameter but I don't know the regex to give to the URL. Views.py: class SearchView(View): template_name = 'auto_project/search_form.html' form_class=ExcelFile qs='' def get(self,request): qs = report.objects.all() date1 = self.request.GET.get('date1','') date2 = self.request.GET.get('date2','') #Filter Stuff return render(self.request,self.template_name,{'qs':qs}) def post(self,request): form=self.form_class(request.POST) if form.is_valid(): f = form.save(commit=False) response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Report.xlsx' xlsx_data = WriteToExcel(self.qs)#Funtion response.write(xlsx_data) f.file = response f.save() return render(self.request,self.template_name,{'f':f}) def report_download(request,file_id): response = Excel.objects.get(id=file_id) return response #forms.py: class ExcelFile(forms.ModelForm): class Meta: model = Excel fields = ['id','file'] #urls.py: urlpatterns = [ url(r'^search/$',views.SearchView.as_view(),name='search'), url(r'^download/(?P<file_id>[0-9]+)/$',views.report_download,name='dload'),] #search_from.html: <form action='.' method='GET'> <!-- some input fields and a submit button--> </form> <button type="submit"><a href="{% url 'auto_project:dload' f.id %}">Download</a></button> -
__call__() got an unexpected keyword argument 'pk' at decorator
i first created this as middleware (works as expected) but now im using it as decorator and as soon as im processing a pk within my views.py and i set this decorator i get the following error call() got an unexpected keyword argument 'pk' i guess this is coming fromt the following line(s): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) #filters if not hasattr(response, 'content'): return response if request.method == "POST": return response else: return self.process_response(request, response) this isn't the full decorator, the full code is currently closed, anyways i hope you guys can give me a hint. Do i have to pass the pk here and if so why and where? kind regards -
Set model field default to value from foreign key instance
Working on a Django app with two models (A and B), B has a field link which is a foreign key relationship to A: # models.py class A(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=15) my_bool = models.BooleanField(default=True) class B(models.Model): link = models.ForeignKey(A) b_bool = models.BooleanField(default=link.my_bool) # Error! I would like for the b_bool field to have the linked my_bool value as a default if no B.b_bool is provided via graphene mutation. Currently, using link.my_bool as a default raises the following error when making migrations: AttributeError: 'ForeignKey' object has no attribute 'my_bool' -
Need to search user based on email and then deactivate his profile
I am trying to create a search form, Where admin can search users and then deactivate their profiles, if it is the right account. tried function based views and then class based views. It shows the profile in function based views but doesn't update it. and in class based view it wouldn't even show the profile. models.py class User(AbstractBaseUser): objects = UserManager() email = models.EmailField(verbose_name='email address', max_length=255, unique=True,) type = models.CharField(max_length = 50, choices = type_choices) name = models.CharField(max_length = 100) department = models.CharField(max_length = 100, null = True, blank = True, choices = department_choices) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a superuser admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['type'] forms.py class SearchForm(forms.Form): email = forms.EmailField(required=True) views.py @method_decorator(login_required, name='dispatch') class adminDeleteProfileView(LoginRequiredMixin, View): def render(self, request): return render(request, 'admin/view_account.html', {'form': self.form}) def form_valid(self, form): self.form = SearchForm(request.POST) print('im here', form.cleaned_data.get('email')) User.objects.filter(email = form.cleaned_data.get('email')).update(active = False) #print('Donot come here') def get(self, request): self.form = SearchForm() return self.render(request) @login_required def admin_deactivate_profile_view(request): error_text = '' if request.method == 'POST': print('here') user_email = request.POST.get('email') try: print('Deactivating',user_email, 'Account.') profile = User.objects.filter(email = user_email).first() if request.POST.get('delete'): User.objects.filter(email = user_email).update(active = False) messages.success(self.request, 'Profile Updated!') except Exception as e: print(e) messages.success(self.request, 'There was an error!') … -
How to cache with redis being on different server
Hi i have an appserver which holds the django app, and another server for caching. I am thinking to use Redis for caching.. How do I pass the IP of the redis server to my django app? -
How do I filter a list of article by category on Django template
I have a list of articles (that has a Many-to-many relationship with categories). I also have list_articles = Articles.objects.filter(author_id = author_id) Now, on template I show list_articles. My question is: How do I quick filter that list_articles by click on one category on a sidebar? Which is possible: javascript or python? -
What is the purpose of the postgresql database when using Heroku with Django?
I'm starting a new project using Django and hosting it on Heroku. I know that Django comes with a SQLite db ready to use for the application to store all of the app's data. Heroku requires PostgreSQL - does this mean that my app will have to be configured locally to use this database INSTEAD OF the SQLite db - or does it use both? Is the PostgreSQL db just something that the Heroku app needs to work or do you actually need this to run your Django app in Heroku? Thanks!