Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After upgrade to Django 1.11 site doesn't work in Chrome
I face strange problem. When running django development server I cant display pages in Chrome but I can in FireFox and MsEdge. The server returns 200 response, so page should be displayed. I did not touch any options related to security. Chrome stucks on spinning wheel, and no other information is available, no timeout, no errors. Django 1.11.7 here. Do not hasitate to comment as it could lead us to an answer. -
Is there 'imagecreatefromjpeg' function in python like in PHP ?
I'm trying to add a cover profile into my web application that could be repositionned .. I found a useful tutorial in this link The problem is that the server side code is in PHP and I'm working with PYTHON and Django . I can't find some functions used in PHP like imagecreatefromjpeg , imageSY , imagedestroy ...etc.. Any help ? -
check existing template in mandrill django
in my database, I stored template info. now I need to check my template is existing in mandrill or not. I read documentaion of mandrill. but I could not check it. could anyone suggest any way to check my template is existing in mandrill or not? -
response['Content-Disposition'] = 'attachment;' in django not downloading the file
filename = "/filepath/in/server" with open(filename, 'rb') as f: response = HttpResponse(f.read(), content_type='application/octet-stream') response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment; filename=filename' print response return response`enter code here` //Clicking on button in my web application should download and save the file from server to my desktop. My html code contains only the button and onclick function(which submits the form and invokes POST). The Post script is written in views.py. The above code is also written in views.py but clicking on the button doesn't download the file as attachment. I can see response content printed in server side. -
Why is my CSS in pythonanywhere taking a day to load?
I change a CSS file, run collectstatic but nothing happens - the app keeps the previous styling, even though that CSS no longer exists anywhere in my files. I got frustrated and gave up yesterday, and found that this morning it had updated, but the initial problem persists. Has anyone else experienced this? Is it just an issue with pythonanywhere or might there be a problem in my code? -
Auto Fill User In Django Form
In my project as soon as user signup it is redirected to update view where he has to fill this information.Since the user has also logged in automatically after signup I want that user field to be filled automatically and can't be edited. models.py class Userpro(models.Model): user = models.OneToOneField(User) dob = models.DateField(default=datetime.date.today) country = models.CharField(max_length=50, default='') qualification = models.CharField(max_length=10, choices=CHO, default='No') university = models.CharField(max_length=100, default='') location = models.CharField(max_length=100, default='') def __str__(self): return str(self.user) forms.py class UserProForm(forms.ModelForm): class Meta: model = Userpro fields = '__all__' views.py def update(request): if request.method == 'POST': form = UserProForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') else: redirect('/') else: form = UserProForm() return render(request, 'app/update.html', {'form': form}) All the required libraries are imported. -
I am unable to deploy my django app on the heroku .How to solve?
So I am trying to deploy my django app over heroku since 3 hrs . Went through many tutorials but still I am unable to make it work . The app is working fine locally Even the foreman app is running the app fine . But I am unable to make it work on heroku .It is deployed successfully but fails to works. Kindly help. Directory and files are in following manner The directories and files are made like that. The codes are on github : https://github.com/Atif8Ted/test_blog This is first try on heroku . Kindly be gentle. -
Django website on VPS with WHM CPanel
What's the difference between mod_wsgi and mod_python. In order to publish django websites on VPS, which one should I install on VPS? -
crispy forms + Bootstrap3: bad position of error field with input-group-addon
When using a input-group-addon, when there's an error, the span element of the error is wrapped by the input-group-addon: the html: <div class="controls col-md-6 input-group"> <input name="name" value="English" class="lang_name dropdown-toggle dropdowntogglewidget form-control form-control-danger" maxlength="40" required="" id="id_name" type="text"> <span role="button" class=" input-group-addon dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span></span> <span id="error_1_id_name" class="help-block"><strong>Languages with this Name already exists.</strong></span> </div> my forms.py: class LanguagesForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): super(LanguagesForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal text_detail' self.helper.label_class = 'col-md-3' self.helper.field_class = 'col-md-6 input-group' ... I guess it's the same problem than Bootstrap 3 form using input-group-addon wrapping error labels with Jquery Validate but here, we have less option... -
How do I prepopulate an inline formset that is purely ImageFields?
I have two models: Profile and CredentialImage. I have implemented inlineformsets to allow the Profile to upload up to 5 maximum images(CredentialImage). Currently, the images save to the database but they will not pre-populate when I revisit the update form, thus allowing the user to upload an unlimited amount of photos 5 at a time. Ideally, the same images saved to the database would pre-populate on the form as to limit the Profile to own and edit only 5 photos at a time. From my understanding, I need to pass in the object to the page to pre-populate information, and I believe I'm doing just that by defining get_object. Here are the two models: class Profile(models.Model): ... def get_absolute_url(self): return reverse("profile:profile_detail", kwargs={"username": self.user}) class CredentialImage(models.Model): profile = models.ForeignKey(Profile, default=None, related_name='credentialimage') image = models.ImageField(upload_to=credential_photo_upload_loc) The modelforms + initialization of the inlineformset_factory: from django.forms.models import inlineformset_factory class ProfileUpdateForm(ModelForm): class Meta: model = Profile fields = [ "introduction", "biography", ] class CredentialImageForm(ModelForm): image = ImageField() class Meta: model = CredentialImage fields = ['image', ] CredentialImageFormSet = inlineformset_factory(Profile, CredentialImage, fields=('image', ), extra=4, max_num=4) A class-based UpdateView for updating a Profile: class ProfileUpdateView(LoginRequiredMixin, UpdateView): form_class = ProfileUpdateForm template_name = 'profile/profile_edit.html' def get_context_data(self, **kwargs): context = … -
Can I execute makemigrations and migrate command in my PyCharm?
I changed my project interpreter to python 3.5, and I still has used to in the terminal to execute the : python manage.py makemigrations python manage.py migrate Because I have changed the project interpreter to python 3.5, I must use python3 manage.py migrate to realize that, sometimes I will write python rather than python3. So is there a method in PyCharm to realize that? -
django TypeError: 'NoneType' object does not support item assignment
class HomeView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) e = [{'year': '2017'}, {'year': '2016'}, {'year': '2015'}] context['e'] = e return context Trying to set the context variable by means of "hard code" results me in TypeError: 'NoneType' object does not support item assignment I am hardcoding the value but it says none is assigned. Doesn't make sense to me.Any clues? -
Displaying two related models in a single get() request
I have two models that are related to each other with user_id, now I want to have a get request in which I will have fields from both the tables. How to make this possible? I guess it would be possible with foreign key, but how do I implement it. Two models look like: model1 class Account(AbstractBaseUser): fullname = models.CharField(max_length=100, blank=True) username = models.CharField(unique=True, max_length=50) email = models.EmailField(unique=True) phonenumber = models.IntegerField(null=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] models2 class Profile(models.Model): User = get_user_model() branch = models.CharField(max_length=20, null=True) year = models.IntegerField(null=True) image = models.ImageField(upload_to="accounts/images/", null=True, blank=True) user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=False, null=True ) I want to display particular user details based on who is logged in at the moment. My get request looks something like this: def get(self, request, format=None): current_user = request.user acc = Account.objects.filter(pk=current_user.pk) serializer = AccountSerializer(acc, many=True) return Response(serializer.data) But this will show only data as of Account model, I want data of Profile model too. How do I do it? -
Django REST framework custom format for all out responses
In my project I use DRF as backend and Angular as frontend. Django==1.10 djangorestframework==3.7.1 I need all responses from DRF to be in the following format. { "status": "", // 200,400,.....etc "error": "", // True, False "data": [], // data "message": "" // Success messages } for this i have written a custom viewset and overridden the functions list, detail, create, update class ResponseModelViewSet(viewsets.ModelViewSet): def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data, status=status.HTTP_201_CREATED, headers=headers) def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on … -
Error WindowsError: [Error 193] %1 is not a valid Win32 application with gdal - GeoDjango
I installed GEODjango with install gdal in Window. But it came error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal201", "gdal20", "gdal111", "g dal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. After that, I config GDAL_LIBRARY_PATH by insert this line to setting.py: GDAL_LIBRARY_PATH = 'C:\Users\User\Desktop\FeedGit\env\Lib\site-packages\osgeo\gdal.py' It came to this error: File "C:\Users\User\Desktop\FeedGit\env\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 49, in <module> lgdal = CDLL(lib_path) File "c:\python27\Lib\ctypes\__init__.py", line 366, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 is not a valid Win32 application I think this is a mistake between Window64 bit and Window32bit. This is my python version: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. My computer is running Window 7 64bit. How can I fix this error, please help me. I really need GeoDjango to mapping many fields on my project. Thanks in advance! -
How to check if a queryset is empty?
Pagination code: try: page = paginator.page(page_number) print(page.object_list) So the following output is the result of print(page.object_list) for my pagination: <QuerySet [<Comment: I can't believe it's happeinig>, <Comment: Just trying to fill up the comments>, <Comment: Another one!>, <Comment: Evenmore noe>, <Comment: Something>, <Comment: Lol>, <Comment: Are comments showing up?>, <Comment: Great for the economy.>, <Comment: honestly>, <Comment: Even though the the onlyEven though the only one to udnertstnaf!>]> <QuerySet [<Comment: Yeah it's crazy how fast aswell. It's very awesome how it's doing atm. >]> <QuerySet []> <QuerySet [<Comment: Sure>, <Comment: No worries>]> <QuerySet []> <QuerySet []> <QuerySet [<Comment: attempt 2!>]> <QuerySet [<Comment: Attempt 3!>]> <QuerySet []> <QuerySet [<Comment: 12>]> <QuerySet []> <QuerySet [<Comment: Somewhere?>]> <QuerySet []> <QuerySet [<Comment: lol>]> <QuerySet []> <QuerySet [<Comment: 12>]> <QuerySet []> As you can see I have empty querysets, and these are causing errors in my code. I therefore would like to iterate over these querysets and spot the empty ones. I tried to add this for loop: for i in page.object_list: if len(i) < 0: but I get an error: TypeError at /news/11/ object of type 'Comment' has no len() Any help appreciated. -
How do I DROP column from database while being inside Django shell?
Here is the scenario: I don't have access to psql prompt. I do have access to python manage.py shell or shell_plus Is it possible to drop a column of that database using Django internals? I know it's possible in theory. Any insights are welcome. -
Deactivate the output format temporarily in IPython
I am learning CBV of Django and intend to make a note for all the methods of 'ListView'. I am working in IPython. In [31]: dir(ListView) Out[31]: [... 'as_view', 'content_type', 'context_object_name', 'dispatch', 'get', ... ] I plan to copy it to my notebook for further reference, whereas the readable format occupies too many space. As a solution,I paste it to a standard python console to get an compact output: [...,'as_view', 'content_type', 'context_object_name', 'dispatch', 'get'....] It's not possible to write a function to get such an output in the IPyhton console. How to achieve it in IPython console. -
How to implement a connection pool in web application like django?
The purpose is to implement a pool like database connection pool in my web application. My application is write by Django. The problem is that every time a http request come, my code will be loaded and run through. So if I write some code to initiate a pool. These code will be run per http request. And the pool will be initiated per request. So it is meaningless. So how should I write this? -
Why am i getting an error when running sudo ./build.sh?
Could not find a version that satisfies the requirement pdb (from -r ./config/requirements.pip (line 37)) (from versions: ) No matching distribution found for pdb (from -r ./config/requirements.pip (line 37)) The command '/bin/sh -c pip3 install -r ./config/requirements.pip' returned a non-zero code: 1 How can i fix this issue? -
django-bootstrap3 Parameter "field" should contain a valid Django BoundField?
I am using django-bootstrap3 to render my forms on the template and i have been struggling to find what is causing the error Parameter "field" should contain a valid Django BoundField when i try to load the page with the form on it. I have attached my code and error below. can someone please point for me what i'm doing wrong? forms.py views.py template browser error -
Tracing API in flask
I have a following front-end code in js(/ember/create/app/components/someFile.js): component.$('.city-select-autocomplete').marcoPolo({ url: '/api/objects/cities', data: {range_size: 8, order_by: '-population'}, minChars: 3, required: true, param: 'search', formatData: function (data) { return data.cities.sortBy('population').reverse(); }, formatItem: function (data, $item) { var state = data.country_code === 'US' ? data.admin1_code + ', ' : ''; return data.name + ', ' + state + data.country_code; }, I am trying to find out where the implementation(server code) is written for url "/api/objects/cities". I tried searching URL mappings but couldn't find it. Project structure: config/ controllers/ deploy/ docs/ ember/ env/ models/ static/ tasks/ templates/ tests/ tools/ utils/ vacuum/ web/ serve.py .. .. .. There must be some url mapping with ("/api/objects/cities") using @app.route annotation but I wasn't able to find it. There must be some convention. api/objects is constant but the last part obj_type varies so there must be a method with the name "cities" and it might be matching by method name. /api/objects/ maps to method with name ? Right ? But I am not finding any such method in controller/web folder. -
config:push is not a heroku command. Perhaps you meant config. How to solve?
When I am typing : heroku config:push I am getting error as config:push is not a heroku command. ▸ Perhaps you meant config ▸ Run heroku help config for a list of available ▸ topics. What should I do ? -
Pass multiple email addresses into exchangelib
I am usng exchangelib in conjunction with Django 1.11 to manage Calendar items. Can anyone provide any guidance on the best way to pass emails to the required_attendees of CalendarItem in my views.py file? required_attendees = [Attendee(mailbox=Mailbox(email_address='user1@example.com'), response_type='Accept')] The number of emails could be from zero to many, eg: required_attendees = [Attendee(mailbox=Mailbox(email_address='user1@example.com'), response_type='Accept'), Attendee(mailbox=Mailbox(email_address='user2@example.com'), response_type='Accept')] At the moment I am repeating code using IF statements based on the length of a list containing all the email addresses. It works but obviously is not the correct way to do it and is very inelegant code. Any guidance will be greatly appreciated! Cheers -
Integrate IDE into Django website
Is there a way to integrate an IDE into a python Django website and have the program created in sed IDE run 24/7 and have the output from the program appear in real time?