Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fill requirements.txt from PyCharm virtual environment
I am trying to fill a requirements.txt for my PyCharm Django project that has a virtual environment. I am using pip freeze > requirements.txt This creates lots of entries as shown here but does not have entries for packages I have added such as djangorestframework, Django-crispy-forms etc. What do I have to do to get all my packages listed? At the moment my requirements.txt looks like this: altgraph==0.10.2 amqp==2.1.4 appdirs==1.4.3 awsebcli==3.10.0 backports.ssl-match-hostname==3.5.0.1 bdist-mpkg==0.5.0 billiard==3.5.0.2 blessed==1.14.1 bonjour-py==0.3 botocore==1.5.26 cement==2.8.2 click==6.7 colorama==0.3.7 coreapi==2.3.0 coreschema==0.0.4 defusedxml==0.4.1 django-appconf==1.0.2 dockerpty==0.4.1 funcsigs==1.0.2 futures==3.1.1 itypes==1.1.0 Jinja2==2.9.6 jmespath==0.9.2 kombu==4.0.2 macholib==1.5.1 MarkupSafe==1.0 matplotlib==1.3.1 modulegraph==0.10.4 numpy==1.8.0rc1 oauthlib==2.0.1 olefile==0.44 openapi-codec==1.3.1 packaging==16.8 pathspec==0.5.0 pbr==3.0.1 progressbar2==3.20.0 psycopg2==2.7.3.2 py2app==0.7.3 PyJWT==1.5.0 pyobjc-core==2.5.1 pyobjc-framework-Accounts==2.5.1 pyobjc-framework-AddressBook==2.5.1 pyobjc-framework-AppleScriptKit==2.5.1 pyobjc-framework-AppleScriptObjC==2.5.1 pyobjc-framework-Automator==2.5.1 pyobjc-framework-CFNetwork==2.5.1 pyobjc-framework-Cocoa==2.5.1 pyobjc-framework-Collaboration==2.5.1 pyobjc-framework-CoreData==2.5.1 pyobjc-framework-CoreLocation==2.5.1 pyobjc-framework-CoreText==2.5.1 pyobjc-framework-DictionaryServices==2.5.1 pyobjc-framework-EventKit==2.5.1 pyobjc-framework-ExceptionHandling==2.5.1 pyobjc-framework-FSEvents==2.5.1 pyobjc-framework-InputMethodKit==2.5.1 pyobjc-framework-InstallerPlugins==2.5.1 pyobjc-framework-InstantMessage==2.5.1 pyobjc-framework-LatentSemanticMapping==2.5.1 pyobjc-framework-LaunchServices==2.5.1 pyobjc-framework-Message==2.5.1 pyobjc-framework-OpenDirectory==2.5.1 pyobjc-framework-PreferencePanes==2.5.1 pyobjc-framework-PubSub==2.5.1 pyobjc-framework-QTKit==2.5.1 pyobjc-framework-Quartz==2.5.1 pyobjc-framework-ScreenSaver==2.5.1 pyobjc-framework-ScriptingBridge==2.5.1 pyobjc-framework-SearchKit==2.5.1 pyobjc-framework-ServiceManagement==2.5.1 pyobjc-framework-Social==2.5.1 pyobjc-framework-SyncServices==2.5.1 pyobjc-framework-SystemConfiguration==2.5.1 pyobjc-framework-WebKit==2.5.1 pyOpenSSL==0.13.1 pyparsing==2.2.0 python-dateutil==1.5 python-openid==2.2.5 pytz==2013.7 PyYAML==3.12 requests-oauthlib==0.8.0 scipy==0.13.0b1 semantic-version==2.5.0 simplejson==3.10.0 six==1.10.0 social-auth-app-django==1.2.0 social-auth-core==1.3.0 sqlparse==0.2.3 tabulate==0.7.5 termcolor==1.1.0 uritemplate==3.0.0 vboxapi==1.0 vine==1.1.3 virtualenv==15.1.0 wcwidth==0.1.7 websocket-client==0.40.0 xattr==0.6.4 zope.interface==4.1.1 -
How can I set up Django Crontab in Docker container?
I have in management/commands file myfile.py and I set it up in this way TIME_ZONE = 'UTC' CRONJOBS = [ ('21 22 * * *', 'django.core.management.call_command', ['myfile']), ] I have added django-crontab to the requirements.txt and 'django_crontab' in INSTALLED_APPS. This file should add data to the PostgreSQL database however it doesn't work. Any ideas why? Maybe I should use Celery scheduler instead? -
ValueError at /post/ No JSON object could be decoded
This is my json: { "documents": [ { "score": 0.5, "id": "1" } ], "errors": [] } I want to know how can I fetch 'score' without converting it into the dictionary?Because when I try to use json.loads it give me the following error: ValueError at /post/ No JSON object could be decoded This is the code which I am using. def GetSentiment(documents): "Gets the sentiments for a set of documents and returns the information." headers = {'Ocp-Apim-Subscription-Key': accessKey} conn = httplib.HTTPSConnection(uri) body = json.dumps(documents) conn.request("POST", path, body, headers) response = conn.getresponse() return response.read() documents = {'documents': [ {'id': '1', 'language': 'en', 'text': caption}, ]} result = GetSentiment(documents) resp_dict = json.loads(result) print resp_dict score = resp_dict["documents"][0]["score"] return score -
Django combine multiple querysets (same model)
I have list of querysets (all for same model): result_elms = [] if city_list: for city in city_list: result_elms.append(results.filter(address__city__icontains=city)) I know that I can use | operator to combine querysets from same model. But how can I apply it for all elements from result_elms list? -
A bug in 'Request and response objects' documentation?
In the first section of Request and response objects | Django ,documentation | Django It says: When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object. Amongst the second sentence, 'the HttpRequest' in passing the HttpRequest as the first argument, its link refers to 'class HttpRequest[source]¶'. It is obvious that it's the object not the class are passed as the first argument. However, the HttpRequest is used instead of the object or the HttpRequest object. If a Bug, it' easy to debug, whereas I checked multiple versions of documentation, they stay the same. If not a Bug, how to explain it? -
django set img src statically using defaul
i am new to django i have two different img tags in my form like this (if user has saved profile image its image will be shown and if not a default image is shown) {% if widget.value.url %} <img src="{{ widget.value.url }}" alt="" id="profile_image" height="200px" width="200px"> {% else %} <img src="{% static 'utils/user.png' %}" id="profile_image" alt="" height="200px" width="200px"> {% endif %} now i want to merge these two using something like this <img src={{widget.value.url|default:{% static 'utils/user.png' %}}} id="profile_image" alt=""height="200px" width="200px"> but that has error and i have tried different types but none works how can i do that exactly? tnx -
How to ad something every third post django
how to put one banner in every post in this ads enter image description here -
How do I thoroughly delete an old image file when a user updates the form's imagefield?
I have two modelforms--one includes a standard ImageField and the other is an inlineformset of ImageFields. The normal standard ImageField renders on the page with the option for "Clear[ing]" while the inlineformset ImageFields render with an optional "Delete" tickbox. Either Clear or Delete will remove the image from the User's profile, but the actual image file will remain in storage, as well as the URL to the image. I am trying to remove all associations to the image once the User updates his Profile form by "clearing" or "deleting" the image. I found FieldFile.delete which I believe just requires me to call .delete() on the instance, but I'm not sure how to conditionally check whether the user is updating the form with the "delete" box or "clear" box ticked. Here are the two models containing the image fields: class Profile(models.Model): profile_photo = models.ImageField( upload_to=profile_photo_upload_loc, null=True, blank=True, verbose_name='Profile Image', ) class CredentialImage(models.Model): profile = models.ForeignKey(Profile, default=None, related_name='credentialimage') image = models.ImageField( upload_to=credential_photo_upload_loc, null=True, verbose_name='Image Credentials', ) The ModelForms: class ProfileUpdateForm(ModelForm): class Meta: model = Profile fields = [ "profile_photo", ] class CredentialImageForm(ModelForm): image = ImageField(required=False, widget=FileInput) class Meta: model = CredentialImage fields = ['image', ] CredentialImageFormSet = inlineformset_factory(Profile, CredentialImage, fields=('image', ), extra=2) … -
Request and response objects
In Django Documentation, Request and response objects | Django documentation | Django When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Amongst the sentence,creates an HttpRequest object is to create an instance. Is it more fancy to mention instance as object to perform as a professional programmer ? -
RelatedObjectDoesNotExist at /register_trainee/succesfull User has no profile
I was Trying to Extend User Model Using a One-To-One Link when I was trying to create a User Object This Error Popped Up here is my models.Py: class Profile(models.Model): phonenumber = models.OneToOneField(User,on_delete=models.CASCADE) and here is my views.py: def trainee_succesfull(request): new_trainee = User() d = request.POST new_trainee.first_name = d['firstname'] new_trainee.last_name = d['lastname'] new_trainee.profile.phonenumber = d['phonenumber'] new_trainee.password = d['password'] new_trainee.save() return render(request, 'trainee/message.html') I know that this question has been answered before but I could not fix the error by looking at the solutions. I would really appreciate It IF someone Can Help. -
Django allauth facebook login failed to redirect back when in an in-app-browser
Problem When in an in-app-browser, like Google Hangout, Telegram or LINE messenger, the user won't be redirected back to my website after a success login through facebook login dialog. It just shows a blank page. Everything works fine when using iPhone Safari app or Android Chrome app. Environment I am using Django==1.11.3 and django-allauth==0.34.0 (which utilizes Facebook Graph API v2.5), and here are my settings.py SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'public_profile', 'user_friends'], 'METHOD': 'js_sdk', 'LOCALE_FUNC': lambda request: 'zh_TW', 'VERIFIED_EMAIL': True } } Anyone experienced the same issue? -
Type object error while trying to inherit a form.Models base class with UserCreationForm base class
I was trying to inherit a form class object which uses forms.ModelForm into a different form class object which inherits from UserCreationForm. I undertand that when form models are been inherited, only one Meta supersedes. However, I still gave it a shot as that's the only way to achieve the business logic I am trying to arrive at. The codes below, pls kindly look through and suggest a work around: class AddressMixin(forms.ModelForm): class Meta: model = Subscriber fields = ['address_one', 'address_two', 'city', 'province'] widgets = { 'address_one':forms.TextInput(attrs={'class':'form-control'}), 'address_two':forms.TextInput(attrs={'class':'form-control'}), 'city': forms.TextInput(attrs={'class':'form-control'}), 'province': forms.TextInput(attrs={'class':'form-control'}), } class SubscriberForm(AddressMixin,UserCreationForm): first_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) password1 = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})) password2 = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})) Heres the error I am getting, AttributeError at /subscribe/signup/ type object 'Subscriber' has no attribute 'USERNAME_FIELD' Again, I understand the error is refering to the subscriber model not having username as an attribute, because the AddresMixin Meta supersedes. However the AddressMixin model contains some business logic methods that needs to be submit during registeration, hence, it needs to pass through the same form. Any advice will help, while I keep trying to figure it out. -
Not redirecting after requests.post django
I'm currently using django rest framework api and I have a form to enter some api information in. I'd like to redirect after I submit my form while still POSTing the data to the API url using the requests library. However the HttpResponseRedirect isn't triggering a redirect for some reason Here is my views.py from rest_frame.requests import reverse import requests def entry_new(request): if request.method == 'POST': form = EntryForm(request.POST) if form.is_valid(): url = reverse("entry-list",request=request) r = requests.post(url, data=request.POST, cookies=request.COOKIES) ## THIS IS WHAT ISN'T FIRING - it goes back to entry_new's URL HttpResponseRedirect(reverse('index2')) else: form = EntryForm return render(request, 'entry_new.html', {'form': form}) class entry_ViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class= EntrySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.partial = True serializer.save(created_by=self.request.user, modified_by=self.request.user, modified_date=datetime.now()) my serializers.py class EntrySerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') modified_by = serializers.ReadOnlyField(source='modified_by.username') class Meta: model = Entry fields = '__all__' my urls.py router = DefaultRouter() router.register(r'entry', views.entry_ViewSet, base_name="entry") urlpatterns = [ url(r'^index2/$',views.index_two, name='index2'), url(r'^cat_new/$', views.category_new, name='cat_new'), url(r'^entry_new/$', views.entry_new, name='entry_new'), url(r'^api/', include(router.urls)), ] -
Django Media Files Not Uploading to S3 Amazon from main site
I'm stuck and confused trying to get this work. I'm running Django on Heroku, using Python 2.7.14 using Django-Storages 1.6.5 trying to upload to Amazon S3. Deploying my site, I can use the Admin site in Django and upload a file to S3 with no problem. Using the non-admin site, I try to upload a media file and it doens't work. The file upload field is is denied by Amazon. Static works with no issue. Why would the Admin site be able to upload media files and the main site not be able to, when they use the same models? -
Serialize queryset based on individual field values using Django Rest Framework
Goal If an object has revealed=true it serializes into: { "id":1, "info":"top secret info", "revealed":true } If an object has revealed=false it omits the info field: { "id":2, "revealed":false } So for a queryset of objects: [ { "id":1, "info":"top secret info 1", "revealed":true }, { "id":2, "revealed":false }, { "id":3, "info":"top secret info 3", "revealed":true } ] Is it possible to achieve this inside of a Django Rest Framework Model Serializer class? class InfoSerializer(serializers.ModelSerializer): class Meta: model = Info fields = ('id', 'info', 'revealed') Background The DRF docs discuss some advanced serializer usage, and this other post dives into an example. However it doesn't seem to cover this particular issue. Ideas A hacky solution would be to iterate over the serialized data afterwards, and remove the info field for every object that has revealed=false. However 1) it involves an extra loop and 2) would need to be implemented everywhere the data is serialized. -
Passing HTML Template Multiple Checkboxes to a new Django form
I'm knew to Django and i'm still learning the ropes. I have the following template, that allows the user to select multiple check boxes. <div class="container"> <div class="row"> <div class="col"> <h3>Financial</h3> <ul> {% for app in fingrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class="col"> How would I pass the result of my checkboxes on report_id to a new form and have it pre-populated with these items after hitting my input/submit button. </br></br> <input class="btn btn-primary" type="button" value="Request Access"> </div> Below is my view and as you'll see I have a lot more grouplists that all use report_id and I want all them to be passed to the form that is generated based on these checkboxes. def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc') reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True) reportaccess = QvReportList.objects.filter(report_id__in= reportIds).values_list('report_name_sc', flat = True) reportGroups = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_group_id', flat=True) reportlist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).exclude(active=0) allreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 100) bhreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 200) cereportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 500) finreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 600) careportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 800) pireportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1100) screportgrouplist = … -
Django form with inputs populated from database
I have a simple Django model structure with Products and Orders, linked by an intermediary table that determines the quantity of each product within a given order: models.py: class Product(models.Model): name = models.CharField() class Order(models.Model): id = models.IntegerField() products = models.ManyToManyField(Product, through='OrderProduct') class OrderProduct(models.Model): order=models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() I'd like to design a form in my forms.py file that 1) pulls a list of every product in the database; 2) gives the user the option to adjust the quantity of each product ordered (e.g., in a CharField input), and 3) creates new Order and OrderProduct objects that store a record of the quantity of each Product ordered by the user. However, I can't figure out a good way to create a form that will automatically pull all Products from the database and add fields to represent the quantity ordered of the given Product. Ideally the result would look something like this, but coded automatically: forms.py: class OrderForm(forms.Form): product_1_quantity = forms.IntegerField() product_2_quantity = forms.IntegerField() product_3_quantity = forms.IntegerField() ....etc., for each product. What's the best way to do this? Does it involve a 'for' loop that creates a new field for each product found in the database? -
Ajax function is not getting the id
I am trying to fix this problem for about 3 days and can not do it. I need to take the id from which is auto incremented in the django. Can you guys help me please. function add_product(){ event.preventDefault(); var name = $("#name").val(); var price = $("#price").val(); var description = $("#description").val(); var dataString = [name, description, price]; var n = dataString.length; $.ajax({ type: "POST", url: "add/", data: { csrfmiddlewaretoken: '{{ csrf_token }}', name: $('#name').val(), email: $('#price').val(), description: $('#description').val(), }, dataType: "json", success: function(){ var button = $('<button class="reo" onclick="delete_product('+ I need to take the id from the database+')" id="my" value="">Delete</button>'); var row = $('<tr>'); for(var i = 0; i < n; i++) { row.append($('<td>').html(dataString[i])); } $('#tableForm').append(row); $('#tableForm').append(button); } }); }; -
Django query many2any self referenced
Currently I have this model: class Group(models.Model): dependency = models.ManyToManyField('self') name = models.TextField() Django create a table with this fields: id from_group_id to_group_id I want to get all rows of model Group that are not in from_group_id. In short I want to get the parent groups -
ValidationError on related model created in inline admin causes 500
I'm creating a one-to-one model to extend the functionality of an existing model type, but I want it to only allow creating the extension model in certain cases. I enforce this constraint by throwing a ValidationError in the full_clean on the new Extended model. This works great when I create Extended models using Extended's ModelAdmin directly (it highlights the a field if it's the wrong type), but when I use StackedInline to inline Extended creation in As ModelAdmin, and A is the wrong type, the form fails to catch the ValidationError and I get the message A server error occurred. Please contact the administrator. This is how I have the models set up: # models.py from django.db import models class A(models.Model): type = models.IntegerField(...) class Extended(models.Model) a = models.OneToOneField(A) def clean_fields(self, **kwargs): if self.a.type != 3: raise ValidationError({'a': ["a must be of type 3"]}) def save(self, *args, **kwargs): self.full_clean() super(Extended, self).save(*args, **kwargs) # admin.py from django.contrib import admin class ExtendedInline(admin.StackedInline): model = Extended @admin.register(A) class AAdmin(admin.ModelAdmin): inlines = (ExtendedInline,) The full traceback: Traceback (most recent call last): File "/usr/local/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 66, … -
How to find Postgres version from Django?
I want to know version of the default Postgres database. How to find it using Django? -
Django on Nginx help needed
I am trying to deploy my website to aws ec2. It's in python/django and I want to learn how to deploy websites myself. I had some issues with aws's EBS so first I'd like to know how to do that manually. I decided to use gunicorn and nginx for this. I can run the website using gunicorn on a virtual env and I created the following script in /home/ec2-user/gunicorn_start.bash: #!/bin/bash NAME="davidbiencom" # Name of the application DJANGODIR=/home/ec2-user/davidbien # Django project directory SOCKFILE=/home/ec2-user/virtual/run/gunicorn.sock USER=ec2-user GROUP=ec2-user NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=davidbiencom.settings DJANGO_WSGI_MODULE=davidbiencom.wsgi echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/ec2-user/virtual/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do$ exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- This runs fine I believe as there are no errors. Next I install nginx and start the service. I confirm it's running as I get the welcome page. Next I do the following: Go to /etc/nginx/nginx.conf and add the following to … -
Django-Python3-LDAP Direct Bind
Is it possible to direct bind to AD with django-python3-ldap? I know search and bind is possible, but this requires someone's AD password to be accessible to other members of the team (i.e. in an environment variable on the server where the Django app is hosted). -
Django: Changed AUTH_USER_MODEL and now getting IntegryErrors when updating other model that references it
I'm using the django-hitcount app on my web app to count hits on some pages, and the hit model references the AUTH_USER_MODEL on a foreign key (the settings variable that defines which model is used as user model). When I started, my webapp wasn't using login, so django-hitcount defaulted to the default user model from Django when I ran the migrations. But now, I've created a custom user model, and the app is throwing integrity errors because, as far as I can tell, the hitcount app ForeignKey is still pointing to the default django user model. IntegrityError at /category/28/22 (1452, ‘Cannot add or update a child row: a foreign key constraint fails (`detdb`.`hitcount_hit`, CONSTRAINT `hitcount_hit_user_id_10387956e3370b97_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))’) Is there any way I can update the foreign key without losing all my hit instances? (using Django 1.11 and MySQL) -
How can I set up Django Crontab in Docker container?
I have in management/commands file myfile.py and I set it up in this way TIME_ZONE = 'UTC' CRONJOBS = [ ('21 22 * * *', 'django.core.management.call_command', ['myfile']), ] I have added django-crontab to the requirements.txt and 'django_crontab' in INSTALLED_APPS. This file should add data to the PostgreSQL database however it doesn't work. Any ideas why?