Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display image in Django admin - Many to many inline admin view
I have the following models: class AModel(BaseModel): a_id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) a_images = models.ManyToManyField(BModel) class BModel(BaseModel): images = ImageField(upload_to='/') I want to display the BModel images in AModel admin form. I am able to do that using class BModelInline(admin.TabularInline): model = AModel.a_images.through How can I display the image preview in the tabular format in AModel form admin? I already tried overriding formfields, but it doeesn't seem to work. formfield_overrides = { models.ImageField: {'widget': AdminImageWidget}} class AdminImageWidget(AdminFileWidget): def render(self, name, value, attrs=None): output = [] if value and getattr(value, "url", None): image_url = value.url file_name=str(value) output.append(u' <a href="%s" target="_blank"><img src="%s" alt="%s" width="150px"/></a> ' % \ (image_url, image_url, file_name)) output.append(super(AdminFileWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) -
Does importing specific class from file instead of full file matters?
Most of the tutorials and books about Django or Flask import specific classes from files instead of importing the whole file. For example, importing DataRequiered validator from wrtforms.validators is done with from wtforms import validators instead of importing it via import wtforms.validators as valids and then accessing DataRequiered with valids.DataRequiered. My question is: Is there an reason for this ? I thought to something like avoiding the loading a whole module for computation/memory optimization (is it really relevant?) ? Or is it simply to make the code more readable ? -
Django ORM: create ranking based on related model count
I have 2 models in my database: Movie and Comment (comment having foreign key pointing to Movie). from django.db import models class Movie(models.Model): title = models.CharField(max_length=120, blank=False, unique=True) class Comment(models.Model): movie = models.ForeignKey(movie_models.Movie, null=False, on_delete=models.CASCADE) body = models.TextField(blank=True) What I am trying to do is create a ranking of Movies where the position is determined by the number of related Comments. I can annotate number of comments and order by this number: from django.db.models import Count qs = Movie.objects.annotate(total_comments=Count('comment')).order_by('-total_comments') This gives me queryset in correct order but I would like to do one more thing - annotate the 'rank' to each row. So my question is: how can I annotate 'rank' to each row of the result? Note that it is required for movies with the same amount of comments to have the same rank. | movie_title | total_comments | rank | |--------------|----------------|------| | mov1 | 10 | 1 | | mov2 | 5 | 2 | | mov3 | 5 | 2 | | mov4 | 3 | 3 | I tried to use window functions, as some of the examples seemed legit for me: from django.db.models import F, Window dense_rank = Window( expression=DenseRank(), partition_by=F('total_comments'), order_by=F('total_comments').asc() ) qs = … -
how to Add django admin as foreign key in django?
this is my class in models.py in django from django.contrib import admin class Post: post_content = models.TextField("Text", max_length=150) fkAdmin = models.ForeignKey(admin, on_delete=models.CASCADE, null=True) -
Filtering on FK with kwargs Django
Assume that I have 2 Models: class Foo(models.Model): item = models.ForeignKey(ItemClass, on_delete=models.CASCADE) ... and class ItemClass(models.Model): item_name = models.CharField(max_length = 100, blank=False) ... when I am trying to make a query with kwargs like filters = {} filters['item__item_name__contains'] = request.POST['search-box'] ... objects = Foo.objects.all().filter(**filters) it returns an empty result. Instead of using kwargs if I use this query objects = Foo.objects.all().filter(item__item_name__contains = request.POST['search-box']) I can get he true result What is the difference between these 2 queries and how can I make my query work with kwargs ? -
django uploads files very well but gives 404 in development
I changed the upload_to ImageField argument to a dynamic one and also tried to resize an image upon upload by overiding save function. I created a upload_to function and it's working fine during upload, but django cannot locate the file afterwards. it display 404 when trying to get the file. Upload_to Function def get_picture_url(instance, filename): DIR = os.path.join(settings.MEDIA_ROOT, "students_passports/") try: all_stud_profile = StudentUserProfile.objects.all().last() except StudentUserProfile.DoesNotExist: all_stud_profile = [] if not all_stud_profile: first_folder = os.path.join(DIR, '%s/%s/') % ("0", "000") os.makedirs(first_folder, exist_ok=True) return os.path.join(first_folder, filename) elif all_stud_profile: first_folder = os.path.join(DIR, '%s/%s/') % ("0", "000") if int(''.join(all_stud_profile.student_ID.split("-"))) == 1: os.makedirs(first_folder, exist_ok=True) get_folder = os.path.join(DIR, "%s/%s/") % (str(all_stud_profile.student_ID)[:1], \ str(all_stud_profile.student_ID[2:5])) file_1000 = len([name for name in os.listdir(get_folder) if os.path.isfile(os.path.join(get_folder, name))]) if file_1000 == 999 and int(all_stud_profile[2:5]) == 999: id_1 = str(int(str(all_stud_profile.student_ID[:1])) + 1) image_folder = os.path.join(DIR, "%s/%s/") % (str(all_stud_profile.student_ID)[:1], \ id_1) os.makedirs(image_folder, exist_ok=True) return os.path.join(DIR, "{}/{}/{}.{}").format(str(all_stud_profile.student_ID)[:1], \ id_1, all_stud_profile.student_ID, "jpg") elif file_1000 == 999 and int(all_stud_profile[2:5]) < 999: id_2_5 = str(int(str(all_stud_profile.student_ID[2:5])) + 1).zfill(3) image_folder = os.path.join(DIR, "%s/%s/") % (str(all_stud_profile.student_ID)[:1], \ id_2_5) os.makedirs(image_folder, exist_ok=True) return os.path.join(DIR, "{}/{}/{}.{}").format(str(all_stud_profile.student_ID)[:1], \ id_2_5, all_stud_profile.student_ID, "jpg") else: image_folder = os.path.join(DIR, "%s/%s/") % (str(all_stud_profile.student_ID)[:1], \ str(all_stud_profile.student_ID[2:5])) os.makedirs(image_folder, exist_ok=True) return os.path.join(DIR, "{}/{}/{}.{}").format( str(all_stud_profile.student_ID)[:1], \ str(all_stud_profile.student_ID)[2:5], \ all_stud_profile.student_ID, \ "jpg") And this is … -
django-wkhtmltopdf on IIS: [WinError 6] The handle is invalid
this is my very first question, so please forgive me, if I forgot something to mention or there's something wrong with it :) I set up a python(3.5.3)-django(2.1.5) -project on IIS(10)-Windows Server. Everything works great. Problem Only wkhtmltopdf(0.12.5) has a strange behavior. When I run it on localhost the command prompt gives me Loading pages (1/6) Counting pages (2/6) Resolving links (4/6) Loading headers and footers (5/6) Printing pages (6/6) Done and I can find the generated .pdf-file in my downloads folder as expected. When I change ALLOWED_HOSTS to the Server's IP and I call the url to generate a pdf it says there is a OSError at /pdf/ [WinError 6] The handle is invalid with the Traceback: File "C:\my_project\myenv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\my_project\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response 156. response = self.process_exception_by_middleware(e, request) File "C:\my_project\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response 154. response = response.render() File "C:\my_project\myenv\lib\site-packages\django\template\response.py" in render 106. self.content = self.rendered_content File "C:\my_project\myenv\lib\site-packages\wkhtmltopdf\views.py" in rendered_content 80. cover_template=self.resolve_template(self.cover_template) File "C:\my_project\myenv\lib\site-packages\wkhtmltopdf\utils.py" in render_pdf_from_template 237. cover_filename=cover.filename if cover else None) File "C:\my_project\myenv\lib\site-packages\wkhtmltopdf\utils.py" in convert_to_pdf 166. return wkhtmltopdf(pages=pages, **cmd_options) File "C:\my_project\myenv\lib\site-packages\wkhtmltopdf\utils.py" in wkhtmltopdf 147. return check_output(ck_args, **ck_kwargs) File "C:\Program Files\Python35\lib\subprocess.py" in check_output 316. **kwargs).stdout File "C:\Program Files\Python35\lib\subprocess.py" in run 383. with Popen(*popenargs, **kwargs) as … -
Python subprocess with double quote and whitespace for django command
I am using this node plugin to run django management commands. If I execute the command directly, it works: sls wsgi manage local -c "check --list-tags" If I call a python script that calls it as a subprocess, It cannot find the command: import subprocess proc = subprocess.Popen(['sls', 'wsgi', 'manage', 'local', '-c', '"check --list-tags"']) (out, err) = proc.communicate() "Traceback (most recent call last):\n File \"/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py\", line 102, in call_command\n app_name = get_commands()[command_name]\nKeyError: 'check --list-tags'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"./wsgi_handl er.py\", line 89, in handler\n management.call_command(*shlex.split(meta.get(\"data\", \"\")))\n File \"/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py\", line 104, in call_command\n raise CommandError(\"Unknown command: %r\" % command_name)\ndjango.core.management.base.CommandError: Unknown command: 'check --list-tags'\n " If I do a command that does not contain any whitespace it works, such as: subprocess.Popen(['sls', 'wsgi', 'manage', 'local', '-c', '"makemigrations"']) -
How to edit forms generated by FormSet that is generated by modelformset_factory?
so I have this formset that I'm using in my template : def manage_authors(request): AuthorFormSet = modelformset_factory(Produkt, fields=('nazwa','ilosc','minimum',),extra=0) if request.method == 'POST': formset = AuthorFormSet(request.POST or None, request.FILES or None) if formset.is_valid(): formset.save() else: formset = AuthorFormSet() return render(request, 'manage_authors.html', {'formset': formset}) And I wish I could like to edit properties of fields that are generated in the html page, change max length, size, label. Now I'm just getting default fields, I know how to do it for predefined forms but what about this situation? -
Django:How to perform a query with settings.AUTH_USER_MODEL?
This is my model: class Company(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True) name = models.CharField(max_length=50,blank=False) auditor = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='main_auditor',blank=True) I want to perform a query which will display the list of company to which a particular auditor is associated with... How to do query with settings.AUTH_USER_MODEL in django? Any idea anyone? Please help -
Django list data from dfiferent models in List View with correct ordering
Heys guys.. I am making a Django project which is a simple clone of Twitter.. Got the idea from Justin Mitchell's Udemy course.. So i implemented a Tweet model and a Retweet model which has ForeignKey to the original Tweet and the User.. The thing is that in the homepage i want both the Tweets and Retweets to show and in the order they were created.. I am using Django Rest Framework for the CRUD functionality of Tweet using ModelViewSet Any idea on how i achieve that using Rest Framework or if that isn't possible could you please give me some other idea.. Thank you in advance.. models.py class Tweet(models.Model): content = models.CharField(max_length=140) user = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: ordering = "-created_on", "content", "user", def __str__(self): return self.content def get_absolute_url(self): return reverse("tweet_api:tweet-detail", args=[self.id]) class Retweet(models.Model): tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE, related_name="retweet") user = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = "-created_on", "user", def __str__(self): return self.tweet.content serializers.py class TweetSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) created_on = serializers.SerializerMethodField() date_display = serializers.SerializerMethodField() class Meta: model = models.Tweet fields = "id", "content", "created_on", "date_display", "user", def get_created_on(self, obj): return obj.created_on.strftime("%I:%M %p - %d %b %Y") def get_date_display(self, obj): … -
Django output 1 field from a model within another table
I have 2 models - class InsName(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, verbose_name = "Insurer/Broker") alias = models.TextField(max_length=80, blank=True) def __str__(self): return f'{self.name}, {self.alias}' def get_absolute_url(self): return reverse('insurer-detail', args=[str(self.id)]) class Development(models.Model): id = models.AutoField(primary_key=True) logno = models.CharField(validators=[RegexValidator(regex='^(SCTASK|CDLI)[0-9]{7}', message='Please enter a valid log number', code='nomatch')], max_length=13) insurer = models.ForeignKey(InsName, on_delete=models.SET_NULL, null=True, blank=False, verbose_name="Client") policy = models.ManyToManyField(Policy, blank=True) on my template I am outputting a list of Developments but where insurer is output I just want the name part to output. I need to retain the alias as it is used in other templates that also calls in InsName. I thought I could use a substring before comma method in the template but I cant see that such a thing exists. Is this possible? If not any tips on how I can achieve this is greatly appreciated! -
POST data from python to django
I am beginner in Django. I am trying to POST a json data from python to django site. import requests import json url = "http://127.0.0.1:8000/esave/search/" data = {'name':'bruce', 'drink':'cola', 'age':19} r=requests.post(url, data=data) got_response = r.text print(got_response) This is what I got after some searches. and on my view function I got this code, but I am not sure how far it is good. def search(request): if request.method == 'POST': data=json.loads(request.body.decode("utf-8")) name = data['name'] #doing something like create and update database #Dont know what to return, just returning the name for verification if nothing return I got error return HttpResponse("name") when I run server in my local host and run the python code to post data, this is what I got. March 20, 2019 - 15:53:28 Django version 2.1.5, using settings 'jazztest.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Forbidden (CSRF cookie not set.): /esave/search/ [20/Mar/2019 15:53:43] "POST /esave/search/ HTTP/1.1" 403 2868 and in my python terminal I got this. $ python dumper.py <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body … -
How to design the architecture of several Python applications interacting asynchronously?
I have the following situation: A - Django web application (public) B - Web application written mostly in PHP (front-end + back-end) C - Back-end Python server (used for data management) D - Back-end Python server (used for machine learning tasks) The application A listen the MySql database called DB01, while the application C listen the MySql database called DB02. All these applications are deployed on AWS. At present these applications interact in the following ways: B send a messages to C, C process the message and reply to B. or B send a message to C, C send a message to D, D reply to C and C reply to B. The next challenge is to design a new pipeline: A send a message to D, (this message require a lot of time to be COMPLETELY processed and it requires data from the database DB02) so D will calculate partial results and send back to A (in this way using Javascript on Django front-end the user could visualise a page that automatically updates it's content as soon as new data are pushed to it). The question is: "How could be designed this pipeline? Are there any frameworks in Python … -
Can I retrieve the HTML element in a django form?
I have a ModelForm, MyForm. Help me write a method that returns html elements for each field present in the form. class MyForm(forms.ModelForm): priority = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control','data-role':'select'}), choices=((1,1), (2,2), (3,3), (4,4)), required=True, initial='3', label=_('Priority'), help_text=_("Please select a priority carefully. If unsure, leave it as '3'."), ) due_date = forms.DateTimeField( widget=forms.TextInput(attrs={'class': 'form-control','data-role':'datepicker'}), required=False, ) def getFormHtml(self): #need to return the string containing the html tag elements for each element in current form. -
Django: Replacing comma with dot as a decimal separator while keeping localization
I have built a multi-lingual website with django. My problem is that when the user changes localization all floats turn from dot-based to comma-based (e.g. the "4.2" become "4,2"). I have created a template filter that replaces comma separators with dots in order to handle this situation but I think it is not the best solution as there are many places that use floats. Can I do that on the back-end while keeping all other localization settings? -
How to perform ajax with django?
Can anyone suggest me a better tutorial or some link of performing ajax request with django. I am very much new in python django it will help me in my learning process. Thank you -
DRF-XML how to add pre-fix and render in specific format
I'm trying to create a link which will render feed from model through serializer for facebook dynamic add. I'm using Django REST Framework for XML rendering, But I'm getting output like <root> <list-item> <id>286</id> <title>Dog Bowl In Blue</title> <description> Solid plastic Dog Bowl in marine blue colo </description> <price>400.00</price> <category_name/> <cook>Mrs John</cook> <thumbnail> https://ee5b36248ba0_thumb.jpg </thumbnail> <is_always_available>False</is_always_available> <preparation_time>6.0</preparation_time> </list-item> </root> but I need to Render like this <?xml version="1.0"?> <rss xmlns:g="http://base.google.com/ns/1.0" version="2.0"> <channel> <title>Test Store</title> <link>http://www.example.com</link> <description>An example item from the feed</description> <item> <g:id>DB_1</g:id> <g:title>Dog Bowl In Blue</g:title> <g:description>Solid plastic Dog Bowl in marine blue color</g:description> <g:link>http://www.example.com/bowls/db-1.html</g:link> <g:image_link>http://images.example.com/DB_1.png</g:image_link> <g:brand>Example</g:brand> <g:condition>new</g:condition> <g:availability>in stock</g:availability> <g:price>9.99 GBP</g:price> <g:shipping> <g:country>UK</g:country> <g:service>Standard</g:service> <g:price>4.95 GBP</g:price> </g:shipping> <g:google_product_category>Animals &gt; Pet Supplies</g:google_product_category> <g:custom_label_0>Made in Waterford, IE</g:custom_label_0> </item> </channel> </rss> Can anyone help me with that ? -
Filtering date in Django Rest Framework (range between start and end date)
models.py date_created = models.DateTimeField() In frontend, I have two params like: date_created_start and date_created_end. What is the best approach to filter date_created and get objects created between date_created_start and date_created_end? -
Django testcase to test models failing
I am writing a test case for my model to test the __str__ but apparently it is failing. Here is my tests.py: from todoapp.models import User, Task from django.test import TestCase class UserModelTest(TestCase): def setUp(self): self.user = User.objects.create( first_name='john', last_name='doe', email='abc@example.com', password='johndoe') def test_string_representation(self): object_name = User.objects.get(id=50) expected_object_name = object_name.email self.assertEqual(expected_object_name, str(object_name)) Here is my models.py: class User(AbstractUser): username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email P.S.: A user with id=50 already exists -
deploying django application with web server, app server and db server
I this is my first django app I am deploying. I am looking at deploying the django app with Gunicorn, Nginx and PostgreSQL. There are three separate servers(Linux). I have installed Nginx on webserver, gunicorn on app and postgres on the db server. I should put my project on app-server? What should i do next. -
Django - 'User' object has no attribute 'session_set'
I want to add a Sessions tabs to my Django project: navbar.html <li><a href="{% url 'user_sessions:session_list' %}">Sessions</a></li> But i keep getting the following error: 'User' object has no attribute 'session_set''User' object has no attribute 'session_set' Exception Location: C:\Users\User\lib\site-packages\django\utils\functional.py in inner, line 214 I don't know where this error comes from, i did not find any other reference online, can anyone help me? Here is the login view that i'm using: https://github.com/Bouke/django-two-factor-auth/blob/master/two_factor/views/core.py -
Django JWT Auth - filtering response for particular user
I’m implementing JWT authentication in my Django project and at the moment I’m stuck in a part where I’d like to filter response data by my JWT. I’d like to get particular data referring to authenticated user in my Django view. How can I get this filtered data? Here’s example for my Settings view. Views.py Class SettingsViewSet(viewsets.ModelViewSet): # here I'd like to decode my JWT token # and filter the response data for particular user queryset = Settings.objects.all() serializer_class = SettingsSerializer urls.py # ... router.register(r'api/settings', SettingsViewSet) # ... urlpatterns = [ # ... url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), # ... ] Serializers.py class SettingsSerializer(serializers.ModelSerializer): class Meta: model = Settings fields = ('id', 'name', 'value', 'description', 'office') settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } Here’s a curl command which I use to get response from server: curl -H ‘Content-Type: application/json’ http://127.0.0.1:8000/api/settings/ -H ‘Authorization: Bearer <Here goes JWT token for particular user>’ In response I get all the settings for all users. I’d like to get data only for the authenticated one. -
Get public address of django application
I have a django application, listening to 127.0.0.1, and reachable via nginx. What are my options in order to get information about the public IP (the ones clients are using) from within the django application? Currently I am doing: def get_local_ip(request): """Return the local IP (where the application is listening to)""" # TODO: this should be the server IP as seen by the UI (the public IP, where nginx is listening) return request.META.get('HTTP_HOST') if request else None But this returns 127.0.0.1. -
How to pass multiple parameters from 'if loop' to 'for loop' in Django?
I have the following code : {% if sr %} {% for lap in filter.qs|slice:":20" %} <tr > <td class="col-sm-3"> <div > <div class="product-image-wrapper"> <div class="single-products"> <div class="productinfo text-center"> <img src="{{ lap.product_image }}" alt="" /> </div> </div> </div> </div> </td> <td class="col-sm-3"> <h5><a href="{{ lap.product_url }}">{{ lap.product_name }}</a> </h5> <br> {# <h5 class="btn btn-outline-secondary"><a href="{{ k.product_url }}" >See Details</a> </h5>#} <a href="{{ lap.product_url }}" class="btn btn-secondary" role="button" aria-pressed="true" style="background-color: #3e4e6f; color: white">See Details</a> </td> <td class="col-sm-3">{{ lap.product_price }} &#2547;</td> <td class="col-sm-3">{{ lap.vendor_name }}</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} {% endif %} Where I want to pass the parameter sr from if loop to the next for loop along the existing filter.qs|slice:":20" parameter in the following part. {% if sr %} {% for lap in filter.qs|slice:":20" %} How can I pass it? Please help.