Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload multiple images for my product model in django?
I want to upload multiple images of the product so how can I do that? Django version is 2.1 and how to store the multiple files as well. Using python3 My model class Product(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) name = models.CharField(max_length=33, blank=True) description = models.TextField() postdate = models.DateTimeField(auto_now_add=True, blank=False) duration = models.IntegerField(null=True, blank=True) image = models.FileField(upload_to=product_directory_path, blank=False, default='default.jpg') My View def addProduct(request): if request.method == 'GET': if request.user.is_authenticated: return render(request, 'postAd.html') if request.method == 'POST' and request.FILES.get('image'): if request.user.is_authenticated: user = User.objects.get(id=request.user.id) owner = UserProfile.objects.get(email=user.email) image = request.FILES.get('image') name = request.POST['name'] description = request.POST['desc'] pr = Product(owner=owner, name=name, image=image, description=description, category=category, price=price, ptype=ptype) pr.save() return HttpResponseRedirect(reverse('ors:dashboard')) -
How to display an Excel sheet in Django?
im working on a Django website and i wnat to display an Excel Sheet that can later be edited on the website. Right now i am only able to upload a file but nothing is displayed. I know FileField is probably the way to go but how do i make the file show on the webpage? Django-excel seems does not do the job for me, because i think there is a much easier way to just display a file (but not an image). Here is my models.py from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to="documents/") uploaded_at = models.DateTimeField(auto_now_add=True) Here is my views.py class UploadFileForm(forms.Form): file = forms.FileField() def index(request): documents = Document template = loader.get_template('documents/index.html') context = { 'documents' : documents } return HttpResponse(template.render(context, request)) def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('documents:index') else: form = DocumentForm() return render(request, 'documents/model_form_upload.html', { 'form': form }) My forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'document') and my upload_template.html where the file should be displayed at the end <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'documents:index' %}">Return to Home</a></p> … -
Using instance in ArrayField valid?
I have user accounts with the field "donation_methods". A user can you choose between different methods to accept donations. By default every user should have the value: 'cash' in the array Is this the correct way to do this because it's an instance and not a callable? donation_methods = ArrayField( models.CharField( max_length=15, choices=DONATION.CHOICES, ), default=list({DONATION.CASH}), ) -
Using instance in ArrayField valid?
I have user accounts with the field "donation_methods". A user can you choose between different methods to accept donations. By default every user should have the value: 'cash' in the array Is this the correct way to do this because it's an instance and not a callable? donation_methods = ArrayField( models.CharField( max_length=15, choices=DONATION.CHOICES, ), default=list({DONATION.CASH}), ) -
Using instance in ArrayField valid?
I have user accounts with the field "donation_methods". A user can you choose between different methods to accept donations. By default every user should have the value: 'cash' in the array Is this the correct way to do this because it's an instance and not a callable? donation_methods = ArrayField( models.CharField( max_length=15, choices=DONATION.CHOICES, ), default=list({DONATION.CASH}), ) -
Using instance in ArrayField valid?
I have user accounts with the field "donation_methods". A user can you choose between different methods to accept donations. By default every user should have the value: 'cash' in the array Is this the correct way to do this because it's an instance and not a callable? donation_methods = ArrayField( models.CharField( max_length=15, choices=DONATION.CHOICES, ), default=list({DONATION.CASH}), ) -
Template Tags not loading the intended output after loading onto Apache WSGI server
I loaded a Django project onto an Apache server and after a some research, managed to configure it correctly. The only issue now is that the bits of the pages generated by the template tag filters aren't displaying. I tried to check if permissions were the issue but I can't seem to pin-point the issue. I also attempted to configure the Apache config file to include an alias and give the template tags directory/file permission to execute but to no avail. What could the problem possibly be? Alias /static /var/www/html/spec2build/spec2build_final/spec2build/static <Directory /var/www/html/spec2build/spec2build_final/static/> Require all granted </Directory> Alias /media /var/www/html/spec2build/spec2build_final/spec2build_final/media <Directory /var/www/html/spec2build/spec2build_final/spec2build_final/media> Require all granted </Directory> Alias /templates /var/www/html/spec2build/spec2build_final/templates <Directory /var/www/html/spec2build/spec2build_final/templates> Require all granted </Directory> Alias /templatetags //var/www/html/spec2build/spec2build_final/spec2build/templatetags <Directory /var/www/html/spec2build/spec2build_final/spec2build/templatetags> <Files filter_render.py> Order allow,deny Allow from all </Files> </Directory> -
Invalid HTTP_HOST header: 'awssgp0-files.fds.api.xiaomi.com' request header attack
I am getting this request (more then 2000 per day) from different country . "Invalid HTTP_HOST header: ‘awssgp0-files.fds.api.xiaomi.com’. You may need to add u'awssgp0-files.fds.api.xiaomi.com' to ALLOWED_HOSTS. Report at /yimotiondetection/2018/10/23/168333/DJVLPPMM81DCHLPN111A_1540282131_0.jpg Invalid HTTP_HOST header: ‘awssgp0-files.fds.api.xiaomi.com’. You may need to add u'awssgp0-files.fds.api.xiaomi.com' to ALLOWED_HOSTS. Request Method: PUT Request URL: http://awssgp0-files.fds.api.xiaomi.com/yimotiondetection/2018/10/23/168333/DJVLPPMM81DCHLPN111A_1540282131_0.jpg?GalaxyAccessKeyId=5661733440758&Expires=1540283933264&Signature=z9QvtfFxrlvtKiMiNiRGmMj2u/0= " I am using elasticbeanstalk . kindly suggest me any solution to block these request -
How to enable the Is Visible Field in Zinnia blog (a django app)?
The Is Visible field in Django package Zinnia blog is not active in the admin interface for entries. As a result I cannot see any of my posts. How do I enable the same? -
How to install a lower version of Django using pip in a virtual Environment
I'm trying to install Django 1.8 on a virtual environment in the server. using pip install Django==1.8 But It finds the newer Django version outside the virtual Environment and installs Django 1.11 instead. Is there any way to install Django 1.8 on the virtual Environment without having to uninstall The Django 1.11 outside the Virtual Environment?? -
DRF: Where should I place logic processing when saving an object
I am working on a small app where users will upload an Excel sheet (FileUpload model) and the sheet is searched for strings matching a particular RegEx. Strings matching this RegEx are the primary key from another model (FileDevice model). My research has so far pointed to placing this logic in the serializer of the FileUpload model but I'm not sure how. Do the comments in the create function look like I'm on the right path or should this logic be performed elsewhere? Model: class FileUpload(models.Model): uploadid = models.AutoField(primary_key=True) user_uploaded = models.CharField(max_length=64, blank=True) time_uploaded = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to=rename_uploaded_file, blank=False, validators=[validators.excel_file_extensions]) devices = models.ManyToManyField(FileDevice, blank=True, related_name='files') class FileDevice(models.Model): device_name = models.CharField(primary_key=True, max_length=16) Serializer: class FileDeviceRelationshipSerializer(serializers.ModelSerializer): files = FileUploadSerializer(many=True, read_only=True) class Meta: model = models.FileDevice fields = '__all__' def create(self, validated_data): # 1. Search for strings in file # 2. Add all string matches to a set # 3. For every entry in set, link to that instance of a different model # 4. Save object -
DRF Django filter range for a CharField
I needed to save creation time as string in model, so I used CharField. But now I have problem filtering by queryparams for obtain objects in range of two times. I see that 'lte' and 'gte' are not working for strings. Anyone have some ideas on how i could do that? -
django 2.1 checkboxselectmultiple
Please help.... I am new to django I keep getting this error on POST method when saving " Select a valid choice. ['DST', 'DAB', 'CGAA'] is not one of the available choices. " here are my codes; models.py class research_data(models.Model): sourcefund_choices = ( ('DPCIE','DOST-PCIEERD'), ('DPCAA','DOST-PCIEERD'), ('DST','DOST'), ('CHD','CHED'), ('DA','DA'), ('DAB','DA-BAR'), ('CGAA','CSU-GAA(fund 101)'), ('C164','CSU(fund 164)'), ) source_fund = models.TextField(blank=True,choices=sourcefund_choices) amt_granted = models.IntegerField(blank=True) status_res = models.CharField(max_length=20,choices=status_choices) date_start = models.DateField(blank=True,default=timezone.now) date_completed = models.DateField(blank=True,default=timezone.now) forms.py class ktmform_main(forms.ModelForm): class Meta: fields = { 'source_fund', 'amt_granted', 'status_res', 'date_start', 'date_completed', } widgets = { 'source_fund': forms.CheckboxSelectMultiple(attrs={'class':'filled-in','id':'sf'}), 'amt_granted': forms.NumberInput(attrs={'class':'validate','id':'amtg'}), 'status_res': forms.Select(), 'date_start': forms.TextInput(attrs={'class':'datepicker','id':'dst'}), 'date_completed': forms.TextInput(attrs={'class':'datepicker','id':'dcm'}), } views.py def res_add(request): if request.method=='GET': ktmfrm = forms.ktmform_main() args = { 'ktmfrm':ktmfrm, } return render(request,'IMS/Res_Form.html',args) else: ktmfrm = forms.ktmform_main(request.POST,request.FILES) if ktmfrm.is_valid(): ktmfrm.save() ktmfrm=ktmform_main() args = { 'ktmfrm':ktmfrm, 'stat':'saved', } return render(request,'IMS/Res_Form.html',args) else: args = { 'ktmfrm':ktmfrm, 'stat':'failed', } return render(request,'IMS/Res_Form.html',args) "source_fund" is the field with CheckboxSelectMultiple as the form widget -
How to use an API from wholesalers to populate inventory on small business website?
I've been building some simple websites with django and am somewhat comfortable with it, enough to use models, templates and apps at least. Now, I'm making a website for a friends small business that will have shopping cart functionality, and will display inventory. He doesn't have anything in stock and get's it all from wholesalers, so inventory will be shown directly from wholesalers database who have an API. Everything I could find when searching for a tutorial covered creating an API, not using one. Do I have to have a mode or a database locally? Or is everything taken from the API as a series of get requests? How do I pull say, all cars that are yellow, or all that are yellow made by BMW, and display on my inventory page with pagination? Not asking for a specific set of instructions here, just a very high level overview so I know what to search for to teach myself how to do this. -
How to serve images inside the document root folder using django and apache
I have deployed a django app using apache. Am using an app called django-ads which allows me to upload images. The app dumps the images inside the BASE_DIR folder so the image url is http://ip-address/iphone.jpeg when it is displayed on an html page. Below is how my conf file looks: ServerAdmin webmaster@localhost DocumentRoot /var/www/html WSGIScriptAlias / /var/www/html/mysite/wsgi.py WSGIDaemonProcess advert-admin python-home=/home/joe/advert-admin/venv python-path=/var/www/html WSGIProcessGroup advert-admin <Directory /var/www/html/> AllowOverride all Require all granted Options FollowSymlinks </Directory> Alias /static/ /var/www/html/static/ <Directory /var/www/html/static> Require all granted </Directory> I get a 404 error every time an image is loaded. How can serve the images inside /var/www/html folder using Apache so that http://ip-address/iphone.jpeg does not return a 404? -
remote_addr value is not storing IPaddress in auditlog_logentry table in Django
i am using django-auditlog plugin.when i try to register a member into database, the values are storing into a users table and its logentry is recorded in auditlog_logentry table.but remote_addr field value is inserting as null instead of ip address.what can i do to resolve this? from auditlog.registry import auditlog from django.db import models class Users(models.Model): firstname = models.CharField(max_length=40,default='') middlename = models.CharField(max_length=40, default='') ... auditlog.register(Users) -
Migrations being applied according to User in models.py instead of being applied according to migrations in the database
I have written a custom django migrations command as shown below User = get_user_model() def populate_asset_assignee(apps, schema_editor): for user in User.objects.all(): user.save() # Some more code The user model looks as follows class User(AbstractUser): username = None email = models.EmailField(max_length=50, unique=True) cohort = models.IntegerField(blank=True, null=True) slack_handle = models.CharField(max_length=50, blank=True, null=True) picture = models.CharField(max_length=255, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) last_modified = models.DateTimeField(auto_now=True, editable=False) password = models.CharField(max_length=128, blank=True, null=True) location = models.ForeignKey('SomeCentre', blank=False, null=True, on_delete=models.PROTECT) # Some more fields I added the location field recently and have the migrations for it which is applied after this custom migration has been applied. The problem I am having is that whenever I try to make the migrations on the test db or a new database, I get the error django.db.utils.ProgrammingError: column core_user.location_id does not exist which is being raised inside the populate_asset_assignee method when I try to do the user in User.objects.all() Any ideas why location_id is beeing checked yet I haven't applied the migrations for the location field yet. -
How to call a javascript function in from your views.py file in Django
Hi I have this JavaScript function: function calcscore(){ var score = 0; $(".calc:checked").each(function(){ score+=parseInt($(this).val(),10); }); $("#price").text(score); } $().ready(function(){ $(".calc").change(function(){ calcscore() }); }); Now i want to call this calcscore() fucntion on views.py in Django. Say i have this function on my Views.py def get_total(): try: final_cost =0 final_cost = calcscore() except: dummy_cost return final_cost Should i use ajax? or how can i achieve this? -
'Classname' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I am creating a simple api to update a particular coulumn in the database but am getting the issue that there is no serializer class included while i have included a serializer class views.py class ClassName(ResponseData, GenericAPIView): serilizer_class = UpdateSerializer @swagger_auto_schema(manual_parameters=[auth, data]) def put(self, request, format=None): data = request.GET.get('data') output = dict() if data: serializer = self.get_serializer( user=request.user.id, data=data) if serializer.is_valid(): output['message'] = 'UPDATED' return Response(self.get_data(output), status=status.HTTP_200_OK) and the serializer.py file contains the following code class UpdateSerializer(serializers.ModelSerializer): def update(self, user, data): user = User.objects.filter(user_id=user).update(column_name=data) return user class meta: model = User fields = ['email', 'first_name', 'last_name', 'wallet_address', 'status', 'image'] -
Django many2many aggregation
need help with aggregation in Django,and I need to annotate some data to each products row. I have models: class Item(Model): price = DecimalField() somedata = CharField() class ItemPack(Model): item = ForeignKey(Item) quantity = PositiveIntegerField() class ItemTwo(Model): price = DecimalField() somedata = CharField() class ItemTwoPack(Model): item = ForeignKey(ItemTwo) quantity = PositiveIntegerField() class Product(Model): pack = ManyToManyField(ItemPack) pack_two = ManyToMany(ItemTwoPack) Is it possible to calculate the total cost of Product here with ORM? I tried this, but seams I am doing something wrong, because I get incorrect result: Product.objects.annotate( total=( Sum(F('pack__item__price) * F('pack__quantity'), output_field=DecimalField())+ Sum(F('pack_two__item__price) * F('pack_two__quantity'), output_field=DecimalField()) ) ) But I get wrong value in total with this query. -
can we retrieve the data by sending id field as json object using POST method in django rest framework
GET : http://127.0.0.1:8000/r/ { "count": 5, "next": null, "previous": null, "results": [ { "id": 1, "url": "http://127.0.0.1:8000/r/1/", "name": "India", "code": 91 }, { "id": 2, "url": "http://127.0.0.1:8000/r/3/", "name": "us", "code": 10, }, { "id": 3, "url": "http://127.0.0.1:8000/r/4/", "name": "pak", "code": 9 }, { "id": 4, "url": "http://127.0.0.1:8000/r/5/", "name": "kansas", "code": 44 }, { "id": 5, "url": "http://127.0.0.1:8000/r/6/", "name": "kanada", "code": 123 } } I know that , suppose I can get "name": "us", "code": 10 based on it's "id": 2 by specifying the id in the URL like http://127.0.0.1:8000/r/2, By using GET method, but I want to retrive "name": "us", "code": 10 based on it's "id": 2 by sending it(means 'id') as json object using 'POST' method. -
How to make a SSL Websocket work with Django-channels
I'm trying to figure out how to get this websocket to work through ssl in https. Following the django-channels tutorial, I've made a similar web app to the tutorial and deployed it to Heroku. Heroku's hosted site is secured, so I have my websocket connecting via 'wss://', but this causes errors in the browser console like so: WebSocket connection to 'wss://asyncdrawshare.herokuapp.com/ws/drawshare/gfdg/' failed: Error during WebSocket handshake: Unexpected response code: 404 WebSocket is already in CLOSING or CLOSED state. The first error references: var drawSocket = new WebSocket( 'wss://' + window.location.host + '/ws/drawshare/' + roomName + '/'); And the second references: drawSocket.send(JSON.stringify({ 'color': drawColor.value, 'x1': x, 'y1': y, 'x2': x + 4 , 'y2': y + 4 })); These are both part of my rooms.html The first error indicates an un-found url. This doesn't make sense to me given the routing: # drawshare/routing.py from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url(r'^ws/drawshare/(?P<room_name>[^/]+)/$', consumers.DrawConsumer), ] It would seem to be this would imply a 404 should not be returned. The second error seems to be a result of the first as any send invokes another instance of that error. So if you have any insight into what is going, … -
Django Password Reset Showing NoReverseMatch error
Here is my urls.py from django.urls import path, include from django.contrib import admin import staticpages.views as home_page_views admin.autodiscover() urlpatterns = [ path('', home_page_views.HomePageView.as_view(), name='home'), path('', include('staticpages.urls')), path('accounts/', include('django_registration.backends.activation.urls')), path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('userprofile.urls')), path('admin/', admin.site.urls), ] here is my password_reset_email.html template You have requested a password reset on the website. Please click the following link to complete the password reset process. {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} When I click on the link in the generated email it shows me the following error: Reverse for 'password_reset_confirm' with arguments '('', '')' not found. 1 pattern(s) tried: ['accounts/reset/(?P<uidb64>[^/]+)/(?P<token>[^/]+)/$'] I have absolutely no idea what is causing this issue. If you require any more information then please leave a comment and I will update the post with more information. I have looked at the other questions about a similar issue but none of them fix my problem as I am already including the auth URLs in my urls.py file. -
Django QuerySet for Counting items for each distinct field in any given month, including 0 value
#models.py class Orders(models.Model): orderid = models.IntegerField(db_column='orderID', primary_key=True) pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True) pickupstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='pickupStore', blank=True, null=True,related_name = 'pickupstore') class Branch(models.Model): branchid = models.IntegerField(db_column='branchID', primary_key=True) # Field name made lowercase. city = models.CharField(max_length=45, blank=True, null=True) The pickupstore field in Orders Class model refers to Branch Class Model. I would like to count the number of pickups for all stores(branches) in any given month, including when stores(branches) have 0 pickups in that particular month This is my solution for counting the number or pickup in all stores (branches in January of 2006, however, it doesn't include stores that have 0 orders branchs = Orders.objects.all().select_related('pickupstore').values('pickupstore__city').filter(pickupdate__year = 2006, pickupdate__month = 1).annotate(num=Count('pickupstore__city')).order_by('pickupstore__city') branchs = branchs.values('pickupstore__city').filter(pickupdate__year = year, pickupdate__month = month) branchs = branchs.annotate(num=Count('pickupstore__city')).order_by('pickupstore__city') -
Python 3.6 - What does "string % tuple" do?
I am writing a python module for an Django-based application that accesses an Oracle database via cx_Oracle. It "appears" that the django code has a bug that breaks the use of the cx_Oracle "executemany" method. If I use cx_Oracle with a connection opened strictly via cx_Oracle, the logic works fine. Use a connection via django, it fails. As django is a requirement, I am looking for a work-around and need to understand what the statement (below) where it fails is trying to do. I understand that "%" is used both as a modulo operator and for string formatting as it apparently is in this case. But despite much searching, this doesn't seem to conform to any string formatting syntax using "%" that I can find. Can someone explain what this is trying to do? query = query % tuple(args) TypeError: not all arguments converted during string formatting Where: query = 'INSERT INTO DATABASE.TABLE\n (DATE, ID, COL_A, COL_B, COL_C)\n VALUES (:1, :2, :3, :4, :5)\n' args = [':arg0', ':arg1', ':arg2', ':arg3', ':arg4'] If you type these values and the above statement into the REPL, you will get this same error. I know I should submit a django bug report. Will figure …