Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Faker, populating a users model
Using this link as a reference(https://medium.com/@sharma.ashish.1996/populating-database-with-faker-library-794ec0976a99) and an online django course, I made a population script to create fake users for the website on django 1.11. It generally works just that the first and last names are exactly the same (e.g. Sprinkle Sprinkle) and it only populates one user at a time, is there something wrong with the populating script? Thanks! Best regards import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','ProTwo.settings') import django django.setup() from AppTwo.models import User from faker import Faker fakegen= Faker() def populate(N=5): for entry in range(N): fake_name= fakegen.name().split() fake_first_name = fake_name[0] fake_last_name = fake_name[1] fake_email= fakegen.email() #new entry user = User.objects.get_or_create(first_name = fake_last_name,last_name= fake_last_name,email = fake_email)[0] if __name__ == '__main__': print('populating databases') populate(20) print('populated') -
How serializers and reponse data pls Django-rest
I am doing a small project in Django with the rest framework and I reached a point where I don't really know how to continue. In the application, my order model like this class Order(models.Model): drink = models.TextField(blank=True, null=True) total = models.IntegerField(null=True, blank=True) ordered_at = models.DateField(default=timezone.now) i want custom reponse like this . I think will use distinct(), and group_by but i don't how do it apply to serializer . If i use views.APIViews i think i can do it . But i want use serializer and use pagination of django for that api . [ { "id": 1, "ordered_at": "2020-09-19", "orders": [ { "id": 64, "drink": "", "total": 200000, "ordered_at": "2020-09-19" }, { "id": 65, "drink": "", "total": 200000, "ordered_at": "2020-09-19" } ] }, { "id": 2, "ordered_at": "2020-09-18", "orders": [ { "id": 63, "drink": "", "total": 200000, "ordered_at": "2020-09-18" } ] } ] -
Update model object using modelformset_factory in a CBV
I am running into a problem when trying to update an object using the CBV (class based view) - UpdateView. I am aiming to use this single CBV (AssetDetail) to both display and update a given, pre-existing model object (Asset) - in a form. Currently - Assets are collected from the DB and laid out on a table. Each Asset item in the table has a Details button which opens a modal window on the same page. In this modal page is the model form in question - where it displays the Name/Price/etc. of the clicked Asset.The form is accompanied with a basic submit button that I was hoping would POST any update made to these fields back to the CBV for validation and save. However - Im hitting an ManagementForm data is missing or has been tampered with error when this update button is clicked. forms.py class AddAssetForm(forms.ModelForm): class Meta: model = Asset fields = ['user','name', 'slug', 'price'] widgets = { 'user': forms.Select(attrs={'id':'add_asset_user', 'class': 'form-control', 'required':'true', 'hidden':'true', }), 'name': forms.TextInput(attrs= {'class': 'form-control ', 'placeholder':' Asset name', 'data-toggle': 'tooltip', 'title': 'The main name of your asset', 'oninput':"add_asset_input_name(event)", 'required':'true'}), 'slug':forms.TextInput(attrs= {'class': 'form-control', 'id':'add_asset_slug', 'data-toggle': 'tooltip', 'title': 'This will auto-fill based on … -
How come I'm getting a CSS loading error in Django with just a minor difference in path name?
Just to give a brief background on the issue, I set up a simple ticketing system. Version I used for Django is 3.0.7, whereas Python is 3.7. I used both bootstrap as my header and crispy forms to design the forms. I placed the static configuration within my settings.py to make sure Django finds it within the directory: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] Then loaded the following within my templates: {% extends '_base.html' %} {% load crispy_forms_tags %} This would load the pages properly. I didn't come across any issues. Now this is where I found an interesting situations. When I used this path for editing forms in urls.py: path('edit/ticket/<int:pk>', ticketEditView, name='edit_ticket'), The page loaded with all the details but the CSS did not load properly. An error of '"GET /edit/static/css/_base.css HTTP/1.1" 404 3229"' popped up. When I replaced the path with the one below, everything seemed to work properly. path('edit/<int:pk>', ticketEditView, name='edit_ticket'), I want to know the difference of the path in urls.py. Why it reacted the way it reacted. -
how can i update foreign key child attribute in Django forms?
i have two forms. i want to update the book title and lesson name which is belong from a book too. i am getting this error 'Lesson' object has no attribute 'all' when i click on update url of a book. would you like to tell me how can i solve this issue? here is the trackback of error. Traceback(most recent call last): File "/home/project/NLS/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/project/NLS/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/project/NLS/src/report/views.py", line 42, in book_update_form lesson.pk), instance=lesson) for lesson in book.lesson.all()] Exception Type: AttributeError at / report/genrate/3 / Exception Value: 'Lesson' object has no attribute 'all' models.py class Lesson(models.Model): name = models.CharField(max_length=10) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=10) created = models.DateTimeField(auto_now_add=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) def __str__(self): return self.title forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ['title', 'lesson'] class LessonForm(forms.ModelForm): name = forms.CharField(max_length=10) class Meta: model = Lesson fields = ['name'] views.py def book_update_form(request, pk): book = get_object_or_404(Book, pk=pk) b_form = BookForm(request.POST, instance=book) l_form = [LessonForm(request.POST, prefix=str( lesson.pk), instance=lesson) for lesson in book.lesson.all()] if b_form.is_valid() and all([lf.is_valid() for lf in v_form]): book_update = b_form.save(commit=False) book_update.save() for lf … -
django httpResponseRedirect with a response
How to send a response with a httpresponseredirect in django? Things i have tried: response = HttpResponseRedirect("Authentication failed! Try again!") response['Location'] = '/permissionDenied' return response I could send the response in the header like response['error']:"Authentication failed! Try again!" But i need to send it in the response for ui to handle it. -
How can I avoid repetition of code within a function-based view in Django?
I have been researching how can I avoid using snippet of code over and over. The answer probably will involve using (generic) Class-based functions. However, I am a beginner in Django and this seems confusing. Here is my view in views.py: @login_required(login_url='/login') def view_list(request, listing_id): bid = Bid.objects.all().filter(listing=listing_id).order_by('-id') b_u = bid[0].user listing = Listing.objects.get(pk=listing_id) if request.method == "GET": return render(request, "auctions/view_list.html", { "form": BidForm(), "total_bids": bid.count(), "bid": None if bid == 0 else bid[0].bid, "listing": listing, "bid_user": "Your bid is the current bid." if request.user == b_u else None }) else: form = BidForm(request.POST) if form.is_valid(): value = form.cleaned_data if value['bid'] <= bid[0].bid: error_check = True return render(request, "auctions/view_list.html", { "error_check": error_check, "alert": f"Your bid is lower than the current bid $({bid[0].bid})! Try placing a higher one.", "form": BidForm(), "total_bids": bid.count(), "bid": None if bid == 0 else bid[0].bid, "listing": listing, "bid_user": "Your bid is the current bid." if request.user == b_u else None }) else: error_check = False new_bid = form.save(commit=False) new_bid.user_id = request.user.id new_bid.listing_id = listing.id new_bid.save() return render(request, "auctions/view_list.html", { "error_check": error_check, "alert": "Your bid was successfully placed!", "form": BidForm(), "total_bids": bid.count(), "bid": None if bid == 0 else bid[0].bid, "listing": listing, "bid_user": "Your bid is the … -
is there a huge difference between django 1.11 and django 3.8?
I Recently Joined in a course Which is quite nice and I like it but it's Explaining on Django 1.11 And Currently am using Django 3.8 SO is there a huge difference between these two Or They are similar ?? -
how to use JWTTokenUserAuthentication backend experimental feature in djangorestframework-simplejwt
I am planning to create microservices architecture in Django and Django rest framework. My intent is to have a separate Django project that handles authentication. This project has djangorestframework-simplejwt package which mentions an SSO feature here. How do I implement this? Should I update the DEFAULT_AUTHENTICATION_CLASSES in both the django projects? -
How to render Django-filters form with buttons as widget?
So, I'm using Django-filters to easily filter pictures on my website, but I need to render it with buttons as widgets. My code: class PicsFilter(django_filters.FilterSet): GAMES = Pics.GAMES ARTS = Pics.ARTS game = django_filters.ChoiceFilter(choices=GAMES) artType = django_filters.ChoiceFilter(choices=ARTS) def __init__(self, *args, **kwargs): super(ArtFilter, self).__init__(*args, **kwargs) if self.data == {}: self.queryset = self.queryset.none() class Meta: model = Pics fields = ['game', 'artType', ] I need game (which shows various game's titles) to be rendered with buttons and artType with dropdown menu, where the last is not a problem because it's the default way it renders. How do I achieve buttons as widgets though? I tried using django-crispy-forms, but I guess I did it wrong, because I tried from crispy_forms.layout import Button ... game = django_filters.ChoiceFilter(choices=GAMES, widget=Button) But it didn't work as intended, as it needs to be called with 2 values and even with those it throws an error 'Button' object has no attribute 'value_from_datadict' So I get it, it's not supposed to work this way, but I'm stuck how else can I achieve this. -
Django Choice Field Set as Default button
I am trying to make a set as default button for my field and this is what I am trying to do and doesn't seem to work can someone help me out. forms.py class VForm(forms.Form): Hours = forms.ChoiceField(choices=[(i,i) for i in HOURS_CHOICES], initial = Defaults.HoursDefault ,widget=forms.Select(attrs={ 'class':"form-control selectpicker", 'data-dropup-auto':"false", 'data-live-search':"true", })) Minutes = forms.ChoiceField(choices=[(i,i) for i in MINUTES_CHOICES], initial = Defaults.MinutesDefault ,widget=forms.Select(attrs={ 'class':"form-control selectpicker", 'data-dropup-auto':"false", 'data-live-search':"true", })) views.py def dashboard_view(request): if request.method=="POST": form = VForm(request.POST) if form.is_valid(): v = form.cleaned_data userInput = dict( hours=v["Hours"], minutes=v["Minutes"], ) request.session['userInput'] = userInput request.session['v'] = vsl print(userInput) form = VForm() content = {} content['form'] = form return render(request,"app/dashboard.html",content) html function Default() { {{ Defaults.VSLMinutesDefault }}=document.getElementById("VSLForm.Minutes"); } -
how to list APIs of multiple Django projects using microservices architecture on a single domain
So I have multiple Django projects(DRF) that acts as microservices. Let's suppose Project1 has Project1 APIs and Project2 has Project2 APIs, how do I list both Project1 and Project2 APIs in the same domain as api.example.com? Is there a feature in the Django Sites framework to achieve this or should I look into Django Rest Framework Routers? FYI, I am planning to deploy these applications on AWS EC2 using Elasticbeanstalk and Docker. -
How can i use python code as core for website?
Hi ,I have written python algorithm in windows and I wanna make UI for this code in web . I haven't make any server or API and so on .How can I do it ? How can I use my code as core for website ? -
How can a logged in user comment on a post? django
I wrote the codes for commenting system and whenever you want to add a comment to a post, You'll be redirected to a page that you can write your comment and choose which member you are. How can I fix the member field with the user that is currently logged in to the site? And how can I make the comment section only down the post and not being redirected to another page? Here's my view.py def comment_post(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('samplepost', slug=post.slug) else: form = CommentForm() return render(request, 'blogapp/comment.html', {'form': form}) and here is my models.py class Comment(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, related_name='comments') body = models.TextField() date_created = models.DateTimeField(auto_now_add=True) -
import variable with data from django to sql database (SQLite3) Django
I'm a beginner so sorry if it's a stupid question. I create a site on the Django. On the HTML code, a have a form that to request and save the data of the form fields on the variable. on views.py file. How I can to do this: when I going to a web page, force Django to run a Python file in the same folder) (which contains a code with a request to add data from a form to a database table) I'm home that I succeed to explain it. -
django get 7 days back date from one date
Here is the date i am getting from django model data 2020-09-18 05:46:41.043849+00:00 <class 'datetime.datetime'> I am trying to get 7 days back from that that. Expected result: 2020-09-11 05:46:41.043849+00:00 Is there any way we can achive that efficiently ? Please have a look -
Django application error when deploying to heroku
I'm new to python and the Django framework. After some series of learning python and Django, I created a web app. I wanted to deploy it into Heroku platform but I'm caught up with this weird error. I have spent weeks googling and researching and finding solutions but to no avail. One of the errors I couldn't fix was wrapt==1.12.1) is not available for this stack (heroku-18). I have searched everywhere on the internet and pip installing wrapt==1.12.1 but still, I kept getting the same error. Please I need help in fixing this error. Thank you. The error message is down below. Error message here -
How to get all the texts from html page having same id with JavaScript?
I am having webpage with this code:- <article class="media content-section"> <div class="media-body"> <h2><a id="post_title" class="article-title" href="/post/new/">new</a></h2> <div class="article-metadata"> <a class="mr-2" href="/profileview/manish">manish</a> <div class="float-right"> <small class="text-muted">Category</small> <small class="text-muted">Sept. 19, 2020, 2:49 a.m.</small> </div> <div style="float:right;"> <img style="height:19px; width:18px;" src="/static/blog/viewicon.png"> <p style="float: right; display: inline !important;" id="ViewCount"> </p> </img> </div> </div> <p class="article-content"><p>newnwnewnenwnenwenwewewewewe</p></p> </div> </article> <article class="media content-section"> <div class="media-body"> <h2><a id="post_title" class="article-title" href="/post/post-with-markdown-styling/">Post with Markdown Styling?</a></h2> <div class="article-metadata"> <a class="mr-2" href="/profileview/manish">manish</a> <div class="float-right"> <small class="text-muted">Category</small> <small class="text-muted">Sept. 15, 2020, 6:46 p.m.</small> </div> <div style="float:right;"> <img style="height:19px; width:18px;" src="/static/blog/viewicon.png"> <p style="float: right; display: inline !important;" id="ViewCount"> </p> </img> </div> </div> <p class="article-content"><p>This are the points which you should follow while writting a good blog:- Have a proper Introduction.&nbsp;Be explainatory.&nbsp;Use easy english language.&nbsp;Be consise and clear.&nbsp;Have a go…</p> </div> </article> ------ ------ ------ I am trying to add a text on the tags containing the id ViewCount by adding a condition to my javascript code that whenever the title feched from the server mathes the title of the page. Here's my javascript code:- $(document).ready(function(){ setInterval(function() { $.ajax({ type:'GET', url: "{% url 'getBlogs' %}", success: function(response){ $("#ViewCount").empty(); for (var key in response.blogs) { var fromServerTitle = response.blogs[key].title; var fromPageTitle = document.getElementById("post_title").innerText; if (fromServerTitle == … -
'chromedriver' executable needs to be in PATH in Python Django
I am trying to execute a Python script in Django. My view file is: def generate_traffic(request): #other code out = run([sys.executable, 'C://Users//Maisum Abbas//learning_users//trafficapp//traffic.py', "--domain", url, "--thread", requests, "--max-clicks", maximum, "--min-clicks", minimum]) If I run the script alone without running it in Django, it works fine. Now, the problem that I am facing is that the script is not able to detect chromedriver if I run it from my function generate_traffic in view.py. I don't know what seems to be the problem since the chromedriver is in the same directory as of my other files. myFolder -view.py -traffic.py (the script I am executing) -chromedriver.exe -otherfiles Kindly guide me of what I am doing wrong or what seems to be the problem here. -
While setting interpretor to python 3.8.2 in django its giving errors such as unable to import django.urls?
I am working on django in VS code. Its giving errors on any django import (ex unable to import django.urls) while setting interpreter to python 3.8. Although when I set interpreter to python 2.7 the errors are resolved. I have installed django in virtual environment. Please enlighten me why this problem is occuring and will it cause any trouble in future?enter image description hereenter image description here -
Can we set live django project on local machine
Is there any way to setup live django project on local machine for practice. There are many ways to set php projects on local machine, same as is there any way for django. -
Error while querying attendance list of employee having OneToOne user relation
I am trying to get my employee attendance list using django-rest-framework but getting this error::: ValueError at /shifts/api/v1/my_attendance Cannot query "sureshemployee@gmail.com": Must be "Employee" instance. Please help class EmployeeAttendance(ModelDateCommonInfo): employee = models.ForeignKey(Employee, related_name='employee_attendances', on_delete=models.CASCADE) check_in = models.TimeField() check_out = models.TimeField() class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') class MyAttendanceList(generics.ListAPIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAuthenticated] serializer_class = MyAttendanceListSerializer filterset_fields = [] def get_queryset(self): queryset = EmployeeAttendance.objects.filter(employee=self.request.user).order_by('-created_at') return queryset Error : Cannot query "sureshemployee@gmail.com": Must be "Employee" instance. Please help -
django.core.exceptions improperly configured ("Error loading psycopg2 module:no module named psycopg2._psycopg2
Can't come up with this error. Any idea about this. ''' django.core.exceptions.improperlyconfigured:error loading psycopg2 module: No module name psycopg2_.psycopg2 ''' -
Ordering models using Django AutoField with custom step size
Consider a model Section that is displayed on a site and created / edited by a user using the Django admin interface. I would like to add a field that allows the user to easily control the order in which sections are displayed on the site. The easiest option seems to be to allow for an integer field that is auto-incremented but can be edited by the user -- akin to what the built-in AutoField does. However, to make editing the order easier, I would like to increment the fields default value by 10 every time, to allow the user to shift sections around more easily. The first section would get order=1, the next one order=11 and so on, that way a section can be wedged in between those first two by giving it, e.g., order=6. Is there a way I can reuse AutoField to achieve this purpose? And if no, how could I best achieve this type of ordering scheme? -
Django reverse relationship in many-to-many field
how do i get gallery response like bellow. Now, galleryserializer returns response with images array with ids only. I am not able to get details of images. json response: { "name": "New Gallery", "images": [ { id: 1, image: 'url/path/to/image', alt_text: 'alt' }, { id: 2, image: 'url/path/to/image1', alt_text: 'alt' }, ] } My models.py file: class GalleryImage(models.Model): image = models.ImageField(upload_to='gallery/') alt_text = models.CharField(max_length=300) created = models.DateTimeField(auto_now_add=True) class Gallery(models.Model): name = models.CharField(max_length=30) slug = AutoSlugField(populate_from='name', unique_with='id') images = models.ManyToManyField(GalleryImage, related_name="galleryimages") created = models.DateTimeField(auto_now_add=True) My serializers.py file: class GalleryImageSerializer(serializers.ModelSerializer): class Meta: model = GalleryImage exclude = '__all__' class GallerySerializer(serializers.ModelSerializer): class Meta: model = Gallery fields = '__all__'