Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python inbuilt HTMLcalendar
How I can display the calendar on certain datetime data which are already saved into the database? I am trying to use python inbuilt HTMLCalendar but yet not found any good tutorial how to use it or which calendar app will be better for this purpose? -
Is having precalculated fields on the database to avoid deep join queries a bad idea?
I have this data model in my application (Django/Rest Framewrok). It mainly lists and operates with Project and Release classes, which has several instances per system affected and multiple phases per instance which have different efforts. I am developing a RESTful API for a frontend, and I'm having trouble with load times when listing all the Projects for a Release, or all the active Projects. I need to go down to the ProjectInstancePhase to get the overall effort for Project o Release elements. Would having precalculated values on the Project or Release objects that update when an dependent object is updated be a bad idea? I know it breaks the normalization of the database, but it would save a lot of time. Think about listing 300 projects with all the related data. I've thought about caching, but I would need to invalidate it often because any change in the related classes would need to be shown. Is threre some ORM trick to lower the load on the database? All the tutorials and examples usually rely on simple data models that seldom reflect real life complex projects so I haven't find this topic covered on them. Thanks a lot. *Listed *Listed … -
Run another task after executing one function successfully Using Celery
I am new to celery module, I want to execute one task after execution of particular function successfully. As I have done following changes in my django app: change settings.py:- import djcelery djcelery.setup_loader() BROKER_URL = 'amqp://rahul:amvarish@127.0.0.1:5672//' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_IMPORTS = ('projectmanagement.tasks',) create tasks.py:- from celery import task @task() def add(x, y): print (x+y) return x + y My view.py:- class Multiply(APIView): def get(self,request): x = request.GET['x'] y = request.GET['y'] try: z= x*y data = {'success':True,'msg':'x and y multiply','result':z} return HttpResponse(json.dumps(data),content_type="application/json") except Exception,e: print str(e) data = {'success':False,'msg':'Error in multiplying x and y'} return HttpResponse(json.dumps(data),content_type="application/json") Now I want my celery task should get call after successful execution of my multiply API.Where should I call my task in between my view function, so that my API response will be independent of celery task execution. -
django - adding a foreign-key's foreign-key filed to the form - unable to save the form
I have the following models. class Category(MPTTModel): name=models.CharField(max_length=75,null=False,blank=False, unique=True) parent=TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class ProductGroup(models.Model): name = models.CharField(max_length=30,null=False, blank=False) category=TreeForeignKey('category.Category', null=False,blank=False) class Product(models.Model): product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False) manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False) product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE,) opening_stock=models.PositiveIntegerField(default=0) I'm using the following model form to create product which works well class CreateProduct(CreateView): model=Product fields=['product_group', 'manufacturer', 'product_type', 'opening_stock'] The product-group table has many rows and hence choosing the right one from the list becomes hard. I'm trying to add an extra field to the top to list all the categories so as to fetch and the corresponding productgroups only in the form. Here's my new code. class CreateProduct(CreateView): model=Product form_class=ProductForm jquery ajax query in product_form.html <script> $("#id_category").change(function () { var category = $(this).val(); $.ajax({ method:'get', url: '/ajax/get_product_groups/', data: { 'id': category }, dataType: 'json', success: function (data) { //alert(data[0].name) $('#id_product_group').empty() $('#id_product_group').append( $('<option></option>').val(0).html('------------') ); $.each(data, function(key, value){ $('#id_product_group').append( $('<option></option>').val(value.id).html(value.name) ); }); } }); }); </script> new url-pattern url(r'ajax/get_product_groups/', GetProductGroups, name='ajax_get_product_groups'), GetProductGroups View def GetProductGroups(request): product_groups=ProductGroup.objects.filter(category__id=request.GET.get('id')) to_json = [] for pg in product_groups: # for each object, construct a dictionary containing the data you wish to return mydict = {} mydict['id'] = pg.id mydict['name'] = pg.name to_json.append(mydict) response_data = json.dumps(to_json) return HttpResponse(response_data, content_type="application/json") The jquery script perfectly fetches the data … -
Background image add in website in Django
I was trying to set background image in my website but in style.css file is not visible it has this error is "Cannot reslove directory 'Images' CSS: background: white url("images/one.png") no-repeat right bottom; index.html: {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}"/> I want to select image from music/images/one.png Thanks is advance -
How to return 401 when Auth Token is missing in Django Rest Framework
I'm finding hard to figure out how to return 401 when the token has been deleted in database for whatever reason. Let me explain. My general settings use SessionAuthentication and TokenAuthentication schemes. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework.filters.DjangoFilterBackend', ), 'DATETIME_FORMAT': '%a, %d %b %Y %H:%M:%S %z', 'DATETIME_INPUT_FORMATS': ['iso-8601', '%Y-%m-%d %H:%M:%S', '%a, %d %b %Y %H:%M:%S %z'], 'DATE_FORMAT': '%Y-%m-%d', 'DATE_INPUT_FORMATS': ['%Y-%m-%d', '%m/%d/%YYYY'], 'PAGE_SIZE': 20 } I have a view for generating the Auth Token, like this: class AcmeObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AcmeAuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.context = {'request': self.request} serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key, 'school': school, 'user': user.id}) obtain_auth_token = BloowatchObtainAuthToken.as_view() My problem is that when token stored in db is gone for whatever reason and clients send the token, I'm getting 403, when I require 401. Looking at the docs this is really cryptic: The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. … -
Testing assumed 404 exceptions
I'm trying to test that a user don't have access to other people's profile. I therefor wrote the following Django client test: user = UserFactory(name='some other user', email='foo@example.com') self.client.force_login(user) response = self.client.get(self.get_url()) self.assertEqual(response.status_code, 404) This works as expected and the test passes. However, what I'm also getting is an unhandled exception error in the console output: Creating test database for alias 'default'... Traceback (most recent call last): File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/views/generic/detail.py", line 117, in get self.object = self.get_object() File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/views/generic/detail.py", line 56, in get_object {'verbose_name': queryset.model._meta.verbose_name}) Http404: No contact found matching the query ---------------------------------------------------------------------- Ran 3 tests in 0.494s OK According to this same problem here. Adding a 404.html in the root template folder should do the trick. Or that for older versions of Django. Adding the following custom Http404 handler: from django.http import HttpResponseNotFound def error404(request): t = loader.get_template('404.html') html = t.render(Context()) return HttpResponseNotFound(html) And calling it with from urls.py: from myapp.views import error_handler handler404 = error_handler.error404 None of these … -
How to convert multiple sheet to csv using python?
I have multiple dataframe which I want to store in the excelsheet, hence I write the following code: NEWExcel=pd.ExcelWriter('K(1).xlsx') NEWT.to_excel(NEWExcel,'Step1_result', index=False) NEWTM.to_excel(NEWExcel,'Step1_Result_by_month', index=False) NEWExcel.save() and it successfully store in my folder and I can open and view the data, but after I create a button in order for me to download the excelsheet: <button onclick="myFunction()">Archive</button> <script>function myFunction(){download('K(1).xlsx');}</script> after I click the button, the file able to download but fail to read the data inside, the following box was shown when I open the file that I download: Anyone have any ideas to help me solve this? because I new to this and hope that can get idea from here. Thanks -
How can I check whether remaining cache or my app's seeing other server?
I am making Swift app and I wanna make a system in my app which upload a image to my Django server. When I selected image and I put "Send" button which send images to the server, I got some errors in Traceback like objc[31510]: Class PLBuildVersion is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x11eab5998) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x11d9a0880). One of the two will be used. Which one is undefined. 2017-06-16 22:05:57.023485 Kenshin_Swift[31510:1318899] [Generic] Creating an image format with an unknown type is an error 2017-06-16 22:05:58.102220 Kenshin_Swift[31510:1319061] [] nw_endpoint_flow_prepare_output_frames [1 127.0.0.1:8000 ready socket-flow (satisfied)] Failed to use 1 frames, marking as failed 2017-06-16 22:05:58.104562 Kenshin_Swift[31510:1319027] [] nw_socket_write_close shutdown(13, SHUT_WR): [57] Socket is not connected ******* response = Optional(<NSHTTPURLResponse: 0x60000023bc80> { URL: http://127.0.0.1:8000/accounts/upload/post } { status code: 404, headers { "Content-Type" = "text/html"; Date = "Fri, 16 Jun 2017 13:05:58 GMT"; Server = "WSGIServer/0.1 Python/2.7.11"; "X-Frame-Options" = SAMEORIGIN; } }) ****** response data = <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Page not found at /accounts/upload/post</title> <meta name="robots" content="NONE,NOARCHIVE"> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } … -
Django OAuth Toolkit: How to authorize with only client credentials?
I am trying to set up OAuth2 authentication system for my Django REST API (using DjangoRestFramework and Django-Oauth-Toolkit). When I set application's authorization grant type as "Resource owner password-based", everything works fine because I provide username and password + client id and client secret. However, for my application, I need to use "Client credentials" authorization grant type, I don't want my application to send username and password all the time in order to get the token, client id and secret should be enough. Here is my setting.py file: OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ], 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'PAGE_SIZE': 10 } When sending the following curl command, I successfully get the access token: curl -X POST -d "grant_type=client_credentials&scope=read" -u"10.10.36.15:C0a0EKxlJF4UgddjqOLE6dpiZYBd9bU7reUDL7UtmecTOT3XPuB5GmyWBi4IgInarF4GsWjgevOTqz9s4xwRTVNv0NH8V41MkKlPLnCq1KcZyjkK7umIMdx1Lc4KB3Ll" http://localhost:8000/o/token/ But when I try to get API resource with the following command, I get response {"detail":"Authentication credentials were not provided."} I can't find the answer. I know it is because permissions.IsAuthenticated setting, but I can't find the alternative. Thanks! -
Cannot populate dummy data against ManyToManyField
I am trying to create test data for a Django model in my project using factoryboy. The data is being generated through Faker except one field, that is a ManyToManyField; a many to many relationship with another builtin model from django.contrib.auth.model named group. class Voucher(models.Model): code = models.CharField(max_length=20, null=True, blank=True, unique=True) is_enabled = models.BooleanField('enable voucher', default=True, help_text='A soft delete mechanism for the voucher.') start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) member_roles = models.ManyToManyField(to=Group, related_name='member_roles') def __str__(self): return "{}".format(self.code) class Meta: verbose_name = 'Voucher' verbose_name_plural = 'Vouchers' This is my model and this is the factory I created to generate dummy data: class VoucherFactory(django.DjangoModelFactory): class Meta: model = 'app.Voucher' code = Faker('first_name') is_enabled = fuzzy.FuzzyChoice([True, False]) start_date = fuzzy.FuzzyDateTime(datetime.datetime.now(pytz.utc)) end_date = fuzzy.FuzzyDateTime(datetime.datetime.now(pytz.utc)) @factory.post_generation def member_roles(self, create, extracted, **kwargs): if not create: return if extracted: for member_role in extracted: self.member_roles.add(member_role) The data gets filled successfully except voucher_member_roles table created against this many to many relationship in Voucher model. I want this table to get populated also. What I am missing? -
How to approach a Selenium / Web crawling / Web scraping App in Python
I want to create a web app for my company that functions like a tool suite for non-technical employees to use. I am not entirely sure how best to approach this and am seeking some advice. The Details(What I may be using): Python Selenium WebDriver, BeautifulSoup, Srapy, Django The idea is to create a variety of methods that can be run by clicking a button and/or inserting content in inputs, and having the tests / functions run and returning the specified results. In my research I learned about some options that might help like pythonanywhere and web2py. But in the end, I wanted to get some advice to see if I was going in the right direction. Or maybe there were some Frameworks or Libraries I should consider. I would appreciate any advice on moving forward with this project. -
Django REST: "Invalid username or password" after specific number of users
I have a user model class User(AbstractUser): place = models.CharField(max_length=64, null=True, blank=True) address = models.CharField(max_length=128, null=True, blank=True) first_name = models.CharField(max_length=64, null=True, blank=True) objects = AuthUserManager() @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) and its viewset class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class ObtainAuthToken(APIView): def post(self, request): user = authenticate( username=request.data['username'], password=request.data['password']) if user: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key, 'user': UserSerializer(user).data}) return Response('Invalid username or password', status=status.HTTP_400_BAD_REQUEST) I can only generate tokens for first 11 users. When trying to generate token for the 12th user, the response is "Invalid username or password". The url.py file is as shown router = DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^login/$',ObtainAuthToken.as_view(), name='login'), ] What is the problem with my code? -
Django - Update multiple models from one view (form-table)
I have this three classes class Product(models.Model): name = models.CharField(max_length=50) class Input(models.Model): idProduct = models.ForeignKey('Product', on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) created_at = models.DateTimeField(auto_now=True) class Output(models.Model): idProduct = models.ForeignKey('Product', on_delete=models.CASCADE) quantity = models.IntegerField() created_at = models.DateTimeField(auto_now=True) And I whant to make a view/form with a table like this | output-quantity->product | product-name | input-quantity->product | List all Product from DB and add the quantity for each product (input or output) Following that I sum up input and output and then subtract them to have a stock record for each product. My problem is I do not understand how I can use three models simultaneously in views / forms -
How to enable download function in django if XLSX file in django folder?
I have multiple dataframe which I want to store in the excelsheet, hence I write the following code: NEWExcel=pd.ExcelWriter('K(1).xlsx') NEWT.to_excel(NEWExcel,'Step1_result', index=False) NEWTM.to_excel(NEWExcel,'Step1_Result_by_month', index=False) NEWExcel.save() and it successfully store in my folder and I can open and view the data, but after I create a button in order for me to download the excelsheet: <button onclick="myFunction()">Archive</button> <script>function myFunction(){download('K(1).xlsx');}</script> after I click the button, the file able to download but fail to read the data inside, the following box was shown when I open the file that I download: Anyone have any ideas to help me solve this? because I new to this and hope that can get idea from here. Thanks -
Python Asyncio in Django View
I would like to make two POST requests from an API on a Django view at the same time. This is how I would do it outside of django. import asyncio import speech_recognition as sr async def main(language1, language2): loop = asyncio.get_event_loop() r = sr.Recognizer() with sr.AudioFile(path.join(os.getcwd(), "audio.wav")) as source: audio = r.record(source) def reco_ibm(lang): return(r.recognize_ibm(audio, key, secret language=lang, show_all=True)) future1 = loop.run_in_executor(None, reco_ibm, str(language1)) future2 = loop.run_in_executor(None, reco_ibm, str(language2)) response1 = await future1 response2 = await future2 loop = asyncio.get_even_loop() loop.run_until_complete(main("en-US", "es-ES")) I'm confused about the event loop. How can I do this inside my Django view? Do I need to use nested functions for this? def ibmaudio_ibm(request, language1, language2): #Asyncio code here -
django.core.exceptions.ValidationError: ["'' is not a valid UUID."]
In an attempt to write object level permissions in Django with the Django Rest Framework, I have bumped into this error (full error log at bottom) django.core.exceptions.ValidationError: ["'' is not a valid UUID."] The error comes from a get query, ship = Ship.objects.get(id=shipID). See file: from rest_framework.permissions import BasePermission from Ships.models import Ship import logging logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) class HasObjectLevelPermissions(BasePermission): def has_permission(self, request, view): if request.method == "GET": return True else: logging.debug("not a GET request") shipID = request.POST.get('id',None) try: ship = Ship.objects.get(id=shipID) # This line is the issue return request.user.userprofile.ship.id == ship.id except: logging.debug("Error in finding ship when checking permissions") return False Below is the Ship model where the UUID is declared. class Ship(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regNum = models.CharField(max_length=100, blank=False, db_index=True) year = models.IntegerField(blank=True) make = models.CharField(max_length=255) length = models.IntegerField(blank=True) beam = models.IntegerField(blank=True) fleet = models.ForeignKey(Fleet) created = models.DateTimeField(auto_now_add=True, db_index=True) def getRegNum(self): return self.regNum Debugging attempts Changing ship = Ship.objects.get(id=shipID) to ship = Ship.objects.get(id="some string") makes the validation error disappear. Changing ship = Ship.objects.get(id=shipID) to ship = Ship.objects.get(id="") makes the validation error disappear. This one is intriguing because an empty string passes the validation. Changing shipID = request.POST.get('id',None) to shipID = request.GET.get('id',None) makes the validation error disappear. I … -
How to update user information using Django Rest Framework?
I am trying to implement authentication by combining Django Rest Framework and Angular, but I am suffering from user information update. Angular sends it to Django with the PUT method, Django accepts the request with View "AuthInfoUpdateView". class AuthInfoUpdateView(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = AccountSerializer lookup_field = 'email' queryset = Account.objects.all() def put(self, request, *args, **kwargs): serializer = AccountSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) At this time, Django accepts the request as below. request.data = {'email': 'test3@example.com', 'username': 'test3', 'profile': 'i am test3'} request.user = test3@example.com And the serializer is implementing as below. from django.contrib.auth import update_session_auth_hash from rest_framework import serializers from .models import Account, AccountManager class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) class Meta: model = Account fields = ('id', 'username', 'email', 'profile', 'password') def create(self, validated_data): return Account.objects.create_user(request_data=validated_data) def update(self, instance, validated_data): insntance.username = validated_data.get('username', instance.username) insntance.email = validated_data.get('email', instance.email) insntance.profile = validated_data.get('profile', instance.profile) instance = super().update(instance, validated_data) return instance I tried to update the user from Angular in such an implementation, and the following response is returned. "{"username":["account with this username already exists."],"email":["account with this email address already exists."]}" It is thought that it is because you did not specify the record to update, but … -
Django WSGI No module named 'site'
I've searched, tried and ran almost every tutorial available to run my django application with apache or even nginx (most of which are over 3 or 4 years old). I've managed to pull through and get parts of everything to work with nginx until I gave up, now I'm trying with apache2, the only error so far I'm having is with wsgi.py, everything else works fine, but running sudo python3 -i /var/www/shinra/shinra/wsgi.py gives me the following error: Traceback (most recent call last): File "/var/www/shinra/shinra/wsgi.py", line 23, in <module> application = get_wsgi_application() File "/home/ubuntu/.local/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'shinra' My wsgi.py is set as … -
how to log all my database changes being done from the application and not only from the django-admin.
I want to log all my database changes being done from the application and not only from the django-admin. how can i achieve that ? Currently we can only see the history in django admin for the changes done through the admin interface. do i need to define signals for this? -
Checkbox to url and url to python in Django
I've only been coding for 2 weeks but I'm trying to learn Django, Python and HTML to make my first website. (Please forgive me if my question is phrased badly, this is my first ever question) I have a model which contains booleans that form a list of checkboxes: class Topic(models.Model): cells = models.BooleanField(blank=True) stainingtechniques = models.BooleanField(blank=True) I then want to generate some information on a page based on the topic the user has chosen from above. I'm not sure how to do it, but one idea i've had is to create a url/slug that contains the topic names, e.g if they check the checkbox for cells but not stainingtechniques then submit, it sends them to /cells. Then at the /cells page, a code checks if cells or stainingtechniques is in the url and displays the info accordingly. My main question is how can i redirect a user to the the slug of "/cells" if the "cells" boolean is true? / checkbox is checked. At the same time could I send them to /cells+stainingtechniques if they check both? (what would i need to add to the models.py, views py, urls py) Then is there a way in python of checking … -
How to request an address within a Django project
this is my view def mydate(request): date = datetime.datetime.strptime(request.GET.get('date'),"%Y-%m-%d") return HttpResponse(data) and i want call this view in another method in the django project how to deal with this problem ? -
<noscript> tags in django - python is not working
I'm totally a newbie to Django-Python. So, whenever I include my tag like this, <noscript> <link rel="stylesheet" type='text/css' href="{% static 'homepage/css/style.css'%}" /> </noscript> Browser doesn't take the code in noscript tag. Whereas, if I load that HTML file independently, there are no issues with the same browser. Tried different ways, <script> var url = "{% static 'homepage/css/style' %}"; </script> Didn't help though! Please push me to pass through this bump! Many thanks! -
Django query: get the last entries of all distinct values by list
I am trying to make a Django query for getting a list of the last entries for each distinct values. I will show an example below as this explanation can be very complicated. Getting the distinct values by themselves obviously in Django is no problem using .values(). I was thinking to create couple of Django queries but that looks to be cumbersome. Is there an easy way of doing this. For the example below. Suppose I want the rows with distinct Names with their last entry(latest date). Name email date _________________________________________________ Dane dane@yahoo.com 2017-06-20 Kim kim@gmail.com 2017-06-10 Hong hong@gmail.com 2016-06-25 Dane dddd@gmail.com 2017-06-04 Susan Susan@gmail.com 2017-05-21 Dane kkkk@gmail.com 2017-02-01 Susan sss@gmail.com 2017-05-20 All the distinct values are Dane, kim, Hong, Susan. I also want the rows with the latest dates associated with these distinct name. The list with entries I would like is the rows below. Notice Names are all distinct, and they are associated with the latest date. Name email date _________________________________________________ Dane dane@yahoo.com 2017-06-20 Kim kim@gmail.com 2017-06-10 Hong hong@gmail.com 2016-06-25 Susan Susan@gmail.com 2017-05-21 -
Can I turn my AngularJS website into Django based website
I've built my site in AngularJS using NodeJS for REST API. Now I want to turn it into a Django website using the same NodeJS rest API. The purpose of change is to move away from Javascript because of SEO reasons. I know webcrawlers are now improved and crawling JS sites and there are other solutions such as prerender.io. We've tried these already kind of figured it out, but I don't want to continue with this anymore. I prefer Django because of the I've worked with it previously for rest API. But I'm not sure it is ideal for serving html pages as good as AngularJS is. So my questions are, Is it possible? Is it ideal? If not what are my other alternatives? Thanks