Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to use request.POST as a dictionary input?
In my django project, I collect membership data by HTML form and insert them into the database. There are the code samples: models.py class member(models.Model): name = models.CharField(max_length=100,blank=True,null=True) gender = models.CharField(max_length=10,blank=True,null=True) profession = models.CharField(max_length=100,blank=True,null=True) views.py: def manage(request): form_values = request.POST.copy() form_values.pop('csrfmiddlewaretoken') # I don't need it. add_member = member(**form_values) add_member.save() If HTML form input is: Rafi, Male, student Database gets in list format: ['Rafi'], ['Male'], ['student'] who can I solve this? -
Django clear form field after a submit form. form create in forms.py
I tried a lot but could not find a solution I also try javascript but could not find a solution def postPage(request, id): post = Post.objects.get(pk=id) showcomment = Comment.objects.filter(postby = id) form = commentForm() form = commentForm(request.POST) form.instance.postby = post if form.is_valid(): form.save() form = commentForm() redirect('postpage', id=post.sno) context = {'post':post, 'form':form, 'showcomment':showcomment} return render(request, 'blog/postpage.html', context) form = commentForm() Only the field shows blank But the data is submitted when we refresh HTML File form action="." method="POST"> {{form}} {% csrf_token %} <input type="submit"> </form> -
TypeError at /featuredcases/ cannot unpack non-iterable bool object
i wanna add a query in which i wanna show only those records which are approved or whose approval is true every time i add this line it showsthe above error kindly help 'case': approvedcases.objects.get(approvedcases.approval == True), -
I am making a Quora Clone with Django with . How do pass question primary key to url to add answer
Here my Answer model is linked with a foreign key to Question model. I am able to add questions but I am unable to figure out how add answers for a particular question. I am using Class-Based views. Please can anyone tell me what to write in AddAnswerView I am attaching code here models.py class Question(models.Model): author = models.ForeignKey(User,on_delete='CASCADE') question = models.CharField(max_length=1000) time_added = models.DateTimeField(default=timezone.now()) def get_absolute_url(self): return reverse('home') class Answer(models.Model): question_url = models.ForeignKey(Question,on_delete='CASCADE') answered_by = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) time_created = models.DateTimeField(default=timezone.now()) upvotes = models.IntegerField(default=0) answer = models.TextField() views.py class AddQuestionView(LoginRequiredMixin,CreateView): model = Question fields = ['question'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class AddAnswerView(LoginRequiredMixin,CreateView): model = Answer fields = ['answer'] def get(self, request, *args, **kwargs): q_id = self.kwargs['pk'] return render(request, 'clone/answer_form.html', {"q_id": q_id}) def post(self, request, *args, **kwargs): urls.py path('addQuestion/',AddQuestionView.as_view(),name='add-question'), -
Building a web app with Python, should I use DJANGO, FLASK or DASH?
I'm an amateur Python programmer and I'm attempting to build a web app which tracks the performance of actors at the box office but unsure about how to best approach it. I've spent the week reading up on Django, Flask and Dash but I still don't know which one I should use to build it. I like how straight forward Dash is, but a key element that I want to include in the app is a search bar through which the user can search for a specific actor and land on a page which has the box office results of that given actor. I understand that Dash is less convenient for this type of search functionality, so I think that I may need to incorporate it into a Django or Flask project (perhaps using django-plotly-dash?) but I don't know if this is necessary or how I might go about doing this. I already have all the data saved locally in CSV files, so it's really just a matter of presenting it. Anyway, any advice would really help (and save me lots of time I'm sure)! Thanks! -
how to get subjects from course using foreign key in django with the help of one to many relationship
I am working on website having different courses each course have some no of subjects basically i am using one to many relationship i am having problem in getting output in desired way (assume i have 2 subjects i.e. cse and mechanical engineering, cse have 2 subjects html and css similarly mech engineering have 2 subjects thermo and fluid mechanics) i want output like this CSE html css mechanical engineering thermo fluid mechanics kindly suggest me what is wrong in my code thats why i cant get desired output` def course(request): courses = Course.objects.prefetch_related('subjects_set') context = {'courses': courses} return render(request, 'test.html', context) def subjects(request, course_id): subjects = Subjects.objects.filter(course_id=course_id) return render(request, 'test.html', {'subjects': subjects}) this is my view.py {% for course in courses %} {{course.title}} {% for subjects in course.subject_set.all %} {{subject.title}} {% endfor %} <br/> {% endfor %} this my html file class Course(models.Model): image = models.ImageField(upload_to='course/', blank=True) title = models.TextField(blank=True) def __str__(self): return self.title class Subjects(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) image = models.ImageField(upload_to='subject/', blank=True) title = models.CharField(max_length=255) def __str__(self): return self.title this is my model ` -
Reverse for 'django.contrib.sitemaps.views.sitemap' with keyword arguments '{'section': 'evergreen'}' not found
Django 3.0.8 Python 3.8.0 Could you help me cope with sitemap sections? class EvergreenPostSitemap(Sitemap): changefreq = 'monthly' priority = 0.8 protocol = 'https' def items(self): return Post.published.all().exclude(category_title="news") def lastmod(self, obj): return obj.updated class NewsPostSitemap(Sitemap): changefreq = 'hourly' priority = 0.9 protocol = 'https' def items(self): return Post.published.filter(category_title="news") def lastmod(self, obj): return obj.updated class AuthorSitemap(Sitemap): changefreq = 'yearly' priority = 0.5 protocol = 'https' def items(self): return Author.published.all() def lastmod(self, obj): return obj.updated sitemaps = { 'evergreen': EvergreenPostSitemap, 'news': NewsPostSitemap, 'aurhors': AuthorSitemap, } urlpatterns = [ path('sitemap.xml', views.index, {'sitemaps': sitemaps}), path('sitemap-news.xml', views.sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('sitemap-evergreen.xml', views.sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('sitemap-aurhors.xml', views.sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] Environment: Request Method: GET Request URL: http://localhost:8000/sitemap.xml Django Version: 3.0.8 Python Version: 3.8.0 Installed Applications: ['admin_aux', 'images.apps.ImagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'posts', 'sidebars', 'general', 'categories', 'marketing', 'home', 'authors', 'taggit', 'cachalot', 'widgets', 'code_samples', 'hyper_links', 'polls', 'applications', 'videos', 'quotations', 'languages', 'people', 'arbitrary_htmls.apps.ArbitraryHtmlsConfig', 'tweets', 'vk_posts', 'facebook_posts', 'instagram_posts', 'email_subscriptions', 'social_share', 'assessments', 'django_bootstrap_breadcrumbs'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, … -
RuntimeError: Model class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
So, I upgraded my django version from 1.11 to 2.2 and ran python manage.py runserver. I get the error: Model class <project_app_name>.models.<model_name> doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Obviously, all apps are registered including the <project_app_name>. So, the answers that try the solution of adding the app to the installed apps don't apply here. Any help would be appreciated -
Finished django course, WHAT NEXT? [closed]
I have just finished a Django course and I can finally build a real-world app, however, I'm currently very confused about what should I learn next. I think of learning the REST framework but I don't know what can I build after learning it or how it will help me So should I learn Rest Framework or learn more Django stuff or AJAX? thanks -
Queuing jobs in Django using clock, worker
I am going through this article : https://devcenter.heroku.com/articles/python-rq Where in Queuing the job I am unable to understand in what part of my Django file should I include the following code: A. Also is the count_words_at_url(url) the function that I want to be periodic. import requests def count_words_at_url(url): resp = requests.get(url) return len(resp.text.split()) B. Should I put the following code in my settings.py? from rq import Queue from worker import conn q = Queue(connection=conn) C. What part of Django should I enqueue the funciton call? from utils import count_words_at_url result = q.enqueue(count_words_at_url, 'http://heroku.com') My procfile is correct. clock.py: from apscheduler.schedulers.blocking import BlockingScheduler sched=BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def refresh: #....function which i want to repeat every 15 seconds. #Some Piece of code sched.start() I am stuck at this issue since 3 days, any help will be really thankful. -
Create a debug version for a web server that utilizes Django
I need to debug a server that I didn't create. In order to do that I had to make a debug copy of the server (I made a copy of the server's directory and gave it a new name). I also need to define a URL for that debug version (the address I got is the address of the non-debug server). How do create that URL? Is there a location in the code wherein I define the URL? Is there a file such as index.html of which I need to make a copy with a different name? -
How to build a LaTeX live preview of a textarea which contains a python expression using sympy in Django?
I would like to create a form on my site built with Django, that would ask for a python expression, with a live LaTeX previewing of this expression. Let me precise the steps : The expression would initially be a string (TextField) I convert it in a python math expression with the eval() sympy function. Simpy converts it in LaTeX code with the latex() function. get a live previewing of this LaTeX code (with MathJax ?) Any idea ? -
How do you stream video files to the browser using python?
What I am trying to achieve I am trying to "pseudo stream" multiple videos (using the mp4, ogg or webm vidoe format) to a wide variety of browsers using Python as my back-end. I have an index.html with a gallery of images. The purpose is that when an image is pressed the user gets redirected to a video stream specifically related to that image. Pseudo streaming means that I send only a part of the video at the time, so the user does not have to download the video to watch it but can watch however much they want or whatever part they want. I am guessing HTML5 is best for this since it has built is functions for pseudo streaming. What I have tried / found I have tried setting up a flask website that uses my index.html file but actually streaming the video itself does not work. When I googled this issue multiple solutions comes up... for cameras only using openCV which I am not at all familiar with. I successfully set up the website with Django as well but since I am unable to create some form of pseudo streaming function it too is completely useless. The … -
Join two querysets in django but keeping their order?
class WordListView(ListView): model = Word template_name = 'vocab/home.html' context_object_name = 'words' current_user = self.request.user if current_user.is_authenticated: all_words = Word.objects.filter(user=current_user) studying_words = all_words.filter(currently_studying=True).order_by('?') other_words = all_words.filter(currently_studying=False).order_by('?') return studying_words|other_words else: return Word.objects.none() I tried using .join() and | and union, but none of them work because they're either outdated or doesn't keep the random order. Is there any way to do this? -
Attrs not being rendered in HTML using Django-Tables2
Based on the [Django-Tables2 documentation][https://django-tables2.readthedocs.io/en/latest/pages/column-attributes.html], it seems pretty straightforward to add custom attributes to any column, and I did so: class NameTable(tables.Table): name = tables.Column(attrs={"td":{"class":"my-class"}}) office = tables.Column(attrs={"td":{"class":"my-class2"}}) class Meta: attrs = {"class": "paleblue"} template_name = "django_tables2/bootstrap.html" fields = ("name", "office") I pass my data to this class by means of: data = [{'name':'John','office'='L.A'},{'name':'Michael','office'='N.Y.'}] table = NameTable(data) template_name = 'planning/index.html' return render(request, template_name, {"table": table}) Unfortunately, even if the data is rendered correctly in the table, I cannot find the tags I have previously defined (my-class and my-class2) in any point of the HTML source code after rendering (which of course means CSS is not being applied correctly). What am I missing? -
Comment mettre une application REST Api react native + django sur google play?
I am creating a REST APi mobile application with native React and Django. I would like to know if it is possible to create an "apk" with a rest api application. Knowing that I am making http requests from react to django. I don't understand or I don't know if it's possible? Is it possible to host a rest api application? If so how do we do with react native and django? Thanks you ! -
Django: can we create a variable using set in django template?
Can we create a variable using set in django template? like this {% set isfound = False %} if so I am getting this error Invalid block tag on line: 'set', expected 'empty' or 'endfor'. Did you forget to register or load this tag? -
How can I override **kwargs value?
I have a dynamically generated dictionary. Example: kwargs = { 'name':'Rafi', 'amount': 530} This dictionary will be used as function parameter. But in case I need to change the value of kwargs['amount'] often (not always). def printer(**kwargs): print(kwargs) for taka in range(100,kwargs['amount'],100): printer(**kwargs) #Each time (5 time) Output should be: { 'name':'Rafi', 'amount': 100} kwargs['amount']-=100 printer(**kwargs) #Output should be: { 'name':'Rafi', 'amount': 30} I need to make some data entry, where until the balance is more than 100 ( kwargs['amount'] > 100 ), every times $100 will be recorded. Kindly, help me to figure it out. (Working with django.) -
"GET /reset_password/ HTTP/1.1" 302 0
How i access below url before login i want to access url before login ....................................................................................................................................................................................................................... template.html <a class="m-auto" href="/reset_password">Forgot password</a> urls.py path('reset_password/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset.html"), name="reset_password"), -
How to redirect users trying to access Private Page to custom page instead of login page?
Need Help, I was able to set up login system on Wagtail website using django-allauth. I have two groups Free and Premium. By default when user registers they are assigned "Free" group role. When they log in they have access to Free articles. When they try to access Private articles meant for "Premium" group they are redirected to wagtail login page. Is there any way to redirect logged in free group users to custom page instead of login page? -
how do I make a model field's value be assigned to a variable and it should belong to the person logged in
I am building a services app using django and I am using stripe. The problem is that the logged in user is given a price quote and so he or she has the option to click on the price quote which will lead them to the test stripe payments page. everything works such as making the charge and etc but how do i get that specific number (price quote) which the user clicked on? that is an integer model field but I want it to be assigned to the stripe charge amount when a user clicks on it. the green button is clicked but I want that integer (quote price) of the user making the request (user is a foreign key in the quotes model) to be assigned to the stripe charge amount how would that happen? -
Caching Generic Related Object in Django
I want to cache generic related objects while querying objects of a model. class Foo(models.Model): name = models.CharField(max_length=50) related_content_type = models.ForeignKey(ContentType, related_name='foo_related', on_delete=models.CASCADE) related_object_id = models.CharField(max_length=255) related = GenericForeignKey('related_content_type', 'related_object_id') So when I run following commands, the actual related object is not directly fetched from the database, but checked whether it is available in cache. foo = Foo.objects.get(name='foo') foo.related -
How can I create a session key in `setUpTestData` for use in subsequent tests?
I want to establish a persistent sessionkey for use in all my tests: class TestAuthorisedViews(TestCase): @classmethod def setUpTestData(cls): # Establish the client and log in for all views cls.client = Client() cls.client.force_login(user=cls.standard_user) # Set a session key cls.session['mykey'] = 1 cls.session.save() However, when used in tests I get a KeyError: def test_view_url_accessible_by_name(self): print('session', self.client.session['mykey']) Results in KeyError: 'mykey' My understanding from the docs is that this is because a new SessionStore is created every time this property is accessed. Do I understand this correctly or is something else going on here? How can I create a session key in setUpTestData for use in subsequent tests? -
django - load secrets, passwords & dynamic settings from cloud
I want to load some values in my Django settings file at the time of application startup, dynamically from the cloud, namely : Database password Database IP address Is it a good practice to add python code to the settings file to retrieve these values from the cloud. I believe these will be loaded only once, at the time of application startup i.e. they won't adversely affect the performance of my application. For instance : # ~ settings.py ~ # retrieve data from the cloud, directly in the settings file db_password = some_cloud_library.get_my_secrets() db_ip_address = some_cloud_library.discover_db_ip() # configure the database with these dynamic values DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', ... 'PASSWORD': db_password, 'HOST': db_ip_address, } } -
VS code getting IndentationError while trying to add a new line to my python-django function
i use VS code for my python - django projects , i know the error should be with my editor , but alos my vc code editor work with 4 space (tabs) as python expected , but still getting this error IndentationError: unindent does not match any outer indentation level while tried to add a new line to my function @login_required def createCityForm(request): cities = CityModelFormset(queryset=City.objects.none()) if request.method=='POST': cities = CityModelFormset(request.POST) if cities.is_valid(): for form in cities: obj = form.save(commit=False) if form.is_valid() and form.cleaned_data!={}: obj.save() return redirect(reverse_lazy('add-info:addi-info')) return render(request,'country/add-city.html',{'cities':cities}) i know my question is duplicated , but i didnt find any solution for vs code editor , thanks for helping