Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send a dictionary through HTML form to Django
I have a form in HTML where I have an input called "csvModified", this is initialized with an empty value and I give it the following data. <input type="hidden" name="csvModified" id="csvModified" value="" /> ... var dict_separators = {}; dict_separators["column"] = separator_columns; (String) dict_separators["thousand"] = separator_thousands; (String) dict_separators["decimal"] = separator_decimals; (String) dict_separators["children"] = final_data; (Array [Strings]) ... document.getElementById('csvModified').value = dict_separators; on Django I am recieving this as data = request.POST.get('csvModified') print(data) However the output is the following [object Object] Am I sending the data correctly from the HTML Form? Is the problem in Python? How can I get the data and iterate over it -
Django - i want to view this plot into Browser
I'm new to Django for now i can pass variables but i don't know how to render dynamic plots from datetime import datetime from matplotlib import pyplot from matplotlib.animation import FuncAnimation from random import randrange x_data, y_data = [], [] figure = pyplot.figure() line, = pyplot.plot_date(x_data, y_data, '-') def update(frame): x_data.append(datetime.now()) y_data.append(randrange(0, 100)) line.set_data(x_data, y_data) figure.gca().relim() figure.gca().autoscale_view() return line, animation = FuncAnimation(figure, update, interval=200) pyplot.show() -
Is using javascript to reassign parents an appropriate way to assign items into flex columns?
I am trying to show a bunch of images in a website, created in django, and I want to be organised into three columns. Since the images can be of different vertical dimensions, I have decided to create 3 divs, one for each column, whose display mode is flex as I do not want to enforce them being in a grid but let the images vary in height. The code below is my solution to this and does what I want it to but, as I'm very inexperienced when it comes to django+css+etc I am wondering if there is a nicer solution to this. Here is the css for the columns and their parent div .display_wrapper { grid-column: 2 / 2; display: grid; grid-template-columns: repeat(3,minmax(100px,400px)); text-align: center; justify-content: center; grid-column-gap: 10px; } .displaycol{display: flex; flex-direction: column; height: 100%;} I add the items to the html using a django for loop, as below {% for object in object_list %} <div class="displaycol" id="col1"> </div> <div class="displaycol" id="col2"> </div> <div class="displaycol" id="col3"> </div> <div class={% cycle "incol1" "incol2" "incol3" %} > <a class="link" href="{% url 'view_object' object_title=object.title %}"> <img class="object_image" src={{ object.photo1.url }} > <h3>{{object.title}}</h3> <p>paragraph</p> </a> </div> {% empty %} {% endfor … -
Using Snowpack to transpile Web Components and package dependencies
I am using Django to build a SSR website and using Django to serve static files. I also built some Web Components using lit-element and Typescript. I would like to avoid the complexity of Webpack and use Snowpack instead. Components are stored at /static/js/components. To use the components, I need to (1) transpile them to Javascript, (2) make available their dependencies (e.g. lit-element) and (3) move the transpired files as well as the _snowpack folder to Django's /static/ folder. Using just snowpack build does both but creates a build folder with a complete copy of the application. It is my understanding that buildOptions.out only moves the output folder (thereby overwriting static/ altogether if buildOptions.clean===true). I guess it would be possible to script the copying of the necessary files and delete the rest of the build folder immediately, but that strikes me as quite inelegant. Is there a configuration to only create _snowpack and the transpiled files to a specific directory? -
Image does not save using Create View Base class in django
I am trying to create my first Website and I encountered some difficulties when I am trying to create a new entry for database using Create View class base. views.py class ProductCreate(CreateView, PermissionRequiredMixin): permission_required = ("mainpages.can_create",) model = Products template_name = "product_create.html" context_object_name = "product" fields = "__all__" def form_valid(self, form): form.save() return redirect("product_view") urls.py ........ path("product-create", views.ProductCreate.as_view(), name="product_create"), ....... models.py class Products(models.Model): name = models.CharField(max_length=50, blank=True, null=True) price = models.FloatField(blank=True, null=True) description = models.TextField(max_length=300, blank=True, null=True) resealed = models.BooleanField(blank=True, null=True) category = models.ForeignKey(to=ComputerScienceCategory, on_delete=models.CASCADE, blank=True, null=True) img = models.ImageField(upload_to='gallery', blank=True, null=True) quantity = models.IntegerField(default=1) def __str__(self): return self.name class Meta: verbose_name = "Product" verbose_name_plural = "Products" permissions = ( ("can_view", "Can view the product"), ("can_create", "Can create a product"), ("can_delete", "Can delete a product"), ("can_update", "Can update a product"), ) html {% extends 'index.html' %} {% block content %} <div style="margin-top:200px;"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Create"> </form> </div> {% endblock %} When I press the submit button, redirects me to the view template, but there the following error is being thrown ValueError at /product-view The 'img' attribute has no file associated with it. I checked my database and I realized that after I … -
Django custom QuerySet with custom filter
The elements that are stored in Django model is as following class Transcript(models.Model): text = models.CharField(max_length=10000, default="") confidence = models.FloatField(default=0) And example data is as following : Word1(1.00-1.50) Word2(1.50-2.15) Word3(2.40-2.80) Word4(3.10-3.25) Word5(3.44-4.12) Word6(4.55-5.12) Word7(6.00-7.00) Word8(7.34-8.00) . Transcript.objects.filter(text = "Word2 Word3") Result : Word2(1.50-2.15) Word3(2.40-2.80) Transcript.objects.filter(text = "Word5 Word6 Word7 Word8") Result : Word5(3.44-4.12) Word6(4.55-5.12) Word7(6.00-7.00) Word8(7.34-8.00) Transcript.objects.filter(text = "Word3 Word5") Result : Word3(2.40-2.80) Word4(3.10-3.25) Word5(3.44-4.12) How can I make these queries using filters and possibly using regex ? -
Unicode-objects must be encoded before hashing while rendering gravtar in a django template
I have installed django-simple-gravatar and added that in my installed apps in the project. And i am now trying to render the gravtar associated with user email: {% load gravatar %} {% gravatar_url user.email 40 %} This is my profile view: def Profile(request, pk): template = 'events/profile.html' user = User.objects.get(id=pk) posts = Post.objects.filter(owner=user) liked_posts = Fav.objects.filter(user=user) ctx = {'user': user, 'posts': posts, 'liked_posts': liked_posts} return render(request, template, ctx) But i get the following error Unicode-objects must be encoded before hashing I tried {% gravatar_url user.email.lower().encode("utf-8") 40 %} But then i get Could not parse the remainder: '().encode("utf-8")' from 'user.email.lower().encode("utf-8")' Please tell me what do i do to render the gravtar image -
where will i get the uid and token to reset the password?
My url: path("rest-auth/", include("rest_auth.urls")) When i request password reset with this endpoitn: http://127.0.0.1:8000/rest-auth/password/reset/ it sends me an email with an url which is working well to reset password but i don't need need like this way. I am using http://127.0.0.1:8000/rest-auth/password/reset/confirm/ to confirm the password reset and it expect following data { "new_password1": "", "new_password2": "", "uid": "", "token": "" } I dont receive uid and token in the mail, only i receive an url to reset password, anyone there know how can make confirm password reset? -
Dynamic HTML to PDF using Python or Javascript
I am trying to add "Download PDF" link on my webapp. At the moment, I call a django function which gets a queryset and passes the context to a html file. However, I would like users to be able to download this html file as a pdf with watermark in the center. I have tried jspdf html2canvas but nothing works with. I have tried xhtmlpdf but its too slow in rendering the html. Any help would be appreciated. -
Creating REST API in Django REST Framework for fetching record from one table in JSON format
I am using Django REST Framework for creating REST APIs. I am working with MySql Database where one table named questionsModel is there. In that table I am storing Course(JEE, IEEE), Subjects(Phy, Chem, Math), Topics, SubTopics, Questions etc which are already mapped with another tables like coursesModel, subjectsModel etc. I am showing my Model Class here : models.py : class questionsModel(models.Model): course_id = models.ForeignKey(coursesModel, max_length=20, null=True, on_delete=models.CASCADE) subject_id = models.ForeignKey(subjectsModel, max_length=20, null=True, on_delete=models.CASCADE) topic_id = models.ForeignKey(topicsModel, max_length=200, null=True, on_delete=models.CASCADE) subTopic_id = models.ForeignKey(subTopicsModel, max_length=20, null=True, on_delete=models.CASCADE) type_id = models.ForeignKey(questionTypesModel, max_length=20, null=True, on_delete=models.CASCADE) # Numerical or Multiple Choice Question = models.CharField(max_length=1000, blank=False, null=True) choice = (('c1','c1'), ('c2','c2'), ('c3','c3'), ('c4','c4')) answer = MultiSelectField(choices=choice) numericAnswer = models.CharField(max_length=1000, blank=False, null=True) marks = models.PositiveIntegerField(default=0) easy = models.PositiveIntegerField() average = models.PositiveIntegerField() tough = models.PositiveIntegerField() very_tough = models.PositiveIntegerField() def __str__(self): return self.Question Here, I am storing n number of Questions in this table. Now my requirement is to fetch lets say 50 random Questions depending on Complexity of the Questions like 10 easy, 20 average, 5 tough etc. I am putting my code here : serializers.py : class questionPaperSerializer(serializers.ModelSerializer): class Meta: model = questionPaperModel fields = '__all__' Can anyone please explain or provide me the code for ````Class … -
Django obj.save() creating duplicate profile instead of updating
I have created a rest API that i want to be able to use to update a users profile information, however instead of updating the profile it creates a new one for that user with the updated fields. so in signaly.py when the instance user is saved it also saves the users profile with instance.profile.save() which is meant to update the profile but instead creates another profile object for the user meaning they now have 2 profiles I have tried, in the serializer, to obtain the profile created first for the user and delete it but you cannot delete an obj that doesn't have a primary key. would appreciate it if anyone could help out, thanks models.py class Profile(TimestampedModel): user = models.OneToOneField( 'User', on_delete=models.CASCADE ) TEAM_CHOICES = ( [...] ) image = models.URLField(blank=True) location = models.CharField(max_length=50, blank=True) fav_team = models.PositiveSmallIntegerField(choices=TEAM_CHOICES, blank=True, null=True) points = models.PositiveIntegerField(default=0) def __str__(self): return self.user.username serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True ) profile = ProfileSerializer(write_only=True) location = serializers.CharField(source='profile.location', read_only=True) image = serializers.CharField(source='profile.image', read_only=True) fav_team = serializers.CharField(source='profile.fav_team', read_only=True) points = serializers.CharField(source='profile.points', read_only=True) class Meta: model = User fields = ('email', 'username', 'password', 'token', 'profile', 'location', 'image', 'fav_team', 'points',) read_only_fields = ('token',) def update(self, instance, … -
Django Admin for Multi-Table Inheritance Models
I've got the following models for a user set up using multi-table inheritance: class MyBaseUser(AbstractBaseUser): # model fields.... class Meta: verbose_name_plural = 'Users' class SubUser(User): # model fields Now in terminal, everything seems to be working as expected, when creating a SubUser it returns a SubUser instance and creates a MyBaseUser in the db. If I query the MyBaseUser class for the id of the created SubUser it returns and I can do my_base_user_instance.subuser.<sub_user_field> - all behaving as I'd expect. How should I set up a ModelAdmin for the SubUser class though? I've got: @admin.register(SubUser) class SubUserAdmin(admin.ModelAdmin): # fields... but none of the SubUser instances are showing up, which I think makes sense given how the multi-table inheritance works, but how do I set up the admin to display/update the subclasses? I've not run into this before, thanks. -
How can I consolidate multiple entries in my data dictionary into only a single entry in my Django View class?
I am working on a Django site that allows a data dictionary to be generated using by analyzing an uploaded metadata set. Each metadata set contains a set of tables, and within those tables, each field and unique value associated with the field. Because some of the fields and/or values have meanings that are not always clear, a data dictionary can be generated which takes each field and/or value and allows users to enter in definition or explanation of field/value in question. It should also be noted here that there is additional information that users can add to each field in the Django site, which are: Is the field a person ID number? Should the field be ignored in the further analysis and data dictionary generation? Should the values in the fields be passed "as is" into further analysis? If the first two questions are marked as true, then the given field is excluded from the data dictionary generation and other analysis. If the last question is marked as true, then when that field is included in further analysis, its values are given without any additional transformation. However, I still want those fields to be included in the further analysis, … -
Django: ModelForm get ManyToMany Field in clean Function
i have a Model called Order and it's it has manytomanyfield to ProductModel i want to get the values of selected products in clean function to make some calculations but i cannot find product field this is the modelform code class OrderForm(ModelForm): class Meta: model = Order fields = "__all__" def clean_points(self): products = self.cleaned_data["Product"] print(self.cleaned_data.get( 'product', None)) points = 20 self.set_customer_points(self.cleaned_data["customer"], points=points) return points def set_customer_points(self, customer, points=0): customer.points = customer.points + points customer.save() and this is OrderModel class Order(models.Model): customer = models.ForeignKey( Customer, on_delete=models.SET_NULL, null=True) description = models.TextField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100, ) discount = models.DecimalField(decimal_places=2, max_digits=100) order_state = models.ForeignKey( 'OrderState', on_delete=models.DO_NOTHING, null=True) points = models.IntegerField(default=0) product = models.ManyToManyField( "product.Product", ) def __str__(self): return self.customer.name class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) discount = models.DecimalField(decimal_places=2, max_digits=100) image = models.ImageField(upload_to="products",) points = models.IntegerField(default=0) def __str__(self): return self.name -
How total amount on cart be added to paystack/flatterwave payments
so I want to add the total amount on my shopping cart to the Paystack Inline and flutterwave inline module as well as the user email. How can I do this? I do not want a fixed amount like in the documentation.. Which is easier to do, in flutterwave inline or paystack inline? And how can I do it? -
Error With Django URL When Passing Parameter
I am setting up a new URL path but I keep getting a page not found. This is my URL that isn't working: url(r'^collections/(?P<collection_name>\d+)$', collections.home, name='collections'), This is the function in my view: def home(request, collection_name, slug=None): collection_data = Collections.objects.get(collection_name=collection_name) try: logged_id = request.GET.get('admin_id') except: logged_id = "" return render(request, 'collections.html', {'collection_data':collection_data,'logged_id':logged_id}) If I turn it into a simple URL and remove the parameter from the URL and view function as follows, it works fine so I know I'm pointing to the right view: url(r'^collections$', collections.home, name='collections'), In the same file I have another URL as follows, and it also works fine: url(r'^store/(?P<seller_id>\d+)$', store.home, name='store'), This leads me to believe that I have a simple typo or something really basic that I am overlooking. Can anyone help me spot the error here? Thank you! -
Using Celery/RabbitMQ/Flower in deployment with Django Website
I have a django website that utilizes celery scheduling async tasks. When I am in development mode, I run the commands: celery -A proj worker --pool=solo -l INFO flower -A proj --port:5555 celery -A proj beat -l info for my project to work. How can I run these commands on a cloud based hosting service such as pythonanywhere. In development I would go to localhost and port number to view rabbitmq and flower. How will this work in deployment? -
Interacting with Django/Flask backend from web app
I would like to ask if there is any documentation which covers interaction between a javascript-based front end with python packages running in the backend in django. So for example, if I want to display the amount of followers for a certain twitter account (obtained using e.g Tweepy), I can pre-code that twitter account in the back end and have the information displayed in the front end and use jinja2 to insert the data where I need into a Javascript-based UI (e.g Chart JS). However, if I want the user to specify the twitter account using an input text box, how can I best configure an input box, which will send the data back to the view, that would update the data based on that input, and return the new input to the template? For example entering 'Joe Biden' would send that information into the tweepy function, and then in my view, I would return the results of that function back into the template. I am currently creating the dashboards using Dash, but the dash UI feels a bit out of place with the UI for the dashboard. I cannot find any documentation that shows more than the hard-coding back-end … -
Django: No post found matching the query when creating a post
I just got slugs to work for my Post model using django-autoslug. But i'm now experiencing this error when i try to create a new post: Page not found (404) Request Method: GET Request URL: http://localhost:8000/post/new/ Raised by: blog.views.PostDetailView No post found matching the query Post Model class Post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = AutoSlugField(populate_from='title', null=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug, 'author': self.author}) views.py class PostDetailView(DetailView): model = Post def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(author__username=self.kwargs['author']) urls.py urlpatterns = [ path('', views.home, name='blog-home'), path('<str:author>/<slug:slug>/', PostDetailView.as_view(), name='post-detail') path('post/new/', PostCreateView.as_view(), name='post-create'), path('<str:author>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('<str:author>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to use session key to authenticate/track users in djagno channels
How can i use session key to authenticate/track users and save chats in database. consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.scope['session']['user_identifier']= self.room_name self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() .......... -
freeze_time doesn't work inside invoked functions
# test.py from freezegun import freeze_time from actual import DummyClass class DummyClassMock(DummyClass): def some_function(self): # does something class TestClass(): def setUp(self): self.dummy = DummyClassMock() @freeze_time('2021-01-01') def test_dummy_function(self): self.assertTrue((self.dummy.dummy_function - datetime.utcnow()).total_seconds() >= 1) # actual.py from datetime import datetime class DummyClass(): def dummy_function(self): return datetime.utcnow() My code goes along the above structure. With this, if I am executing the test_dummy_function individually, dummy_function is returning 2021-01-01 and test case is a pass. However, when I running this along with all the other test cases in the project, it is failing. Content is not dependent either. -
IntegrityError at /music/4/music_create/ NOT NULL constraint failed: music_artist.as_pro_id
I'm trying to make a create view for a user to make an object list of their favourite artists but I keep getting an integrity error and I'm not sure what's the source of the problem. heres my model.py class Artist(models.Model): artist_name = models.CharField(default='', max_length=200) artist_name2 = models.CharField(default='', max_length=200) artist_name3 = models.CharField(default='', max_length=200) artist_name4 = models.CharField(default='', max_length=200) artist_name5 = models.CharField(default='', max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) as_pro = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='artist') and here is my class based create view class MusicCreateView(CreateView): form_class = ArtistForm model = Artist template_name = 'music/music_create.html' success_url = reverse_lazy('accounts:profile') def get_object(self, *args, **kwargs): pk =self.kwargs.get('pk') obj = Artist.objects.get(pk=pk) instance = form.save(commit=False) instance.save() if not obj.as_pro.user == self.request.user: messages.warning(self.request, 'You need to be the associated profile to edit this') super(MusicCreateView, self).form_valid(form) -
Display objects of a model using a dropdown menu, Django DetailView and get_context_data()
I'm trying to display a model's information using the generic DetailView from Django, where there will also be a dropdown menu below to allow users choose a specific object of the Location model. I'm actually stuck with two problems, where the first one is that the Location.objects.all in the template doesn't show the objects currently in my database, the second problem is that the get_context_data doesn't seem to do what it is expected. How can I fix it or is there actually an easier way to implement it without overriding the context data? Thanks a lot for any help. urls.py path('show/<int:pk>', views.ShowsView.as_view(), name = 'show'), views.py class ShowsView(generic.DetailView): model = Location template_name = 'showlocation.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pk'] = self.request.GET['location'] return context <h1>Location: {{ location.location_name }}</h1> <ul> <li> As of Date: {{location.as_of_date}}</li> <li> Population: {{location.population}}</li> <li> Total Case: {{location.total_case}}</li> ... </ul> <form action="" method = "get"> <label for="locations">Choose a location:</label> <select id="locations" name="location"> <option value=1>trial</option> {% for Location in Location.objects.all%} <option value="{{Location.pk}}">{{Location.location_name}}</option> {% endfor %} </select> <input type="submit" value="Go"> </form> -
Users have to request access to view post which are set to private Django
I created a simple Post model with heading and body and other basic fields having a foreign key relationship with user model to get the author of model class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField() type_choices = models.CharField(choices=TYPE_CHOICES, max_length=15) author = models.ForeignKey(user_models.User, on_delete=models.CASCADE) Here TYPE_CHOICES are Private and Public I want to show all posts in my homepage but when any user (other than author of that post) click on post which is set to private they have to request access to view that post. And that request would be sent to the author of that post and they can then either accept or decline the request for that user to view their post. I tried to search this but I am not getting what I am trying to search instead some other results are shown . If anyone can help me out on this it would be very much helpful -
Django - How do I limit the amount of objects returned per row?
I have a page with a bootstrap card for every item like {% for item in item %} create a card with some content.... How do I limit the amount of cards created per row until it jumps to the row below it?