Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Parallax Not functioning properly : Django
I have downloaded the template : http://keenthemes.com/preview/megakit/ On the index page there is a parallax : <div class="js__parallax-window" style="background: url(img/1920x1080/07.jpg) 50% 0 no-repeat fixed;"> <div class="g-container--sm g-text-center--xs g-padding-y-80--xs g-padding-y-125--sm"> <div class="g-margin-b-80--xs"> <p class="text-uppercase g-font-size-14--xs g-font-weight--700 g-color--white-opacity g-letter-spacing--2 g-margin-b-25--xs">Subscribe</p> <h2 class="g-font-size-32--xs g-font-size-36--md g-color--white">Join Over 1000+ People</h2> </div> <div class="row"> <div class="col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1"> <form class="input-group"> <input type="email" class="form-control s-form-v1__input g-radius--left-50" name="email" placeholder="Enter your email"> <span class="input-group-btn"> <button type="submit" class="s-btn s-btn-icon--md s-btn-icon--white-brd s-btn--white-brd g-radius--right-50"><i class="ti-arrow-right"></i></button> </span> </form> </div> </div> </div> </div> The Parallax image is basically defined with properties in the line : <div class="js__parallax-window" style="background: url(img/1920x1080/07.jpg) 50% 0 no-repeat fixed;"> Now to use the same in django I changed the url of the image to following: <div class="js__parallax-window" style="background: url({% static 'img_events/1920x1080/04.jpg' %}) 50% 0 no-repeat fixed;" > The only problem the parallax is not working properly in this case, the parallax image size should only be 50% but it causes a mismatch in the height and placement of the testimonials and the background image whereas the same code works in the template -
Form did not saving data in to database on submission
I have created a form through which I am trying to submit data into the database but it redirects without submitting data into the database. This can be easily done by using the admin section. forms.py class InvestorsForm(forms.ModelForm): class Meta : model = Investment fields = ['amount', 'rate'] view.py def InvestView(request): if request.method == 'POST': form = InvestorsForm(request.POST, instance=request.user) if form.is_valid(): amount = form.cleaned_data['amount'] rate = form.cleaned_data['rate'] instance = form.save(commit=False) instance.name = request.user print(instance.name) instance.save() return redirect('myinvest') else: form = InvestorsForm(request.POST) args = {'form':form} return render(request, 'investors/form.html', args) models.py class Investor(models.Model): name = models.CharField(max_length=99) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Investment(models.Model): amount = models.FloatField(blank=False) rate = models.FloatField(blank=False) timestamp = models.DateField(default=datetime.now) investor = models.ForeignKey(Investor, on_delete=models.CASCADE) def __str__(self): return str(self.investor) -
How to add ajax to a button that deletes table rows?
I am working on a project in which a delete button deletes the row from table. But the list page gets reloaded everytime I delete an entry. I dont want it to reload. I just want it to remove the entry from list page but I am not good with ajax. Please help me with the code. Thanks in advance. centrelist.html <script> $(document).on('click','#delete',function(){ var a ; a=confirm("Do you really want to delete the user?"); if(a==true){ var url = "{% url 'NewApp:centredelete' pk=1%}" var id = $(this).attr('name') document.location.href = url.replace('1',id); } }); </script> <tbody> {% for c in centres %} <tr> <td>{{ c.name }}</td> <td>{{ c.address }}</td> <td>{{ c.contact }}</td> <td>{{ c.phone }}</td> <td> <a href="{% url 'NewApp:centreupdate' slug=c.slug %} " style="color:black; margin-left:8px"><span class="glyphicon glyphicon-edit"></span></i></a> <a href="#" style="color:black ;margin_left:8px;" id="delete" name="{{c.id}}" ><span><i class="glyphicon glyphicon-trash"></span></i></a> </td> </tr> {% endfor %} </tbody> views.py def ajax_change_status(request, pk): userpr = UserProfile.objects.get(pk=pk) userpr.pk = pk if(userpr.verified): userpr.verified=False userpr.save() return HttpResponseRedirect(reverse('NewApp:userlist')) else: userpr.verified = True userpr.save() return HttpResponseRedirect(reverse('NewApp:mail', kwargs={'pk':pk})) -
How to set default datefield and overwrite it as well as set default default datetimefield and overwrite it, all in the same models.py
Two of my models have datefield and datetimefield. They exist in the same models.py file and I would like to set them to be default upon adding to the database / into existence. More importantly, I would also like to overwrite these fields for generating models to test them. After some research, I started to use pytz and django.utils timezone. The problem I run into are runtime errors when I try to overwrite them using python's built in datetime (using things like timedelta etc). So I tried converting pytz.utc.localize(), but it complained that the datetime objects I fed it was not naive, but then when I go back to my original version, it still threw the Runtime error. I've found many ways to get over this, mainly using things like date = models.DateField(("Date"), default=datetime.date.today) which requires import datetime, but the problem here is that I also want to use DateTimeField and now just DateField. So I would use date = models.DateField(("Date"), default=date.today), but this requires from datetime import date. The imports conflict and the entire thing is messing with me class SomeTime(models.Model): moment = models.DateTimeField(default=???, editable=True, blank=True) class SomeDay(models.Model): date = models.DateField(default=???, editable=True, blank=True) I would like to go m … -
How to fix 'Forbidden 403' error about doccano
for the doccano,when I login on the Edge,it's normal and I can pass verification,but login on the Chrome , Forbidden (403) CSRF verification failed. Request aborted. I install doccan by docker , and try to add new account or rebulit but no use. -
How do I check if two instances of a Django model are the same across a set of attributes and annotate a queryset accordingly?
My app has a model "OptimizationResult", where I store results from mathmatical optimization. The optimization distributes timeslots over projects. I need to indicate whether the current results is different from a recent result, based on a set of attributes (in particularly not the primary key) The attribute optimization_run is a coutner for different runs Project is a ForeignKey to the project. By overwriting the __hash__ and __eq__ functions on the model I can compare the different instances by OptimizationResults.objects.filter(proj = 1).filter(optimization_run =1) == OptimizationResults.objects.filter(proj = 1).filter(optimization_run = 2) . But as I understand __eq__ and __hash__ are not available on the database. How would I annotate the results accordingly? Something like OptimizationResults.objects.filter(optimization_run = 2).annotate(same_as_before = Case(When(),default=False)) -
nonetype' object has no attribute 'decode' error when i upload the image to database in django
i am new to ionic4/angular4.i need to upload the profile pic to database.i wrote code but i don't know whether it is correct or not and when i am uploading it i am getting the above mentioned error. backend he is using Django and backend is correct only other requests is accepting.sorry for the bad indentation. .ts getPicture() { const options: CameraOptions = { quality: 70, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, allowEdit: false, sourceType: this.camera.PictureSourceType.CAMERA, correctOrientation: true, saveToPhotoAlbum: false }; this.camera.getPicture(options).then( imageData => { // imageData is either a base64 encoded string or a file URI // If it's base64 (DATA_URL): this.image = this.sanitizer.bypassSecurityTrustUrl( "data:Image/*;base64" + imageData ); // this.imageURI = imageData; this.profileService .postInfluencerProfile(this.image, null, null) .subscribe( response => { console.log(response); }, (error: MavinError) => { if (error instanceof NotFoundError) { alert("Not found"); } else { console.log(error); } } ); }, err => { // Handle error } ); } service.ts postInfluencerProfile( profilePic: File, name: string, emailId: string ): Observable<any> { const url = "****************"; const apiKey = "************"; const sessionID = localStorage.getItem("sessionID"); const formdata = new FormData(); formdata.append("file", profilePic); console.log(formdata); const loginContext = { user_agent: "Dalvik/2.1.0 (Linux; U; Android 6.0.1; Nexus Player Build/MMB29T)" }; const postData = { … -
Pytest: Fixtures inherited everywhere implicitly
I'm trying run this test and I have some troubles. First, test at 113 line: when I use decorator at 112 line, response.status_code is 200 OK, and test at 133 line get 200 OK too. But I don't need 200 OK response at 113 line and I remove 112 line. What I got? I got 403 response, it's true. But (!) at 133 line I got 403 response too! Decorator with fixture in 132 line doesn't work.Okay, I'm swap tests by position. Move 133 line up above test at line 112. And what I got? 200 OK and 200 OK too in test_miss_permissions_list. Wtf? What I'm doing wrong? Full code: gist.github This is pytest version 4.6.4, registered plugins: celery-4.2.1 pytest-cov-2.7.1 pytest-django-3.4.8 pytest-forked-1.0.2 pytest-xdist-1.29.0 pytest-xdist-1.29.0 def test_miss_permissions_list(api_client): response = api_client.get(uri) assert response.status_code == status.HTTP_403_FORBIDDEN @pytest.mark.usefixtures("list_permissions") def test_list(api_client): response = api_client.get(uri) assert response.status_code == status.HTTP_200_OK -
Is there a general way to define models for different forms (perhaps using inheritance/some other method)?
Is there a way to have a general template like structure (similar to parent-child classes in python), so that we can define functions and processes without writing down relatively similar code multiple times for the different forms? I am working on a project where we want to efficiently design 10-15 forms for a website that users will fill multiple times. The previous architecture was not made meticulously and so, is very clunky (has a lot of code duplication, etc). These forms do not have the same number/name of fields. As an example, there could be a form "student" and another form "flowers", the point here being that the two forms are unrelated. Both of these forms have different fields, student may have "name", "parent", "job of parent", while flowers may have "scientific name" and "medicinal uses". Let's say all fields in student are related to "name" and all fields in flowers are related to "scientific_name". Is there a way to define a parent model, that defines this general structure, and then inherit both of these tables from there (the field names have to be different)? I couldn't figure out a way to do that. -
Storing logging information from a Celery task in Django database
Let's say I have the following function that I want to execute periodically in Celery: import logging import requests log = logging.getLogger(__name__) def spam(): data = fetch_some_data() log.info(f'Fetched {len(data)} data') stuff = [] for item in data: try: response = requests.get(url + item) response.raise_for_status() except RequestException as exc: log.error(f'Error when requesting {item}: {exc}') continue stuff.append(response.text) for item in stuff: do_something(item) log.info(f'Processed {len(stuff)} items') When the accompanying task is executed: from hello import spam @app.task def run(): spam() I would like to see the result of the task stored along with the logged messages. Flower for example is able to show the task progress and history but I would like to add the logging information as separate fields (e.g. "Info Messages" and "Error Messages"). Similarly, if using django-celery-results, it could show the same information in the Django Admin view. What's the best way to achieve this? -
GeoDjango Querying location__within=poly uses Boundaries instead of Actual Shape
I'm using GeoDjango to find all points within a Polygon but it seems to be using the Boundaries (NMW,NME,SME,SMW) to find points. So it brings back results that are outside of the primary shape. polygon = Polygon((18.3825363358424 -33.97219070578159,...) Order.objects.filter(location__within=polygon) I would like the query to bring points inside the shape and not inside its bounds. i.e if * was my shape; I'm getting points in # that seems to suggest that it's querying on the bounds instead of the actual shape. ************** ************** ******######## ******######## ******######## Please tell if I'm doing some wrong? -
High Availability functionality for Django
I have a Django server on IPAddres1 and running on port 8000, and it is connected to the Postgre Database on port 5432. Django has API which is exposed for API calls from the GUI of some WEB application and of course it has some defined cron jobs (used by scheduler and worker). I have many cron jobs some are being run on every 5 minutes, some one per day etc. My ittention is to create Active-Passive or Active-Active Django High Availability architecture where second Django server on IPAddress2 (and also running on the port 8000 connected to the same database) will take over all functionalities which are used by the first Django server. I am really not sure how to setup this kind of environment so any help will be highly appreiciated. I suppose API calls will be available from the second Django server. But I am not sure how cron jobs should take over all jobs which are configured to be run (I have many jobs which are being run on every 5 minutes). Since I am really not so deep expert for Django I will really appreciate all suggestions how to resolve this or links to documention … -
Delete object from database automatically if one field is TRUE
Automatically delete an object from the database if one attribute of the object is TRUE. I've tried Django Signals, but it didn't help. class Question(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) question = models.TextField(max_length=200) answered = models.BooleanField(default=False) def __str__(self): return self.name If I change the "answered" field to TRUE in Admin Panel, then this object must be automatically deleted from the database. -
Python - data from the scraper does not go to the database - Django
The scraper should scrape every blog post on each page Data from the scraper should go to the Postgresql database, where the following statistics will be counted: The 10 most common words along with their numbers under the address /stats The 10 most common words with their numbers per author available under the address / stats / / posts authors with their name available in the address / stats / / available under the address / authors / so far I have focused on the first and second task but I have two problems (one results from the other and vice versa) I do not know how to make the data go to the database and thus I do not know how to do "Counter" Here is my scraper: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from collections import Counter import psycopg2 # from sqlalchemy.dialects.postgresql import psycopg2 url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages … -
Django rest_framework_simplejwt token expiring too fast
With Django I've set up authentication with JWT using the rest_framework_simplejwt app. I believe the default timeout for the access token is 1 day, and even after explicitly configuring it to 1 day in settings.py the token doesn't work anymore after ~10 minutes, and the server returns a 401 response. settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } SIMPLE_JWT = { 'TOKEN_LIFETIME': timedelta(days=1), 'TOKEN_REFRESH_LIFETIME': timedelta(days=7), } I was thinking there might be a problem with the time setting in Django, so in settings.py I put a print of datetime.datetime.now(), which strangely is called twice during startapp, with a 2 hour time difference. Still though if the token lifetime is supposed to be 1 day it should be valid so I'm not sure what's the issue. Any ideas on what the problem might be? Thank you so much in advance. -
Name error context not defined in class based view
I'm very confused by this but it does appear to be my issue. I am getting a name error for context here: class ProjectView(ListView): template_name = 'project_portal/home.html' queryset = Project.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # <-- name error here context['update_category'] = UpdateCategory.objects.all() context['update'] = Update.objects.all() return context What am I doing wrong here? I thought that: context = super().get_context_data(**kwargs) was the definition? -
How to do unit testing properly in django?
Here i am trying to do a testing for the add_course function and i write the test code as below but it failed.This is the first unit testing i have done with django so any help would be great. I got this when i run python manage.py test AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.077s FAILED (failures=1) Destroying test database for alias 'default'... Is there any problem with my view or test file. views.py def add_course(request): if request.method == 'POST': form = AddCourseForm(request.POST or None) if form.is_valid(): course = form.save() course.save() messages.success(request, 'course with title {} added.'.format(course.title)) return redirect('view_course') else: form = AddCourseForm() return render(request, 'add_course.html', {'form': form}) test.py import unittest from django.test import Client class AddCourseTest(unittest.TestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.post('/add-course/') self.assertEqual(response.status_code,200) -
Fullcalendar in Django: TemplateDoesNotExist
I have downloaded the FullCalendar library from FullCalendar and installed it. Views.py def event(request): all_events = Events.objects.all() get_event_types = Events.objects.only('event_type') # if filters applied then get parameter and filter based on condition else return object if request.GET: event_arr = [] if request.GET.get('event_type') == "all": all_events = Events.objects.all() else: all_events = Events.objects.filter(event_type__icontains=request.GET.get('event_type')) for i in all_events: event_sub_arr = {} event_sub_arr['title'] = i.event_name start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") event_sub_arr['start'] = start_date event_sub_arr['end'] = end_date event_arr.append(event_sub_arr) return HttpResponse(json.dumps(event_arr)) context = { "events":all_events, "get_event_types":get_event_types, } return render(request,'classroom/teachers/event.html',context) Urls.py path('calendar', teachers.event, name='calendar'), event.html {% extends 'base.html' %} {% load fullcalendar_tags %} {% block content %} {% calendar %} {% endblock %} <script> $(document).ready(function() { $('#calendar').fullCalendar({ defaultDate: '2016-07-19', editable: true, eventLimit: true, // allow "more" link when too many events events: [ {% for i in events %} { title: "{{ i.event_name}}", start: '{{ i.start_date|date:"Y-m-d" }}', end: '{{ i.end_date|date:"Y-m-d" }}', }, {% endfor %} ] }); }); </script> </html> When I try to run it, I get the error: TemplateDoesNotExist at /shipper/calendar fullcalendar/calendar.html I am doing everything it says in the related question. But something is going wrong. Please Help -
How to fix "Django test setUp() function not creating the django users"?
I am doing the django test cases. Now I have a problem that, user created in django test is not shown in the database created for test. consider my database name as db. from django.contrib.auth.models import User,AnonymousUser from django.test import TestCase,LiveServerTestCase from django.db import connection class machinelist(TestCase): def setUp(self): self.user=User.objects.create_user(username="vishnu***",email="vishnu@clartrum.com",password="vishnu@12345") print self.user.username db_name = connection.settings_dict['NAME'] print db_name t=raw_input("PAUSE") def tearDown(self): print 'd' def test1(self):#view function print "2" The output will print the username vishnu*** and db_name as test_db. But when you observe the database, there is no data. In the code, when the raw_input is executed, I will sign into the mysql server and verified that test_db is created successfully and also the django's tables. But when i checked auth_user table there is no data in it. I am using django 1.11.20 and mysql 5.6.33. Why User is not updating on the database table? -
How can I refresh the queryset when using the browser's "back button?"
I'm using django to build a simple website and in part of it a message can be clicked on and marked as read which also pulls up a detail page with the message title and body. When I press the back button, however, it still leaves it as unread until I refresh the page. I've checked the sqlite file and it does show it as read already (I'm using a simple boolean field), but it doesn't on the page until it's refreshed. I have tried refreshing the page to make sure that the field has the correct value, but I'm not sure where to go from here. The section of my code that takes the user to the message detail page is as follows: def messages(request): user = request.user sent_messages = Message.objects.filter(sender=user.id) unread_messages = Message.objects.filter(recipient=user.id, read=0) read_messages = Message.objects.filter(recipient=user.id, read=1) context = { 'sent_messages': sent_messages, 'unread_messages': unread_messages, 'read_messages': read_messages, } return render(request, 'messenger/messages.html', context) It should automatically send the message to the unread section on the page, but it won't do that unless the page is explicitly reloaded. -
How to return List of QuerySets in graphql query as separate list elements?
The problem I am facing is that I have custom_filter of MyModel which return the list of <QuerySet> like [<QuerySet [<MyModel: xyz>]>, <QuerySet [<MyModel: xyz>, <MyModel: xyz>,<MyModel: xyz>]>] The object type class MyModelNode(DjangoObjectType): class Meta: model=MyModel filter_fields=['id] interfaces = (graphene.relay.Node,) Query class Query(graphene.ObjectType): my_model_items = graphene.List(MyModelNode) def resolve_my_model_items(self, info, **kwargs): my_model_filtered_items = MyModel.objects.custom_filter(kwargs) # my_model_filtered_items holds the list of querysets return my_model_filtered_items How to handle list of querysets. The graphql respone of the query should give a list which have the querysets as elements. [ { //These are from first <QuerySet> "myModelItems":[ { "fieldsIaskedFor":"response" } ] }, { //These are from second <QuerySet> "myModelItems":[ { "fieldsIaskedFor":"resp" }, { "fieldsIaskedFor":"resp" }, { "fieldsIaskedFor":"resp" }, ] }, ] How to get results of different querysets in separate list elements ? The number of <QuerySet> are not fixed. What I have to do to achieve that ?. -
How do I keep one portion of the query string in the URL when going to another page using Django?
I'm creating a web app that does web crawling using Django. After clicking a button the crawling would start. After the crawling process is done, I would get a query string like this ?conditions=cancer&geolocation=&startdate=2019-05-10&enddate=2019-05-11&max=100 I would like to know how can I get the button to auto redirect to the next page while keeping the query string in the URL intact? Preferably without any new packages or new coding language if possible. At the moment, i'm using two buttons one for crawling and one to bring the user to the next page but this method doesn't keep the query string in the URL intact. Thanks! I have tried adding action="/view" into form in crawl.html, however it would just immediately direct the user to the next page and stop the crawling process. Button onclick does the same thing as well. It brings the user to the next page and cuts short the crawling process. in views.py class testcrawl(TemplateView): template_name = 'crawl.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # crawl codes return tweets in crawl.html <form method="GET"> //multiple input fields (not using django forms) <button type="submit" class="btn btn-primary" id="searched">Search</button> -
How can we include datatable inside django admin with search box for retrieving and editing model data
I'm building a website using Django it is my first web site using Django, I want to how I can include datatable inside Django admin with a search box for searching the data from the model. -
Django:How do I put the initial data into the database before Migrate?
Added models from existing code. I'd like to put in the initial data when I migrate the models I've added. python3 -m pip install sqlparse python3 manage.py makeemigations sbimage //I have edited the generated 0002 file. python3 manage.py Migrate image 0002 //Normal operation confirmed. python3 manage.py sqlmigrate thimage 0002 //Normal operation confirmed. However, the data did not enter the table when the database was verified. from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sbimage', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthNumberR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_r', models.CharField(max_length=64)), ], ), migrations.RunSQL("INSERT INTO WarningStateList (id, warning) VALUES (1, 'aaaaaaaaaaaaaaa');"), ] -
Django: Adding databases to DATABASES after startup
So this is ultimately a multi tenancy question about adding new databases for new tenants after the server has started. If i have an array of nodes behind a load balancer, i don't want to have to restart each one after a new tenant is created. Is there a proper dynamic way to add databases that django can use without having to restart the server? Thanks