Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do display a form and the result of the form in a table format on the same page in django?
Ive spent the past week looking for help with this and i cannot find any resources to help, if someone can link me to a resource or anything that would be great. -
How to use django graph variable in javascript
Function for graph : def graph_on_surf_one_segment(result): fig = plt.figure() plt.plot(draw_X,draw_Y) plt.title("On surface movement") plt.xlabel("x") plt.ylabel("y") imgdata = StringIO() fig.savefig(imgdata, format='svg') imgdata.seek(0) data = imgdata.getvalue() return data views.py graph = graph_on_surf_one_segment(result) graph_2 = graph_on_surf_one_segment(result_zero) return render(request, "segments_to_download.html", {"result":result,"graph":graph,"graph_2":graph_2}) In html is classic {{ graph|safe }}. This will display a graph. I need to display only one graph and below the graph will be the button, that will switch between these two or more graphs, if the 1st graph is displayed, after clicking the second one will be displayed. I cant load graphs into variables and then compare them. If load graph into variable like this var a = {{graph}}, it gives an error. It is possible to do this ? -
How do I separate my templates correctly in Django?
I'm in doubt as to how I can make my templates in Django. I created three apps on my django: User Posts Index And each app I create a folder called "templates" and there I make the templates for these pages, but there is a problem! Whenever I put the same page in my view that I created in another template, all the repeated content appears there, is there any way to make this not happen? -
Django rest framework, serializers and data
So, I am getting data from a front and. Let's say it's a department name: "COINS" and key: "coins". I am defining a method in my serializer class, just to see what data actually is. def validate(self, data): print(data) return data I have tried getting data from the context, but I only get the key: "coins". Name is not present in data, BUUUT it's present in the validated_data Have spent all day figuring it out. How does they kwarg is present in validate_data, but not in data. Thanks in advance -
Heroku error after deploying (No module named '_tkinter')
I have an web app deployed on heroku (using Python), I am using now Pyppeteer to make some automatic jobs in a web site. After deploying I am getting this issue: Request Method: GET 3.1.4 ModuleNotFoundError No module named '_tkinter' /app/.heroku/python/lib/python3.6/tkinter/init.py, line 36, in /app/.heroku/python/bin/python 3.6.12 ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Anyone faced this issue? I already used the buildpacks for chrome and puppeteer but getting same error. Also have tried: import matplotlib matplotlib.use("Agg") Thanks!! -
Importing Signing and Verifying key for JWT RSA algorithm in Django rest framework
I'm working on a django rest api application that uses JWTAuthentication using django-rest-framework-simplejwt. Since the RSA algorithm is in use, the signing and verifying key needs to be set. The implementation below worked for me. SIMPLE_JWT = { 'SIGNING_KEY': open('jwtRS256.key').read() if os.path.isfile('./jwtRS256.key') else None, 'VERIFYING_KEY': open('jwtRS256.key.pub').read() if os.path.isfile('./jwtRS256.key.pub') else None, } After upgrading to django 3 and running py -Wa manage.py test. This are some of the warning messages being displayed. D:\path\to\settings.py:398: ResourceWarning: unclosed file <_io.TextIOWrapper name='jwtRS256.key' mode='r' encoding='cp1252'> 'SIGNING_KEY': open('jwtRS256.key').read() if os.path.isfile('./jwtRS256.key') else None, ResourceWarning: Enable tracemalloc to get the object allocation traceback D:\path\to\\settings.py:399: ResourceWarning: unclosed file <_io.TextIOWrapper name='jwtRS256.key.pub' mode='r' encoding='cp1252'> 'VERIFYING_KEY': open('jwtRS256.key.pub').read() if os.path.isfile('./jwtRS256.key.pub') else None, ResourceWarning: Enable tracemalloc to get the object allocation traceback I tried an alternative to solve this issue but it seems to break the app when authenticating users. This is the attempted solution. def get_file(file_url): if os.path.isfile(file_url): with open(file_url) as f: return f return None SIMPLE_JWT = { 'SIGNING_KEY': get_file('./jwtRS256.key'), 'VERIFYING_KEY': get_file('./jwtRS256.key.pub') } This doesn't work when trying to log in and returns a 500 with TypeError: Expecting a PEM-formatted key. -
Model with a lot of fields with a clearly visible pattern: is a loop possible when declaring model fields?
Django 3.1.6 class RasterImage(models.Model): img_original = models.ImageField(upload_to=_raster_img_upload_to, verbose_name=" img_original", ) img_100_100_webp_1x = models.ImageField(upload_to=_raster_img_upload_to, verbose_name=" img_100_100_webp_1x", null=True, blank=True, width_field="img_100_100_webp_1x_width", height_field="img_100_100_webp_1x_height") img_100_100_webp_1x_width = models.PositiveIntegerField() img_100_100_webp_1x_height = models.PositiveIntegerField() img_100_100_1x = models.ImageField(upload_to=_raster_img_upload_to, verbose_name=" img_100_100_1x", null=True, blank=True, width_field="img_100_100_2x_width", height_field="img_100_100_2x_height",) img_100_100_2x_width = models.PositiveIntegerField() img_100_100_2x_height = models.PositiveIntegerField() class Meta: verbose_name = _("Raster image") verbose_name_plural = _("Raster images") For each picture I'll store a hundred of image files. The pattern of each field is clearl: width, height, device pixel ratio, webp or not. Then fields to keep width and height. The question Is it possible to organize such a model field set in a loop somehow? P.S.: Don't persuade me to use django-imagekit or something. I'll keep process images locally. -
Django REST Framework: POST view for ManyToManyField
User has to be able to create new chat and add there participants. For new chat I need new chat's ID (which has to be generated automatically) and chat participants (who will be chosen out of other users in database by the user who creates a chat). Here is the chat model: class Chat(models.Model): id = models.CharField(_('id'), primary_key=True, default=hex_uuid, editable=False, max_length=32) chat_participants = models.ManyToManyField(User, blank=True) class Meta: db_table = 'chat' verbose_name_plural = 'chats' And here is the serializer: class ChatSerializer(serializers.ModelSerializer): chat_participants = ChatParticipantsSerializer(many=True, read_only=True) class Meta: model = Chat fields = '__all__' PS. ChatParticipantsSerializer contains name and last name of participants (it uses a customized User model). Here is the view (it is incorrect, but I leave it here for any cases. Generic views don't help me, so I decided to write it from the scratch): @api_view(['POST']) @permission_classes((IsAuthenticated,)) def create_or_update_chat(request): new_chat = Chat.objects.create() The only field I need here is chat_participants for user's choice. After choosing participants, user just should click the 'POST' button (which is prepared by Django REST Framework itself for 'POST' requests) and that's all. But unfortunately I couldn't find the proper post where this problem is properly solved. -
Django Form css not displaying flex properties
I'm setting up a comment form for a blog with django. I want to have the submit form on the left and the already existing comments on the right, but I can only get them to display underneath each other. I've been trying with flexbox display: row Here is my code: entry_detail.html <div class="comment_section"> <div class="left"> <h2>What do you think?</h2> <form method="POST" class="comment_form"> {{ comment_form.as_p }} {% csrf_token %} <a href="{% url 'entry_detail' pk=entry.pk %}" <div> <input type="submit" value="Add my thoughts" class="form_btn"> </div> </form> </div> <div class="right"> {% for comment in entry.comments.all %} <div class="comment_box"> <p> {{ comment.name }} says: </p> <p class="comment_text"> {{ comment.text|linebreaks }} </p> <p class="detail_date comm"> {{ comment.date_posted }} </p> </div> {% empty %} <h2 class="background">Be the first to share your thoughts!</h2> {% endfor %} </div> </div> css: .comment_section { border-top: 1px solid #8f666c; margin-top: 2%; display: flex; flex-direction: row; width: 100%; border: 1px solid green; } .left, .right { display: flex; flex-direction: column; width: 45%; border: 1px solid blue; } .right { background-color: transparent; height: inherit; align-self: top; border: 1px solid red; } The rest of my flexbox css works, so I'm guessing the problem lies somewhere with the form? -
Modifying Available and CHosen Choices For ManyToMany Field With Horizontal Filter
Within the Model Admin, is it possible to control what's shown in a ManyToManyField horizontal_filter widget, in both the available and chosen fields? For instance, I have a County model and a Territory model, and want to hide a County if it's already assigned to a Territory. The problem with the below is that selected County objects will be hidden in both the "Available" and "Chosen" widget with horizontal_filter. Is it possible to only hide them in the "Available" column? class TerritoryAdmin(admin.ModelAdmin): filter_horizontal = ('counties',) ordering = ('territory_name', ) # remove counties already assigned to a territory def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == 'counties': assigned = Territory.objects.all( ).values_list('counties__fips_code', flat=True) kwargs["queryset"] = County.objects.exclude(fips_code__in=assigned) return super().formfield_for_manytomany(db_field, request, **kwargs) -
how to fix (CSRF token missing or incorrect ) react/redux + django
i'm developing authentication [login_page localhost:8000/login/][1] i tried to login but my state is LOGIN_FAIL [LOGIN_FAIL][2] I've checked it's working on postman and I know my template should have this code. <form method="post">{% csrf_token %} But, If I paste this code into Login.js, it makes an error. Like this Login.js: const Login = ({ login }) => { const [formData, setFormData] = useState({ email: '', password: '' }); const { email , password } = formData; const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = e => { e.preventDefault(); login(email, password); }; // Is the user authenticated // Redirect them to the home page return ( <form method="post">{% csrf_token %} <div className="container mt-5"> {/* <h1>회원가입</h1> <p>이메일로 회원가입</p> */} <form onSubmit={e => onSubmit(e)}> <div className="form-group"> <input className="form-control" type="email" placeholder="이메일" name="email" value={email} onChange={e => onChange(e)} required /> </div> <div className="form-group"> <input className="form-control" type="password" placeholder="비밀번호" name="password" value={password} onChange={e => onChange(e)} minLength='6' required /> </div> <button className='btn btn-primary' type='submit'>login</button> </form> <p className='mt-3'> <Link to='/signup'>signin</Link> </p> <p className='mt-3'> <Link to='/reset_password'>find password</Link> </p> </div> </form> ); }; error code: Forbidden (CSRF token missing or incorrect.): /http//localhost:8000/auth/jwt/create/ [04/Feb/2021 01:33:26] "POST /http//localhost:8000/auth/jwt/create/ HTTP/1.1" 403 2513 authentication trigger code: export const login = (email, password) => … -
Can I use file returned by urllib.request.urlopen as reqular file(file opened with open file)?
below is my Django code import urllib.request as request ... bookmark, created = Bookmark.objects.get_or_create(title=title, url=url, owner=owner) icon = request.urlopen("https://saved.io/assets/img/favicon.ico") bookmark.fav_icon = icon #fav_icon is ImageField bookmark.save() I want to assign the icon retrieved by urlliblib.request module to bookmark.fav_icon which django ImageField -
How to change datetype timestamp without timezone to timestamp with timezone in the Django
models.py class sample(models.Model) a = models.DateTimeField(blank=true, default=true) POSTGRES sample Table a column datetype is a timestamp without timezone I need to change 'a' column datetype timestamp without timezone to timestamp with timezone using Django model. how to achieve this scenario. -
How to redirect to a custom admin page by using a custom admin field in django admin panel
Having my PlugAdmin class class PlugAdmin(admin.ModelAdmin): list_display = (...'custom_link') in admin.py among the other fields of my model I have defined the custom_link field as below: def custom_link(self, obj): info = (obj._meta.app_label, obj._meta.model_name) return mark_safe('<a class="custom" href="%s">Advanced Config Page</a>' % reverse('admin:%s/%s/advanced-config' % info, args=(obj.pk,))) By pressing the custom_link my aim is to redirect to advanced_config_view which is a custom admin page that was defined properly(both in admin.site.urls and as view: def get_urls(self): urls = super().get_urls() my_urls = [ path('<uuid:plug_id>/advanced-config/', self.admin_site.admin_view(self.advanced_config_view), name = "advanced_config"), ] return my_urls + urls def advanced_config_view(self, request, plug_id): plug = Plug.objects.get(id = plug_id) context = dict( # Include common variables for rendering the admin template. self.admin_site.each_context(request), plug = plug, ) return TemplateResponse(request, "custom_admin/advanced_config.html", context) My page can not load and i got the error from Traceback : Template error: In template /home/giorgos/.local/share/virtualenvs/backend-tSqKtrJ_/lib/python3.7/site-packages/django/contrib/admin/templates/admin/base.html, error at line 65 Reverse for 'stations/plug/advanced-config' not found. 'stations/plug/advanced-config' is not a valid view function or pattern name. 55 : <a href="{% url 'admin:logout' %}">{% translate 'Log out' %}</a> 56 : {% endblock %} 57 : </div> 58 : {% endif %} 59 : {% endblock %} 60 : {% block nav-global %}{% endblock %} 61 : </div> 62 : <!-- END Header … -
Retrieving data with time for multiple users
So I'm making a Django project and the idea is to make a quiz Question shows up, you have four answers you press one and then based on speed and if you got the right answer you get some points. So I made that using ajax and setTimeout and interval functions and a hidden input field for score that's updated every 0.1 seconds (or 0.01 but it doesn't really matter). So the simplified form part looks something like this: <form> <input name="answer1" type="submit" value="Answer 1 Text"> .... # 4 answers <input name="score" type="hidden" value="10"> # The score is based on time left </form> Now I'm not sure how vulnerable that is (I'm guessing it's not very secure to do it like that (especially the score part) and also if for some reason tab is not focused it does intervals and timers once every second (I can make that work but it doesn't really fix the problem)). Now I'm not sure if it would be best to continue working on this solution or use something like channels to receive answers from users (there would be many users answering at the same time so not sure if going the channels route would … -
Django disable Foreing check in sqllitle for development?
Is there a way to disable foreign keys when using sqllitle as database? Loaddata would often fail because of foreign keys, and disabling it would make all work, in mysql I would usually set an init command but it doesn't seem to work with sqllitle. I came up with something like this in settings.py: if 'loaddata' in sys.argv: from django.db import connection cursor = connection.cursor() cursor.execute('PRAGMA foreign_keys = OFF') But it fails as there is in the library base a thing that would reenable it. -
How to add a 'MultipleChoiceField' filter using django-filters
You know when you use the following in forms.py COLORS_OPTIONS = ( ('Red', 'Red'), ('Green', 'Green'), ('Blue', 'Blue'), ) class ColorsForm(forms.ModelForm): color = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=COLORS_OPTIONS) class Meta: model = Color fields = '__all__' and it displays it as checkboxes in your template? I want to do the exact same thing just using django-filters (in order to filter of course). How can I do that? -
Django Restframework using password for jwt_secret
I want to make older refresh tokens invalid whenever a user updates their password. Django restframework jwt takes a function that returns a secret jwt for a particular user. def jwt_get_secret_key(user): jwt_secret = ... return jwt_secret Instead of this being some set value. I wanted it to be a hash of the users password. What's the best implementation for this approach? -
Get data from OrderItem object ()
I'm creating an ecommerce app. And right now I'm trying to send the Items to Order with an Email to me. I want to send a message with the items. The email is send with a form to the backend which sends the email over sendmail() to me. Sending the Email works but getting the items in the Email does not. I use some Javascript to handle the sending of the email and updating the cart. Here are my models.py: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) # Nicht nötig image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity … -
Converting a 'go home' button from jquery to django
I am a beginning programmer trying to learn Django. I have a 'go home' button that worked fine in jquery: $("#goHomeButton").on('click', function(){ goHome(); }); function goHome() { location.replace("../public/home.html"); I am trying to do the same thing with Django, but after several days (and many online searches) I still have not found a way to do this. I suspect it is as simple in Django as it is in jquery, -
how can i make someone on another network access my website with django
hello guys I'm trying to make another one to access my Django website I host it on my localhost by type python manage.py runserver 0.0.0.0:8000 and i set the ALLOWED_HOSTS = ['*'] when I trying to connect with my IP it's says refused to connect. can someone help me -
django Form values are empty
I have a problem with the home page displaying form values. Although on the search page the values are fine. What could be the problem here? I copied the same form from the search page to the homepage but still, it doesn't work, the values are empty. Any hint is appreciated, thank you! search page: <form action="{% url 'search' %}"> <div class='flx around px'> <input type='text' id='search-keyword' class='search-keyword form-control' placeholder='keywords (pool,garage)'> <select name='area' id='search-area' class='form-control'> <option selected="true" disabled="disabled" selected>Area(All)</option> {% for key,value in area_choices.items %} <option value="{{ key }}" {% if key == values.area %} selected {% endif %}>{{ value }}</option> {% endfor%} </select> </div> <div class='flx around'> <select name="bedrooms" class="form-control"> <option selected="true" disabled="disabled" selected>Bedrooms(All)</option> {% for key,value in bedroom_choices.items %} <option value = "{{ key }}" {% if key == values.bedrooms %} selected {% endif %} >{{ value }}</option> {% endfor %} </select> <select name="price" class="form-control "> <option selected="true" disabled="disabled" selected>Price(All)</option> {% for key,value in price_choices.items %} <option value = "{{ key }}" {% if key == values.price %} selected {% endif %} >{{ value }}</option> {% endfor %} </select> </div> <button type = "submit" class='btn fntmk my2 size'>Search&nbsp;<i class="fas fa-search size"></i></button> </form> home page: <form action="{% url 'search' … -
Getting Image in django teplate from ManyToMany field
It is returning an error : Not Found: /post-detail/6/images/wallpaper002.jpg. I have tried to show image through {{ post_detail.img.all.first.url }} but I could show image in the template, it returns None value. news.html ''' <div class="text-center"> <img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first }}"> </div> ''' models.py ''' class Pictures(TimestampedModel): img = models.ImageField(upload_to='images') def __str__(self): return str(self.img) class Post(TimestampedModel): title = models.CharField(max_length=128) lang = models.IntegerField(choices=LANGUAGES, default=1) short_description = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) category = models.ManyToManyField(PostCategoies, blank=True) img = models.ManyToManyField(Pictures, blank=True) icon = models.CharField(max_length=128, blank=True, null=True, help_text="Example: fa fa-info") is_active = models.BooleanField(default=True) def __str__(self): return self.title ''' views.py ''' from django.shortcuts import render, redirect from django.contrib import messages from django.views import View from .models import Post, Pictures from django.views.generic import DetailView from . import models from django.shortcuts import get_object_or_404 class HomePageView(View): def get(self, request): posts = Post.objects.all()[:4] context = {'posts': posts} return render(request, 'index.html', context) class PostDetailView(DetailView): context_object_name = "post_detail" model = models.Post template_name = 'news.html' ''' urls.py ''' app_name = 'posts' urlpatterns = [ path('', HomePageView.as_view(), name=""), path('post-detail/<int:pk>/', PostDetailView.as_view(), name="post_detail") ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ''' -
Download file from a django UpdateView template
I'm new to django, and I've a little problem. I've a model with a FileField field, using generic views and ModelForm, I can upload a file to the server. In a modify page using an UpdateView I've a link to my document (e.g. http://127.0.0.1:8000/static-storage/file_name),but if I try to download I get an error page not found. Maybe I need to write an url path but I can't understand how to implement. Could someone give me an help ? Thanks. -
how convert data to string in django templae
I have a trouble in my django template, the below code don't work <td> {% if product.size %} {% for size in product.size.__str()__.split(",") %} <span style="border:1px solid red;"> {{size}} </span> {% endfor %} {% endif %} </td> what can I do to work my code ?