Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get StringRelatedField along with PrimaryKeyRelatedField using Serializer in DRF
Sorry for this newbie question, but I simply cannot find my way reading the manual. models #Subject class TemaPai(models.Model): subject = models.TextField() disciplines = models.ManyToManyField(Materia) # order = models.IntegerField(blank=True, null=True) def __str__(self): return self.subject class Meta: verbose_name_plural = "temas-pais (subjects)" # Order and junction class TemaPaiOrdem(models.Model): subject = models.ForeignKey(TemaPai, on_delete=models.CASCADE) discipline = models.ForeignKey(Materia, on_delete=models.CASCADE) order = models.IntegerField() def __str__(self): var2 = self.subject.subject var = self.discipline.discipline return var2 + ' - ' + var class Meta: verbose_name_plural = "Temas-pais-ordem" unique_together = ('subject', 'discipline') serializers class TemaPaiSerializer(serializers.ModelSerializer): disciplines = serializers.PrimaryKeyRelatedField(many=True, queryset=Materia.objects.all()) class Meta: model = TemaPai fields = ('id', 'subject', 'url', 'disciplines') class TemaPaiOrdemSerializer(serializers.ModelSerializer): discipline = serializers.PrimaryKeyRelatedField(queryset=Materia.objects.all()) subject = serializers.PrimaryKeyRelatedField(queryset=TemaPai.objects.all()) class Meta: model = TemaPaiOrdem fields = ('id', 'subject','discipline', 'order') Well, TemaPaiOrdemSerializer is giving me a list like this: [ { "id": 1, "subject": 1, "discipline": 1, "order": 1 }, { "id": 2, "subject": 2, "discipline": 1, "order": 11 } ] It is fine. But I want to retrieve the subject string representation (from TemaPai model) as well, as a read_only field. So my desired list would be something like: [ { "id": 1, "subject": 1, "subject_name": "Introduction", "discipline": 1, "order": 1 }, { "id": 2, "subject": 2, "subject_name": "Advanced stuff", "discipline": … -
Django reusable app with multiple app inside
My current folder tree looks like: my_reusable_app .gitignore MANIFEST.in README.rst setup.py I would like to have multiple apps inside this one reusable app: my_reusable_app my_reusable_app_users my_reusable_app_payments .gitignore MANIFEST.in README.rst setup.py How can I achieve this? How to setup urls etc.? -
Accessing model inside a function based view.
Is there a way to access model instance in function based view? I tried the code below in a hardcoded strategy. I need it to be dynamic. Form: <form method="POST" action="{% url 'cadmin:toggle_status' model='Library' %}" #***** Model is hardcoded class="visible-lg-inline"> {% csrf_token %} ..... </form> URL: path('toggle-status/<slug:model>', toggle_status, name='toggle_status'), View: def toggle_status(request, model): /******* How can i access model instance here? *********/ if request.POST: toggle_status = request.POST.get('toggle-status') pk = request.POST.get('pk') if toggle_status and pk: if model == "Zone": Zone.objects.filter(pk=pk).update(status=toggle_status) if model == "Library": Library.objects.filter(pk=pk).update(status=toggle_status) return HttpResponseRedirect(reverse('cadmin:library_list')) -
Reverse relation in Django
I am trying to fetch multiple images for a particular post-id and i have a piece of code which is working for me but I am not able to understand why/how? If anyone can explain and/or give me some documentation for the same I would be able to use it in future as well. This is the code I am trying to understand. Thanks. {% for posts in posts %} {{ posts.id }} {% for image in posts.post_image.all %}<!--first post is for the "for loop" second post for the post field in model and all is for all images I guess.--> {{ image.image }} <a href='#'><img src='{{ image.image.url }}' class="img img-responsive image " width='100'/> </a><br> {% endfor %} {% endfor %} view.html: *{% extends 'base.html' %} {% block main_content %} <div class="content-wrapper"> <div class="container-fluid"> {% if posts %} {% for post in posts %} </div> <div class="strip"> <div class="row"> <div class='col-md-8'> <h6><a href="/final/{{ post.id }}" class="nav-link js-create-book" data-toggle="modal" data-target="#exampleModal">{{ post.title|title }}</a></h6> </div> <div class='col-md-4'> <a href="/delete/{{ post.id }}" class='demo'><i class="fa fa-close pull-right"></i></a> <a href="/edit/{{ post.id }}" class='' ><i class="fa fa-pencil pull-right"></i></a> </div> </div> <div class='row'> <div class="col-md-10"> <div class="descrip"> <p><small>{{ post.description|truncatechars:250 }}</small> </p> </div><!-- descrip ends--> <p><small><strong>{{ post.created_at }}</strong></small></p> <!-- … -
Django background fail
I have a problem with displaying background at phone. Okay where is the problem, I have a page uploaded at django with background picture with logo of company. Everything works fine, background looks cool even if I choose responsive view on the page at my pc. But when a look at my page at phone the background is pixelate and when I browse trough the page it is moving up and down. Does anybody know where might be problem? Page: nanet.pythonanywhere.com/eshop/index Code: github.com/MartinStevko/SEN_eshop -
How to use uwsgi whitelist command
how to setting whitelist in my uwsgi.ini to let it working my ini setting: [uwsgi] http = :80 chdir = /usr/local/myproject wsgi-file = myproject/wsgi.py master = true processes = 2 threads = 4 chmod-socket = 664 vacuum = true plugins = http,python3 stats = 127.0.0.1:5566 static-map = /static=/usr/localmyproject/static whitelist = 127.0.0.1 -
Querying data with filters using django rest framework
So I'm using django rest framework on top of django as my serverside and MongoDB as a database (a mongo replica set, to be specific). My model looks like this: #models.py class MyModel(models.Model): data = models.TextField() Here's the serializer that I'm using: #serializers.py class MySerializer(serializers.ModelSerializer): data = serializers.JSONField(binary=True) def create(self, validated_data): test = MyModel(data=validated_data) test.save() return test class Meta: model = MyModel fields = ['data'] This is my view: #views.py class MyView(APIView): serializer_class = MySerializer def post(self, request): serializer = self.serializer_class(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() except djongo.sql2mongo.SQLDecodeError: return Response( status=status.HTTP_503_SERVICE_UNAVAILABLE ) return Response( status=status.HTTP_200_OK ) Then, in a test mode, I make a few records into the database using httpie. The requests look like this: http POST localhost:8000/api/test data='{"sizes": ["M", "L"], "colors": ["white", "yellow"], "model": "poet"}' http POST localhost:8000/api/test data='{"colors": ["red", "black"], "sizes": ["S", "M"], "model": "polo", "material": "silk"}' http POST localhost:8000/api/test data='{"colors": ["white", "yellow"], "sizes": ["M", "L", "XL"], "model": "poet", "material": "bamboo"}' The data is written to the DB and replicated. So now I would want to make the following query: test = MyModel.objects.filter(data__contains={'sizes': ['M', 'L']}) But it returns an empty queryset and it's not supposed to. What am I doing wrong? -
Django best practice - compare users
I'm working on a small project and I have a user profile page. This page has a variable called user. This variable contains the user object of the current profile page. The logged in user object is accessible with request.user If you just print the user object it will return the username because the model returns this in the __str__ function What is the best way to compare if the user profile belongs to the current user? I could just write if user == request.user But what if django changes the return value of the __str__ function? or I could write if user.username == request.user.username or if user.id == request.user.id -
django application image broken after upload to aws s3
I have a django project which is hosted on heroku and amazon s3 is used to store static files. When ever an image is uploaded with the application(django-oscar) the image shows for a few minutes and if i view page source and click on the image link, the image shows up but after a few minutes the image appears broken and when ever I check the image source and I click on the image I get this response <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>cache/a8/2b/a82bd1030ccf019a87yhd766d1b9d62a71a4956.jpg</Key> <RequestId>3A990EFFD267D5BC</RequestId> <HostId> Bkspd4xpxp0R/3A6TmPF5bq+tM0BjF/v5oU5p12pccdkcNMDPf1JoYuigErtGjhksauajszFCajOEgBD3M= </HostId> </Error> and I have another django project being hosted on heroku and it does not happen like that and I use the same s3 settings for both. conf.py import datetime AWS_ACCESS_KEY_ID = "AKIAJ7GLHHZEGEYSJUIOXWYHZCA" AWS_SECRET_ACCESS_KEY = "wzsAPF18E9cfYTY*JKSKAUU87ja.aia8yaFCKzYit9uIQHk64EVD4OWpfjufECcnOt" AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = 'ze.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'ze.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'ze' S3DIRECT_REGION = 'us-west-2' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ), } utils.py from … -
Decode url(r'^(?P<pk>[-\w]+)/$') to path() in Django
I need to convert the following regular expression using url() method to path() method. url(r'^(?P<pk>[-\w]+)/$') Thanks and regards. -
Single sign on between different domain and platfomm
How to achieve single-sign-on between two different domain and platform. I have created a site in open-edx and use my other wordpress site as user sign in. My issue is if I am login to wordpress site and open my edx site it should be logged in and redirect me to my profile page. How can I identify in edx site that I am alredy logig in other site and take me to the profile page, like youtube and gmail. Thanks. -
Django + Python website - button for running script - RasPi
I am hosting a local server using Django and Python on my Raspberry Pi. What i want to do is practically create a button on my home website, that when clicked will run certain script, for example different Python script as subprocess or a method in view with the script, doesnt matter. I would also like a button with form which would make me get the text input from user written in the form to a variable in views to actually use it. I've searched and tried thru all existing stuff i believe, like guides and others and none have worked for me. Starting from different button settings ending with form - POST. The closest i got is with this script. this one actually worked but only ended up giving FORM type into console and refreshing page, nothing more. I know its a mess but after trying for 3 days straight i ended up bruteforce trying sollutions so please try to put up with me. views.py urls.py -
The django view didn't return an HttpResponse object. It returned None instead
The view login.views.IndexView didn't return an HttpResponse object. It returned None instead. class IndexView(FormView): form_class = NameForm template_name = 'reg.html' success_url='display' def form_valid(self, form): form.save() def dis(request): st4=[] st5=[] ob=Register.objects.all() for i in ob: st4.append(i.name) st5.append(i.rollno) return render(request,'view.html',{'st4':st4,'st5':st5}) -
Error: Wheels are not supported
The travis test returns an error which states Error: Wheels are not supported when it is install Django==2.0.4 even though the Django version supports wheels. What is the problem here? Relevant Link : https://github.com/django-blog-zinnia/zinnia-wysiwyg-tinymce/pull/10 -
Redis & Celery Cassandra for Statistics Handling
I have 8 instances with 5000 Input threads each, each thread will receive 2Kb of data every 10 seconds. I have a separate DB instance to store the entire data from 8 instances after computations and processing. I am planning to store the data initially to the corresponding Redis instance before moving to the database since it will free my input threads very quickly. I will receive around 65Mb of data per 10 seconds from each instance, so around 550 MB data as a whole from 8 instances. I am planning to run Django celery workers at each instance which will migrate the data from the corresponding Redis to DB instance. I have some interdependent data between each Redis instance which I need to compute/accumulate before/after storing to the DB. Am I on the right track. Where should I compute the interdependent data, after pushing to DB or before pushing with some lock mechanisms to handle conflicts during concurrency? Is Redis the right choice to store data initially, and Django celery enough/apt for my architecture. Please lead me on the right track. -
flask on lighttpd with fastcgi not serving css and images
I'm trying out to deploy flask application with lighttpd and Fast-CGI. On starting the lighttpd server, HTML page is rendered on the browser, but corresponding CSS and images wasn't served by lighttpd. Following are the minimal setup code snippet:- Flask (File name: - example.py) #!/usr/bin/env python from flask import Flask from flask import render_template app = Flask(__name__) @app.route("/") def hello(): return render_template('topic.html') HTML(File name: - topic.html) <!DOCTYPE html> <body> <img alt="logo" src="{{ url_for('static', filename='img/example.png') }}"> </body> </html> fcgi enabled WSGI (File name: - test.fcgi) #!/usr/bin/env python from flup.server.fcgi import WSGIServer from example import app if __name__ == '__main__': WSGIServer(app, debug = True).run() lighttpd config file server.modules += ( "mod_fastcgi" ) server.modules += ( "mod_rewrite" ) server.modules += ( "mod_alias" ) server.modules += ( "mod_accesslog" ) server.document-root = "/var/www/testing/" server.port = 5000 server.modules += ( "mod_cgi" ) mimetype.assign = ( ".html" => "text/html", ".txt" => "text/plain", ".jpg" => "image/jpeg", ".png" => "image/png", ".js" => "text/javascript", ".css" => "text/css" ) cgi.assign = ( ".pl" => "/usr/bin/perl", ".cgi" => "/usr/bin/perl", ".rb" => "/usr/bin/ruby", ".erb" => "/usr/bin/eruby", ".py" => "/usr/bin/python", ".php" => "/usr/bin/php-cgi" ) index-file.names += ( "index.pl", "default.pl", "index.rb", "default.rb", "index.erb", "default.erb", "index.py", "default.py", "index.php", "default.php" ) server.errorlog = "/var/log/lighttpd/error.log" accesslog.filename = "/var/log/lighttpd/access.log" … -
django.core.management.sql.sql_delete removed on django 1.11
I'm upgrading django from 1.8 to 1.11 and this imports are failing from django.core.management.sql import sql_delete *** ImportError: cannot import name sql_delete from django.core.management.sql import sql_all *** ImportError: cannot import name sql_all I was looking for the remove mention in the releases notes but I couldn't find anything. Does anyone know when were removed and any alternative to replace it? -
write inner join query in django
i have two tables and need to write this query in django my models are: class students(models.Model): name = models.CharField(max_length=30) active = models.BooleanField(max_length=1) class college(models.Model): department = models.CharField(max_length=20) college_name = models.CharField(max_length = 50) s_id = models.ForeignKey(students, on_delete=models.CASCADE) my mysql query: select b.name,a.department from college as a inner join students as b on (a.s_id = b.id) where (a.department = 'CSE' AND b.active = 1) i just want to write this query in django -
Django class based view filter choices
I need to filter the choices of a CharField in a CreateView, however, I can't filter in the form, because the form is also used for several other views, which need different initial choices. (For the filtering, I would technically have to query the possible field choices, but that didn't work either, so I just printed them into the view (any input on that would be appreciated, too), so right now, I have a variable called valid that holds the choices I want the field to have). Afaik, the right place for this would be the view's get_initial()(?). def get_initial(self): initial = super(MailCreate, self).get_initial() valid = something initial["usage"].queryset = valid return initial This is my CharField: usage = models.CharField(_('Usage'), choices=usages.items(), null=True, blank=True, max_length=200) I tried something like form.fields['usage'].queryset = valid, but it failed, I'm guessing because it's not a ChoiceField, but a CharField. I also tried initial['usage'].choices = valid and self.fields['usage'].choices = valid, but they failed, too, supposedly because they can only be used like that in some other place. I also tried looking at the official documentation, but I only found the description for what get_initial() does... Right now I am running out of ideas... -
Django Image Compression inside Model
I'm working on a django project in which i'm trying to resize & compress an image before saving. Here's my code, # Model class Content(models.Model): data = models.TextField() image = models.ImageField(upload_to='images/') # Compression & Resizing def save(self, *args, **kwargs): if self.image: img = Image.open(self.image) resize = img.resize((240, 240), Image.ANTIALIAS) new_image = BytesIO() resize.save(new_image, format=img.format, quality=80, save=False) temp_name = os.path.split(self.image.name)[1] self.image.save(temp_name, content=ContentFile(new_image.getvalue()), save=False) super(Content, self).save(*args, **kwargs) Resizing & Compression is working fine. But the problem is that, it's re-naming the images in a wrong way. For example, I saved an image originally named, abc.png, after the compression & resizing, it re-named it as abc_SNNYByd_tYB56u7_d23fUHs_qHICQxb_MFuW3DN_Y6JAvNE_SDzC_s20OMui.png. Someone suggested me to delete the original image before saving the new one, but I don't know how to do it inside the model? Or is there any other way to fix this problem? Thank You . . . -
Dropdowns Django with dynamic list
I am trying to give a drop-down menu from Django, from a dynamic list of data columns. For example, every time I run the model I generate column names and these names shall appear on the drop-down menu. Previously, I have used a text box from Django which looks something like this: Forms.py from django import forms class LinearForm(forms.Form): Column_name1 = forms.CharField() I have seen forms.ModelMultipleChoiceField() and forms.ChoiceField() which takes choices as a list of values, since I need to import dynamic list is generated from my Views.py and my dropbox must generate from Forms.py. How do I proceed with this? -
Axios not sending as post method
I'm trying to get a simple post form setup in React with Axios, but it doesn't seem to be sending as a post request for some reason, so Django keeps throwing a 405 error. React: handleSubmit(e) { console.log('Form state: ', this.state); e.preventDefault(); const username = this.state.username; const password = this.state.password; const formData = { username: username, password: password, } // Django backend currently running on localhost:8000 axios('http://localhost:8000/login', { method: 'POST', data: formData, }).then(res=> { console.log('res', res); console.log('res.data', res.data); } ) } Django method: @require_http_methods(['POST']) def login(request): ... -
pass information about object when link is clicked
am creating a website that allows user to follow certain stocks and view articles related to what they follow.I want them to be able to clink a link to all "news about stock X". views.py: stocks_user_follows = request.user.profile.followed_stocks.all() return render( request, 'core/index.html', {'stocks_user_follows':stocks_user_follows}) html: {% for stock in stocks_user_follows %} ... <a href="#" >All {{ stock }} News</a> {% endfor %} how do I pass stock to a view when the link is clicked? -
having more control over the models fields in the template
i have a major doubt. i have a model and i want to display the item from the model in a loop. eg:i have like 1000 types of cheese which i want to show in the template either by thumbnails or any other way.. so i use a loop and show the item and i can also show the fields individually, but how can i have more control on the data i show in context of styling.. my designer gave me a design where some thumbnails are large and some medium and some small, the positioning of the items are irregular.. when the data is dynamic i can use only one style and the entire things follows as its in a loop.. i can split the models and try those things. but is there a another way where i can have more control over the model items????? -
Post Request not available inside get_queryset function inside ListView
In ListView, I can easily use def post(self, request) method to make a post request from a list view. But I want to make the post request from def get_queryset(self) which I am not yet able to do. When I try to do it it shows "method 405 not allowed!" even though post method is allowed through http_method_names. class ZonListView(SearchMixin, SingleTableMixin, ListView): template_name = 'cadmin/list.html' model = Zon table_class = ZonTable search_fields = { 'title': 'icontains', 'description': 'icontains', } def post(self, request): # ***** this one works! ****** try: toggle_status = request.POST.get('toggle-status') pk = int(request.POST.get('pk')) .... return HttpResponseRedirect(reverse('cadmin:zon_list')) def get_queryset(self): qs = super(ZonListView, self).get_queryset() if self.request.POST: #***** Not working. 405 Error *****# try: toggle_status = self.request.POST.get('toggle-status') pk = int(self.request.POST.get('pk')) ...... if self.request.GET: try: status = self.request.GET.get('status') qs = qs.filter(status=status) except Exception: pass return qs.distinct() def get_context_data(self, **kwargs): ....