Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Testing With Selenium
After running this test the user data persists and is in the default table. My understanding was that a test table would be created and all data in it would be destroyed after the tests run. Can someone explain to me why the data is going to the default table? import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.support.wait import WebDriverWait class AccountSignUpTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Chrome() def tearDown(self): self.browser.close() def test_can_a_user_signup(self): self.browser.get('http://localhost:8000/accounts/signup/') email = self.browser.find_element_by_name('email') email.send_keys('test@example.com') first_name = self.browser.find_element_by_name('first_name') first_name.send_keys('FName') last_name = self.browser.find_element_by_name('last_name') last_name.send_keys('LName') password1 = self.browser.find_element_by_name('password1') password1.send_keys('xxxxxx') password2 = self.browser.find_element_by_name('password2') password2.send_keys('xxxxxx') timezone = Select(self.browser.find_element_by_name('timezone')) timezone.select_by_value('America/Phoenix') self.browser.find_element_by_id('submit').click() assert self.browser.title == 'Login' if __name__ == '__main__': unittest.main() -
Django: Having problem when calculate differences between today's date and date in database
I have an object name Device with 'trandate' attribute. I want to get differences between today's date and database date. And then calculate the number of devices where the device's inactive_days is greater than 31. Here is my code. todays_date = datetime.now() trandate = request.GET.get('devc_trandate') inactive_days = todays_date - datetime(trandate) inactive_devices = Cust.objects.values('name').annotate(inact_devc_count = Count('devc',filter=Q(inactive_days__gte=31))) But I got an error. an integer is required (got type NoneType) -
NoReverseMatch at /customer/1/list/
I am trying to make a upload function in the form, but when I click upload button, it throws error: NoReverseMatch at /customer/1/list/ Here is code in the view def list(request,pk): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) form.cId = pk; newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('list')) # render(request, 'list.html', {'documents': documents, 'form': form}) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return Here is code in the url url(r'^customer/(?P<pk>\d+)/list/$', Views.list, name='list'), please help -
Why can't I modify third party packages?
This must have happened just recently, within the last day or two, but for some reason my modifications to third-party packages under site packages in my virtualenv do not affect the app at all. I can delete critical parts of a package and my app still works as usual. I only have one virtualenv so not sure what else the project would be depending on. Does anyone know why this might be happening? I can add more info if needed. -
django no module name
i am trying to set up a project and every time i runserver it tells me there is no module named 'views' that i am trying to import to the urls.py of the same folder! from django.conf.urls import url import views urlpatterns = [ 'products.views', url(r'^$', ProductListView.as_view(), name='product_list') i tried every possible solution and nothing worked until i launched the command tree on windows powershell and it gave me this: ├───carts │ ├───migrations │ └───__pycache__ ├───ecommerce │ └───__pycache__ ├───newsletter │ ├───migrations │ └───__pycache__ ├───orders │ ├───migrations │ └───__pycache__ ├───products │ ├───migrations │ └───__pycache__ ├───statics │ └───our_static │ ├───css │ ├───img │ ├───js │ └───psd └───templates ├───carts ├───orders ├───products └───registration which is odd because the views folder that i want to import should be under products but apparently it can not see it i tried setting the PYTHONPATH but that didn't work either everything i do it either tells me the module doesn't exist or throws a weird syntax error in the views file print formset.is_valid() which i figured is totally unrelated does anyone have an explanation for this? thank you. -
Handling two objects does not exist errors
I have a get_context_data function for my DetailView Inside this function, I try to query two results. However, if the object does not exist then I get an error. If both objects don't exist, then I get two errors. I know I can do a try-except, but what if both conditions fail what is a more elegant way of catching both errors? I know I can do two try-except, but is there a better way specifically where I can make it so that the query does not return an object does not exist, instead it returns a default value? Here's what I have: def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) try: vote = Voting.objects.filter(user_id=self.request.user, choice__question=self.kwargs.get('pk')) context['voted'] = vote[0].choice.id context['follower'] = .object.user.followers.get(follower=self.request.user) except: context['voted'] = 0 return context -
How do I import a JSON file into SASS variables, in a Django project?
I have a json file that describes defines some color constants, like: { "red": "#ff0000" } I'd like to import this file into a SASS file, in a Django project, so I don't have to duplicate the file. How might I do that? -
Schema for bulk creation api
I'm using django-rest-framework to build my API in which supports bulk create/update. In these cases, the api will accept a list of object like [ {"foo":"bar"}, {"foo":"bar"} ] The code I'm using to allow bulk apis is just a small modification to add option many=True for serializer if the data is a list. It's like: def create(self, request, *args, **kwargs): many = isinstance(request.data, list) if many: serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) self.perform_bulk_create(serializer) else: ................ But the problem is the schema generated keep detecting my request body just the single model only. Is there any config to make DRF schema generator knows that it will accept a list type? Any help will be appreciated. Thanks for your time. -
Best way to add comment field in Django Rest Framework
Currently I am creating a site that I would like users to be able to comment in. I am just having a hard time wrapping my head around how to model the models so to speak. The way I have it, I believe that the comments aren't connecting themselves to the main article, I believe they just get added and sunk into the abyss. What's the best way to connect the models? Should I just not have a separate model for the comments? This is more of a hypothetical question than a how to code question. Currently this is the way I have it. class Comments(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) comment = models.CharField(null=True, blank=True, max_length=5000) date = models.TextField(blank=True, null=True) username = models.CharField(null=True, blank=True, max_length=20) class Article(models.Model): title = models.CharField(max_length=250, primary_key=True) content = models.TextField(blank=True, null=True) usedfor = models.TextField(blank=True, null=True) url=models.CharField(max_length=200, null=True) username = models.CharField(max_length=50, null=True, blank=True) article_programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE, blank=True, null=True) score = models.IntegerField(max_length=5, null=True, blank=True) article_framework = models.ForeignKey(Framework, on_delete=models.CASCADE, related_name="article_framework", blank=True, null=True) date_added = models.IntegerField( max_length=10, blank=True, null=True) article_comments = models.ForeignKey(Comments, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title -
how to update django database entry based on request.POST data
I am working with django on updating my QueryDict into the database. This QueryDict comes from a request.POST method via the html interface. <QueryDict: {'csrfmiddlewaretoken': ['foo'], 'student_attend': ['Select', 'Select', 'Select'], 'final_student_pk': ['7', '8', '12'], 'submit_student_attendance': ['']}> What I was attempting to do, was to update my database object student_attend column based on the final_student_pk value. Meaning to say, I was attempting the below: if 'submit_student_attendance' in request.POST: to_update = AddNewSchedule.objects.filter(pk=request.POST['final_student_pk']) to_update.update(student_attend=request.POST['student_attend']) This does do the job of updating my AddNewSchedule database table. However, it only updates the last pk item. (ie: it only updates item 12 in the database). It does not loop through pk 7 and pk8 to update the database as well. How can I resolve this? -
Communication between django and java script using path
This is my views.py function from django.shortcuts import render, redirect from django.views.generic import TemplateView from rest_framework.response import Response from rest_framework.views import APIView # Create your views here. def index(request): """ View function for home page of site. """ # Render the HTML template index.html with the data in the context variable return render( request, 'index.html', ) from .models import Survey from .forms import SurveyForm #from django.http import HttpResponseRedirect class form(TemplateView): """ View function for form.html """ # Render the HTML template index.html with the data in the context variable template = 'form.html' def get(self, request): form = SurveyForm() return render(request, self.template, {'form': form}) def post(self, request): form = SurveyForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.user= request.user data.save() form = SurveyForm(); return redirect('form'); text = 'There was an error.' args = {'form':form, 'text':text} return render(request, self.template, args) class ChartData(APIView): authentication_classes =[] permission_classes =[] def get(self,request,formate=None): articles = dict() for survey in survey.object.all(): if not survey.major in articles: articles[survey.major] =1 else: articles[survey.major] +=1 articles =sorted(articles.items() , key =lambda x:x[1]) articles = dict(articles) data ={ "articles_labels":articles.keys(), "articles_data":articles.values() } return response(data) def survey_article_list(request): return render(request,"plotly.html",{}) this is my plotly.html <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="row"> <div id="articles" style="width:1400px;height:800px;"></div> </div> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> … -
How to create pdf using Django's ReportLab using sample Json Data
I need to create a pdf using python's Reportlab (just the list of samples as a content). How do I go about doing it Below are my models class Patient(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=35) phone = models.CharField(max_length=18) email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) class Embryo(models.Model): name = models.CharField(max_length=45) analysis_result = models.Charfield(max_length=10) created_at = models.DateTimeField(auto_now_add=True) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) Here's a sample I need to create a PDF of the below with the below contents: [ { "name": "embryo_1", "analysis_results": "46,XX" }, { "name": "embryo_2", "analysis_results": "47,XY,+21" }, { "name": "embryo_3", "analysis_results": "46,XY" }, -
django update database based on pk [on hold]
I apologise for not being explicit in my earlier question. Below is the updated question. I am working with django on updating my QueryDict into the database. This QueryDict comes from a request.POST method via the html interface. <QueryDict: {'csrfmiddlewaretoken': ['foo'], 'student_attend': ['Select', 'Select', 'Select'], 'final_student_pk': ['7', '8', '12'], 'submit_student_attendance': ['']}> What I was attempting to do, was to update my database object student_attend column based on the final_student_pk value. Meaning to say, I was attempting the below: if 'submit_student_attendance' in request.POST: to_update = AddNewSchedule.objects.filter(pk=request.POST['final_student_pk']) to_update.update(student_attend=request.POST['student_attend']) This does do the job of updating my AddNewSchedule database table. However, it only updates the last pk item. (ie: it only updates item 12 in the database). It does not loop through pk 7 and pk8 to update the database as well. How can I resolve this? -
Save mutiple images without bound form
I have one form with one file field like this: <label for="file">Photos: <input type="file" id="file" name="file" accept="image/*" multiple></label> So I don't render a form from form.py but I have a model for that form I manually render in my HTML page. In my view I can use request.FILES.getlist('file') to access all the images but How can I bound the <input type='file'> field to my model models.FileField() field and save the images? Is that possible? -
How do I create a Django web application with an HTML/CSS/JS frontend and a Django and Flask backend?
I have never made a web application using the combination of Django, Python, and Flask. I am not sure how to even get the directory sorted out. I was going to just write the front end in HTML/CSS/JS and then figure out how to connect everything to it, but I don't even know where to begin. Here is the prompt: Build a Django application that will connect with 3 external weather services and provide an average temperature for a given zip lat/lon. The Django application should have a single url route that takes in a latitude, longitude, and a list of external services to filter on. The acceptable filters will be ‘noaa’, ‘weather.com’, and ‘accuweather’. For example: if the user sends in ‘noaa’ and ‘accuweather’ in the filter list, then only those two services will be used to calculate the average temperature for the given lat/lon. In order to connect with the 3 external APIs, we have created a simple Flask application that you will run and connect to. This will prevent you from having to actually integrate with three external providers. Please access this application and view the readme here: https://github.com/otterlogic/mock-weather-api Although this is a simple application, please use … -
Adding J Query datepicker to django forms
So I've been trying to add a J Query datepicker (calendar thing) to my django code for about a week, and I'm getting nowhere. I've been trying soo many tutorials to no avail- so I'm needing some help. I'm pretty new to django, but my job needs me to add this datepicker to a site. Here's my forms.py: class AnimalForm(forms.ModelForm): class Meta: model = Animal fields = ['animal_id','species_strain','dob', 'dod', 'sex', 'source', 'parents', 'labloc', 'notes'] widgets ={ 'dob':forms.DateInput(attrs={'class':'datepicker'}), "dod":forms.SelectDateWidget(empty_label=("Choose Year", "Choose Month", "Choose Day")), "parents":SelectMultiple(), } Here's my views.py: def addAnimal(request): if request.method =='POST': aform = forms.AnimalForm(request.POST,request.FILES) aform.fields['dob'].widget.attrs.update({'class': 'datepicker'}) aform.fields['dod'].widget.attrs.update({'class': 'datepicker'}) if aform.is_valid(): animal = aform.save(commit=False) animal.save() return redirect('/input') else: aform = forms.AnimalForm() return render(request, 'lab/input.html', {'aform':aform}) And finally, here's my html template: <!-- date picker html --> <script src="jquery-3.3.1.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function() { $( "id_dob" ).datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, }); } ); </script> I hope this makes sense, according to the tutorials I've been doing, everything should be right but I honestly don't know. I admittedly don't know what I'm doing, but I don't have a choice lol. I'm trying to … -
How to write json to Google Cloud Driver
I am using django for logging. Here is what I have so far: from google.cloud import logging client = logging.Client.from_service_account_json('file.json') client.setup_logging() LOGGING = { 'version': 1, 'handlers': { 'stackdriver': { 'level': 'INFO', 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': client, }, }, 'loggers': { 'datadocs': { 'handlers': ['stackdriver'], 'level': 'INFO', 'propagate': False, }, } } And here is how it shows up in Google Stackdriver: Is there a way to actually add additional key/value fields instead of just having the json message be formatted as text? Can any fields be added except for the "message". How would this be done? -
channels without channel layer or any other free hosting
I have a project in django 2.0 nad django-channlels 2.0 which I need to host I followed the documentation and I was able to run channels on localhost along with redis but when I hosted on pythonanywhere,it showed it doesnot support websocket, so then I hosted on heroku,but there they were asking for verification of credit card info which i dont have to run redis.Are there additional hosting website whre I can rrun redis erver for free Or is it poosible to implement channels without channel_layer and redis.My code is working perfectly fine on local host but can't host online for free. class PageConsumer(WebsocketConsumer): def connect(self, **kwargs): self.accept() channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("admin", {"type": "analytics.admin_message", "message": "plus"}) def disconnect(self, close_code): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("admin", {"type": "analytics.admin_message", "message": "minus"}) its corresponidng receiver class ChatConsumer(WebsocketConsumer): def connect(self, **kwargs): self.accept() async_to_sync(self.channel_layer.group_add)("admin", self.channel_name) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)("admin", self.channel_name) def analytics_admin_message(self, something): if something["message"] == "plus": self.send(text_data=json.dumps({ 'message': "plus" })) else: self.send(text_data=json.dumps({ 'message': "minus" })) def receive(self, text_data): print("data hai bhyi", text_data) text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } -
Django change BooleanField value after DateField expires
I would like to be able to automatically set suspended to False (if is True, of course) when end_suspension_date passes by (and therefore if it exists). models.py class Profile(models.Model): suspended = models.BooleanField(default=False) start_suspension_date = models.DateField(null=True, blank=True) end_suspension_date = models.DateField(null=True, blank=True) # ... other fields Is there any way to do this without third-party apps? I thought of defining a function inside the model (but I don't see much sense in doing so): def end_suspension(self): if date.today() >= self.end_suspension_date: self.suspended = False start_suspension_date = None end_suspension_date = None else: # do nothing... -
Django Oauth Toolkit: Obtain Token Using Code As Opposed to Curl
How do I obtain a token from Django OAuth Toolkit using my Django code instead of via a call to curl? I've registered an application and have a client ID/secret. Also, my authorization grant type is authorization-code not password. All the example I have seen use password and changing password to authorization-code yields a 400 error. Any help would be greatly appreciated. Thanks. -
Propagate entries in django/python logging
I am looking for a practical explanation of the difference between having propagate be true or false. Here is the current logger I have: LOGGING = { 'formatters': { 'default': { 'format': '[%(asctime)s] %(filename)s:%(lineno)d@%(funcName)s [%(levelname)s] %(message)s', }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'default' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'default' }, }, 'loggers': { 'app': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', 'propagate': True, }, } } If I set propagate to False, what would happen in the above case? Would it still send messages to mail_admins, or would it only use the first item? What exactly would be the difference between the two settings, beyond just what it says in the django docs here: https://docs.djangoproject.com/en/2.1/topics/logging/. -
How to unit test that a function has been decorated?
I have a view that is decorated like this: @check_has_permission('is_manager') def view(): pass How do I unit test that view to make sure check_has_permission is getting called with 'is_manager'? -
How can I get accurate weather and location data in Geodjango?
I have been working for my thesis project. Here I have to collect exact location (latitude, longitude, and place name), weather data (weather status, humidity, pressure etc.) and affective responses (comfortable-uncomfortable etc). For love in Django, I have chosen Geodjango. I have to use OSM as the layer. If you could give me advice on how to pack these all together. Then it could have been a great help to me. Thank you so much. -
'QaDetail' object has no attribute 'object'
I have detail view in my app, where user can post his answer on question. But I get an error: 'QaDetail' object has no attribute 'object' In the traceback, an error is here: context = super(QaDetail, self).get_context_data(**kwargs) here is my django view (cbv): class QaDetail(generic.DetailView, generic.FormView): template_name = 'qa/qa_detail.html' context_object_name = 'question' model = Question form_class = AnswerForm def get_success_url(self): return reverse('qa:qa_detail', kwargs={'pk': self.get_object().id}) def get_context_data(self, **kwargs): context = super(QaDetail, self).get_context_data(**kwargs) context['answers'] = self.get_object().answers.all() return context Below is my unit test: class AnswerCreateTests(LoggedInTestCase): def setUp(self): super(AnswerCreateTests, self).setUp() def test_status_code(self): self.assertEqual(self.response.status_code, 200) def test_create_answer(self): obj = AnswerFactory(text='this is answer') response = self.client.post(reverse('qa:qa_detail', kwargs={'pk': obj.id})) self.assertEqual(response.status_code, 200) self.assertContains(response, 'this is answer') an error here: AttributeError: 'QaDetail' object has no attribute 'object' -
Django-jet missing argument: 'sortable_by'
I am using a theme Django-jet and Django 2.1 when trying to change any model I get this error: _init__() missing 1 required positional argument: 'sortable_by' Is there any way to fix it without a downgrade?