Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Project structure and what apps should be in Django
Hello every one im learning django and im starting to master it. I have done many small project in django. But i still want to know what is the base way to structure diango project for advance and latter development. Here are simple case about it. Let say i want to have a website that have front and backend feature and have the url pattern domain/dj-admin for back end and front and have reguler url like wordpress. And in my website will have a blog and online store or maybe forum. Now we narrow it little bit. In blog shuld i create many app that containt post,category, tag and media app or i just create a blog app with post,cat,tag and media in blog model. And shuld i give every app a urls.py. because i want some url for example. Next for the backand shuld i create and project or just app to handle or user input for a ap. And If i create the backend app the url will be nice domain name and the url will loke like this domain/dj-admin/blog/post/edit. -
How can I get Django request data using query parameters
I am developing a web app and I want to use query parameter to show the task description. Currently I am using a post method which gets the ticked checkboxes and then redirects it to another view then that displays the description. Here is my code: Here is my views.py: @login_required def view_task_description(request): if request.method == 'POST': task_description = GetTaskDescription(data=request.POST, user=request.user) if task_description.is_valid(): obj = GetTaskDescription.get_task_description(task_description) return redirect('get_task_description', pk=obj[0].pk) return render(request, 'todoapp/select_task_description.html', context={'view_tasks': GetTaskDescription(user=request.user)}) @login_required def get_task_description(request, pk): obj = get_object_or_404(Task, pk=pk) return render(request, 'todoapp/task_desc.html', context={'description': obj.description}) Here is my forms.py: class GetTaskDescription(forms.Form): get_tasks = forms.ModelMultipleChoiceField( queryset=Task.objects.none(), widget=forms.CheckboxSelectMultiple, required=True ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(GetTaskDescription, self).__init__(*args, **kwargs) self.fields['get_tasks'].queryset = self.user.task_set.all() def get_task_description(self): tasks = self.cleaned_data['get_tasks'] return tasks Here is my urls: url(r'^view_task_description/$', views.view_task_description, name='view_task_description'), url(r'^view_task_description/(?P<pk>[0-9]+)/$', views.get_task_description, name="get_task_description"), I want to display the task description simply using get and not the whole way around using post and then get. I am not able to figure that out. Kindly help me. -
download large csv file after manual processing of queryset
I have a model in Django: class MyModel(models.model): a = models.FloatField() b = models.FloatField() It contains > 10.000 items. In my view I need to get all the items, do something with each one of them, and return csv file with a result: def myview(): allitems = MyModel.objects.all() for i in allitems: i.a = random.random() i.b = random.random() i.save() # WRITE_TO_CSV HERE return HttpResponse(allitems) The problem is that since I have manually process each item in allitems query, it takes a long time. What is the correct way to redirect a user to a resulting page to download file when it is ready without bumping into timeout issue? -
Creating dynamic ModelChoiseField from users List objects
I have been trying for awhile now without any luck.. I have model Like this: class List(models.Model): name = models.CharField(max_length=100, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') def __str__(self): returnself.name class Meta: unique_together = ['name', 'user'] Every user can create their own lists and add values to those lists. I have adding values and everything else working but to the form that adds these values I would somehow need to filter to show only users own lists, now its showing all lists created by every user... this is the form: class data_form(forms.Form): user_lists = List.objects.all() selection = forms.ModelChoiceField(queryset=user_lists) data = forms.IntegerField() Any ideas how to filter it? I have tempoary "list.objects.all()" since dont want it to give error that crashes the server. I have watched a ton of examples on stackoverflow but none of them seems to be exact thing that I am looking for.. Thanks already for asnwers! :) -
problem with connect django to stored procedure
I'm connected the database with Django that was successful Now I use the following code to call Stored Procedure views serializers models Display Error Exception Type: MultiValueDictKeyErro please help me. -
How to auto reload python module without restarting app?
maybe stupid question, but I am interested in adapting python file after I run the app. Suppose we have a script: import time while True: time.sleep(10) print(2) I run it, so it prints number 2 every 10 seconds. I would like to be able to change 2 to 5 so that I don't need to rerun script, but output changed to 5. This mechanism is somehow implemented in Django, when editing files are reloaded. -
comment isn't getting deleted
I made a comment model for a blog and I wanted to give the user a way to delete the comment so i made a function based view for it but it didn't work so I decided to use a class based view but both of the views give the same error. the only thing that happens is that the url gets a ? after it and the page just refreshes as it is the function based and class based views are both given below func based def comment_delete(request, pk): comment_to_delete=get_object_or_404(comment,pk=pk) if request.method=='POST': post_url=comment_to_delete.content_object.get_absolute_url() comment_to_delete.delete() messages.success(request, 'Your comment has been deleted') return HttpResponseRedirect(post_url) context={ 'comment':comment_to_delete } return render(request, 'blog/confirm_delete.html', context) class based class DeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = comment success_url = '/' def test_func(self): comment= self.get_object() if self.request.user == comment.user: return True return False html of confirm page {% extends 'blog/base.html' %} {% block content %} <form> <p>are you sure you want to delete {{ comment }}</p> <input type="submit" value="confirm" > </form> {% endblock %} models.py class comment(models.Model): post=models.ForeignKey(Blog, on_delete=models.CASCADE) user=models.ForeignKey(User, on_delete=models.CASCADE) content=models.TextField(max_length=160) timestamp=models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title,str(self.user.username)) def get_absolute_url(self): return reverse('comment', kwargs={"pk": self.pk}) -
Django filter objects F('duration') from now
I have a model: class Examle(models.Model): date = models.DateTime(auto_add_now=True) duration = models.IntegerField(default=90) # days And I want to filter it like so: Example.objects.filter(date_lt=datetime.today() - timedelta(days=F('duration'))) Of course timedelta won't take F-object as valid parameter, but hope you got what I mean. -
Django render loading page then load actual page
My actual page that I want to load takes quite a bit of time because it querying an API for a lot of data (python is doing the backend querying). How can I render my loading page and then render my actual page when the data has been gathered. What I am trying to do in my view.py class Page(ListView): def loading(request): return render(request,'loading.html') def viewProfile(request, player_name): Page.loading(request) context = { 'data1' : query_api(1), 'data2' : query_api(2), 'data3' : query_api(3), } return render(request, 'actualpage.html', context) -
Looking for opinions about my first project
Like in title, I'm looking for opinion about my first Django project because I want to start looking for my first job as developer and I don't know if my skills are already good enough for this(I know that as programmer my skills will never be good enough because always will be something new to learn but I want to start looking for job because there I can learn more than only by learning in home) I have project on GitHub: https://github.com/Kuracha/Shop-WebApp There isn't README yet and newest version of project is in working branch not in master because I must clear database yet, I'm mostly uncertain about quality of my API and tests. -
Implementing a invited users drop down list to posts in django
I have a model post for a social media type applicaiton, how would I create an invite's list that could query through the users and select ones to invite was thinking of creating a post access class table with a one to many relationship between users and posts, ideally a drop down menu would be made in the html, for a user to select the other users which are in the database. 1.What kind of relationship must my model show, I am fairly new to django 2.Would my form simply be class PostAccess(forms.ModelForm): class meta: model = PostAccess fields = ('allowed access') 3. Models from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) private = models.BooleanField(default=False) allowedaccess = models.ManyToManyField("Post",blank=True) class Postaccess(models.Model): allowedaccess = models.ForeignKey(Post,on_delete=models.CASCADE) -
Use Django template syntax in a css file
I have a css file home_global.css which has the following in it: body { background-image: url("{% static 'citator/citator.jpg' %}"); } This static file is loaded using: <link rel="stylesheet" href="{% static 'citator/home_global.css' %}" type="text/css"> However the url of the background-image, expectedly, doesn't resolve but is parsed literally. What I would like to do is enable Django template syntax in the css file. Please note that the static URLs etc are all set up correctly and this question doesn't involve that. This question is very similar to another question that I myself asked a month ago: How to use django template syntax in static files However, the answer provided there was specific to javascript, and in particular noted that "The fundamental issue that prevents this is that context is passed to the template that is mentioned in your render() function in the view(or any other function the behaves the same way e.g. render_to-response())." If I understand this correctly, the same limitation does not apply here. Furthermore, I've subsequently learned from the Django documentation that it is possible to use Django template syntax in a variety of text documents. It therefore seems to me that in this case, where I want to use … -
angular 7 not calling django URL
I need to call an url on my djangoserve, but its not executing. but console.log() shows, its the right URL, and also calling this url manually works as I wished. what am i doing wrong? script_dashboard.js ... var win = window.open("http://127.0.0.1:4200/" + values.toString(), '_blank'); ... app.components.ts export class AppComponent implements OnInit { constructor(private route: ActivatedRoute, private apiService: ApiService, private location: Location, private http: HttpClient) { } getFirstData(): void { const dbKey = this.route.snapshot.paramMap.get('key'); console.log(dbKey); this.apiService.getAllMeasurements(dbKey); } ngOnInit() { this.getFirstData() } } api.service.ts export class ApiService { baseurl = "http://127.0.0.1:8000"; httpHeaders = new HttpHeaders({ 'Content-type': 'application/json' }) constructor(private http: HttpClient) { } getAllMeasurements(key: string): Observable<any> { console.log("EXECITUNG") // return this.http.get(this.baseurl + '/reload_site/?keys=' + key, console.log(this.baseurl + '/tviewer/reload_site/?keys=' + key) return this.http.get(this.baseurl + '/tviewer/reload_site/?keys=' + key, { headers: this.httpHeaders }); } } console.log in browser null api.service.ts:15 EXECITUNG api.service.ts:17 http://127.0.0.1:8000/tviewer/reload_site/?keys=null core.js:16828 Angular is running in the development mode. Call enableProdMode() to enable the production mode. app.component.ts:20 1.1.1.1,T api.service.ts:15 EXECITUNG api.service.ts:17 http://127.0.0.1:8000/tviewer/reload_site/?keys=1.1.1.1,T as you see ..api.service.ts:17 http://127.0.0.1:8000/tviewer/reload_site/?keys=1.1.1.1,T.. is the correct url, but it gets not called. Some1 has an idea? -
Login authenticate is not working in django?
I am trying to make a login system which will authenticate wether user is in db or not.But it doesn,t authenticate the user.I don,t know what i am doing wrong and I really don,t have idea how this authenticate will check the model db info Please explain me what authenticate does and what will it do right now and please help me in fixing the problem Here,s my register view def register(request): user = UserProfile() if request.method == 'POST': user.username = request.POST.get('Username') user.email = request.POST.get('email') user.password = request.POST.get('Password') user.confirm_password = request.POST.get('ConfirmPassword') user.profession = request.POST.get('Proffesionname') user.save() return redirect(reverse('login')) return render(request,'social_app/register.html',{'user':user}) Here,s the login views def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('Password') user = authenticate(username = username,password = password) if user: if user.is_active: login(request,user) return HttpResponseRedirect('/profile/') else: return HttpResponse('User no longer active') else: print(f'username :{username}') return render(request,'social_app/login.html') Here,s the UserProfile model class UserProfile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) email = models.EmailField(max_length = 50) password = models.CharField(max_length = 20) confirm_password = models.CharField(max_length = 20) profession = models.CharField(max_length = 50) def __str__(self): return self.user.username -
Uploading image from React to DRF
I want to upload a picture when registering a new user in my DRF backend. However, when I try to upload the image, I get the following error: "The submitted data was not a file. Check the encoding type on the form." # models.py class User(AbstractUser): ... photo = models.ImageField(blank=True, upload_to='photos/%Y/%m/%d/') ... # serializers.py class RegisterSerializer(ModelSerializer): class Meta: model = User fields = (..., 'photo', ...) ... # frontend export const register = ({ ..., photo, ...}) => dispatch => { // Headers const config = { headers: { "Content-Type": "application/json" } }; // Request Body const body = JSON.stringify({ ..., photo, ...}); axios .post("/api/auth/register", body, config) .then(res => { dispatch( createMessage({ registerUser: `Registered new user! Welcome ${username}` }) ); dispatch({ type: REGISTER_SUCCESS, data: res.data }); }) .catch(err => { dispatch(returnErrors(err.response.data, err.response.status)); dispatch({ type: REGISTER_FAIL }); }); }; When I console.log(photo) it gives my a "File" object with the image details. The image is uploaded through react-images-upload . -
django and react ,api rest is obligatory?
I use the Nosql database with framework Django (backend) and React (frontend), it is obligatory to use an Api Rest or not? if so How to manipulate the data between the frontend and the backend. Thank you, -
How to Load JSON Data in Django Model
I want to load below json data in my Model. { "99popularity": 79.0, "director": "William Cottrell", "genre": [ "Animation", " Family", " Fantasy", " Musical", " Romance" ], "imdb_score": 7.9, "name": "Snow White and the Seven Dwarfs" }, { "99popularity": 84.0, "director": "Stanley Kubrick", "genre": [ "Adventure", " Mystery", " Sci-Fi" ], "imdb_score": 8.4, "name": "2001 : A Space Odyssey" }, I have create two models using reference to json data class Genre(models.Model): name = models.CharField(max_length=30) class Movie(models.Model): popularity = models.FloatField(max_length=10) director = models.CharField(max_length=30) genre = models.ManyToManyField(Genre) imdb_score = models.FloatField(max_length=10) name = models.CharField(max_length=30) But in Genre Model i don't have any data and in json in genre section their is no id instead name. How can i load that data in my model. Please Help. -
My Django redirect function is not working
I am developing a webapp and I cannot seem to execute my view that I have used in redirect method. Can someone help me with it ? Here is my views.py @login_required def view_task_description(request): if request.method == 'POST': task_description = GetTaskDescription(data=request.POST, user=request.user) if task_description.is_valid(): obj = GetTaskDescription.get_task_description(task_description) return redirect('get_task_description', pk=obj[0].pk) # return render(request, 'todoapp/task_desc.html', context={'description': obj[0].description}) return render(request, 'todoapp/select_task_description.html', context={'view_tasks': GetTaskDescription(user=request.user)}) @login_required def get_task_description(request, pk): # print "Reached get task descrition method" obj = get_object_or_404(Task, pk=pk) return render(request, 'todoapp/task_desc.html', context={'description': obj.description}) Here are my urls: url(r'^view_task_description', views.view_task_description, name='view_task_description'), url(r'^view_task_description/(?P<pk>[0-9]+)/$', views.get_task_description, name="get_task_description"), Here is my forms.py: class GetTaskDescription(forms.Form): get_tasks = forms.ModelMultipleChoiceField( queryset=Task.objects.none(), widget=forms.CheckboxSelectMultiple, required=True ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(GetTaskDescription, self).__init__(*args, **kwargs) self.fields['get_tasks'].queryset = self.user.task_set.all() def get_task_description(self): tasks = self.cleaned_data['get_tasks'] return tasks -
Django i18n gives incomplete translations
I am facing a problem with django translation. Some strings of my .po files doesn't appear when the server runs. I mean some translations are displayed some others are not. wether they appears or not, they are both listed in the django.po file. it's not a question of "fuzzy" tags, as a I removed them. It's seem not to be a question of empty quotes following very long msgid or msgstr. The only reason of that bad translation display are the format_html() function which allow to type a longer help text. Do you have any idea on how I can solve this case ? apps/survey/forms.py from django import forms from django.utils.translation import ugettext_lazy as _ from django.utils.html import format_html from django.forms.widgets import NumberInput from survey.models import Survey2019 class Survey2019Form(forms.ModelForm): class Meta: model = Survey2019 ... lines = forms.IntegerField( label=_('Lines'), help_text= _("What is the average number of lines contained in your reports ?"), widget=NumberInput(attrs={'type':'range', 'step': '1', 'min':'0', 'max':'500', 'step':'5'}), initial=0 ) categories = forms.IntegerField( label=_('Categories'), help_text= format_html("{}<br>{}<br>{}<br>{}", _("What is the average number of categories or dimensions in your reports ?"), _("Categories are mostly not numeric data."), _("They can't be computed but provide qualitative informations."), _(" For exemple : geographic areas, colors … -
How to activate Virtual Environment in DJango
I am currently on Windows and the Venv is not getting activatedUnactivated ENV, Is there any way to fix this. Thanking you guys in advance! Help out a newbie! -
Django 2 request.POST not saving to database with instance=request.user
I have a form where a user can submit some text, which then gets saved to the model TextSubmission. However, it only saves when I take out instance=request.user from views.py and it does not save with the instance of the user who submitted it. If I leave instance=request.user in, the request.POST object does not get saved but does get posted. (I can see from print(request.POST) Can someone help me figure out why this is and how to get the text to save along with the user? models.py class TextSubmission(models.Model): text_submission = models.CharField(max_length=50, null=True, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: ordering = ['text_submission'] def __str__(self): return self.text_submission forms.py class TextSubmissionForm(forms.ModelForm): class Meta: model = TextSubmission fields = ['text_submission'] views.py def profile_view(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) t_form = TextSubmissionForm(request.POST, instance=request.user) if u_form.is_valid() and t_form.is_valid(): u_form.save() t_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) t_form = TextSubmissionForm(instance=request.user) context = { 'u_form': u_form, 't_form': t_form, } return render(request, 'profile.html', context) profile.html <form method="POST" enctype="multipart/form-data"> <div class="profile-form"> {{ p_form }} {{ t_form }} </div> <button type="submit" value="submit">Update Profile</button> </form> -
Django FormView, Return without redirecting
I would like to know if it is possible to stay on the same page without having it reload to a success_url using FormView. Ideally I would it to just send a notification or do nothing at all. just process the form. if this makes sense. my code currently looks like this in views.py class Capture(FormView): template_name = "capture.html" success_url = '/' form_class = TestForm def form_valid(self, form, *args, **kwargs): print("Submit Capture") form.save_screenshot() return super().form_valid(form) how can I change this to not reload my page. Other libraries or methods are welcomed and not limited to using FormView. -
Complex name as primary key django error "NoReverseMatch"
I have complex names as the primary key, like "Service books\ PS 35 fianto". Django doesn't like them, so I get the NoReverseMatch error. Here is my url path: path('results/<str:pk>/', views.genre_book, name='books_genre_table'), My primary key for the model is a a TextField. desc_us = models.TextField(blank=True, primary_key = True, unique=True) Here is my error thread: Reverse for 'books_genre_table' with arguments '('Cta book Win / out Compatability ',)' not found. 1 pattern(s) tried: ['results/(?P<pk>[^/]+)/$'] This url is for a table with that unique service. However, the URL will not match. The underlying code works. -
Django pagination with mysql databse not working properly
I am trying to connection Django pagination with mysql Database but i am facing some problem Problem it's work fine when data is less. but when data is in millions it take 2-3 minutes to load the data in html page, even i am fetching only 100 rows at a time. every time I change the page it take 2-3 minute to load the data in html page view.py from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def displayLogs(request): from django.http import HttpResponseRedirect from django.shortcuts import renderimport mysql.connector con = mysql.connector.connect (host="localhost", user = "root", passwd ="12345", db = "database") cur=con.cursor() sql = "SELECT * FROM Table " cur.execute(sql) user_list=cur.fetchall() searchlen=len(user_list) paginator = Paginator(user_list, 100) page = request.GET.get('page') users = paginator.get_page(page) return render(request,'displayLogs.html',{'users': users,'searchlen':searchlen}) template.html <table cellpadding="0" cellspacing="0" border="0" class="table table table-striped table-hover table-bordered"> <thead> <tr> <th ><center><b>ActivityDate</center></th> <th><center><b>Activity</center></th> <th><center><b>ActorUserPrinicipalName</center></th> <th><center><b>Target1Name</center></th> </tr> </thead> <tbody> <tr class="gradeX"> {% for item in users %} <td>{{item.0}}</td> <td>{{item.1}}</td> <td>{{item.6}}</td> <td class="center">{{item.10}}</td> </tr> {% endfor %} </tbody> <tfoot> <tr> <th ><center><b>ActivityDate</center></th> <th><center><b>Activity</center></th> <th><center><b>ActorUserPrinicipalName</center></th> <th><center><b>Target1Name</center></th> </tr> </tfoot> <div class="pagination" style="border-style:inset;border-width:5px;padding-bottom: 5px"> {% if users.has_previous %} <a class="pagination-action" href="?page=1"> <i class="fas fa-angle-double-left"></i></a> <a class="pagination-action" href="?page={{ users.previous_page_number}}"> <i class="fas fa-angle-left"></i></a> {% endif %} {% for num in users.paginator.page_range %} {% … -
Large PDFs taking exponentially longer time with ReportLab
I am using ReportLab for generating PDF Reports and below is the code for the same. The problem is, for X number of pages, it takes T time, but for 2X pages, it takes a lot more than 2T time. Since I have a need to generate PDFs that may go up to 35000 pages, it is a big hassle. What can I do to circumvent around this issue. from reportlab.platypus import TableStyle, SimpleDocTemplate, LongTable, Table from reportlab.lib.pagesizes import letter class JournalPDFGenerator(object): """ Generates Journal PDF with ReportLab """ def __init__(self, pdf_name, profile_report_id): self.pdf_name = pdf_name self.profile_report_id = profile_report_id self.profile_report = ProfileWatchReport.objects.get(id=self.profile_report_id) self.document = SimpleDocTemplate(self.pdf_name, pagesize=letter) self.story = [] def get_prepared_rows(self): row = [your_mark_details, threat_mark_details] yield row def generate_pdf(self): report_table = LongTable([row for row in self.get_prepared_rows()]) self.story.append(report_table) self.document.build(self.story)