Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Moving .py files into a folder to tidy up
I have a Django project and I thought it would be good to tidy things up and put all my .py files into a folder. My directory structure initially was the fairly straightforward: [site] ├── [mysite] │ ├── __init__.py │ ├── admin.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── manage.py And now I have moved all of those .py files except __init__.py into the folder py. [site] ├── [mysite] │ ├── __init__.py │ └── [py] │ ├── admin.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── manage.py To ensure that this will work I went through and changed all the references to files to their new location. For example in manage.py I changed: if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") to if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.py.settings") I did this for all the references I could find. But the problem I am facing now is admin.py does not seem to be referenced or imported anywhere and when I make changes to it now it does not cause my test server to restart, so it is obviously disconnected from the project. Is there some way to point Django to the new … -
inserting API data into html via django models
I have created a function that allows me to loop through some data from an API I am using. I have tested this outside the Django model and works as intended. Now I would like to put my code within a Django model so i can use the data within an HTML page. I would like each of the values to be used within html tags as I am creating a table of jira tickets. I have tried to work along with the following: Using APIs within Django and how to display the data from a previous test, which worked. It seems that I cant do it with the function I have created. The below is the function i have created. def get_jira_tickets(): jira_url = 'https://domain.atlassian.net/rest/api/2/search?jql=project=CS' jira_r = requests.get(jira_url, auth=( 'paulb@domain.com', 'API_KEY')) data = jira_r.json() client_name = '[client_name]' client_ID = '[client_ID]' for ticket in data['issues']: ticket_number = ticket['key'] summary = ticket['fields']['summary'] assignee = ticket['fields']['assignee']['name'] status = ticket['fields']['status']['name'] updated = dateutil.parser.parse(ticket['fields']['updated']) ticket_url = 'https://domain.atlassian.net/browse/' + ticket['key'] client = ticket['fields']['customfield_10907'][0]['value'] if status != 'Closed' and client_name in client and client_ID.upper() in client: ticket_dict = { 'ticket_number': ticket_number, 'summary': summary, 'assignee': assignee, 'status': status, 'updated': updated, 'url': ticket_url, 'client_id': client } return ticket_dict … -
Stuck while iterating in the django template
I have this dictionary:- a = {'title': ['Turning a MacBook into a Touchscreen with $1 of Hardware (2018)', 'Supercentenarians are concentrated into regions with no birth certificates', 'Open list of GDPR fines so far'], 'url': ['https://www.anishathalye.com/2018/04/03/macbook-touchscreen/', 'https://www.biorxiv.org/content/10.1101/704080v1', 'https://github.com/lknik/gdpr/blob/master/fines/README.md'], 'type': ['story', 'story', 'story'], 'n': [0, 1, 2]} I passed it into the template. Now, what I want is to get the first 'title' along with the 'type', with its 'url'. I tried the following code:- <ul> {% for i in n %} <br/> {{i}} <li>{{title.i}}</li><br/> <li>{{url.i}}</li> {%endfor%} But couldn't get the desired output. My desired output is:- Title: Turning a MacBook into a Touchscreen with $1 of Hardware (2018) URL: https://www.anishathalye.com/2018/04/03/macbook-touchscreen/ TYPE: story In this way a continuous list of Titles followed by url and type. The output I get is a blank screen. Please help me out. -
Temporarily disabling foreign key constraint checking during bulk_create in django with mariadb backend
I'm attempting to generate large amounts of dummy data programmatically in django and Model2FK references two models, Model1 and Model2 which have more than 10M records. I have been using bulk_create to generate the Model2FK data, but generating 10,000 objects with a batch size of 1,000 takes ~120 seconds. This isn't efficient enough to generate the data in a reasonable amount of time (it currently would take over a week to generate all the data I require). I suspect that this is slow because django or mariadb is performing checks on the foreign keys for each created object, and this is resulting in long lookup times as the database looks up both references to ensure they exist. Since I am generating the data myself I know that the keys exist and would like to skip this step. I've tried using SET FOREIGN_KEY_CHECKS=0; in mariadb to disable foreign key checks, but it seems to only update for that mariadb session, and so doesn't reflect in my django script. Furthermore, I'd like to be able to manage this entirely in my django script if possible so that I do not need to connect to the database each time I need to run … -
google social authentication django rest api
I am setting up a django rest api and need to integrate social login feature.I followed the following link Simple Facebook social Login using Django Rest Framework. # Google configuration SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '****' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '*****' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email'] Above is my settings file configuration of google. After setting up all, facebook authentication working finely.In the case of google authentication , when i uses the access token of same account of which developer account is created(configured in settings.py) is given , social authentication is working.But when i uses access token of different account following error is occuring AuthForbidden at /user/oauth/login/ Your credentials aren't allowed Why it is happening so? Do i need to configure anything in the google developer account? -
Set global exception handler from inside a thread (in Django)
I know about this python bug, which does not allow sys.excepthook to be used from inside a thread. A recommended workaround is to surround the thread's run method with try/except. However, since I am using Django, I am already locked in in Django main thread. So: Is there any way to globally catch exceptions in Django? -
Django in one serialize pull out child objects
This my models class Dictionary(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parentId = models.UUIDField(editable=True, null=True) name = models.CharField(max_length=100) date_create = models.DateTimeField(auto_now=True) date_end = models.DateTimeField(auto_now=False, null=True) class Teacher(models.Model): name = models.CharField(max_length=100) message = models.CharField(max_length=300) status = models.OneToOneField(Dictionary, on_delete=models.CASCADE) this is my urls from django.urls import path from . import views urlpatterns = [ path('get', views.GetViewSet.as_view({'get': 'list'})), ] This is ViewSet class GetViewSet(viewsets.ModelViewSet): MyApiObj = null @property def api_object(self): return namedtuple("ApiObject", self.request.data.keys())(*self.request.data.values()) def get_serializer_class(self): GeneralSerializer.Meta.model = apps.get_model(app_label=self.MyApiObj.app, model_name=self.MyApiObj.object) return GeneralSerializer def post(self, request): self.MyApiObj = self.api_object return self.select_api() def select_api(self): queryset = QueryHelper.select(self.MyApiObj) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Serializer class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None fields = '__all__' My post parameters to django { "app":"leads", "object":"Teacher", "settings":{ }, "data":{ } } answer: [ { "id": 1, "name": "John", "message": "Hi everyone", "status": "e3b86ed4-8794-413b-994c-b1ec0a43eebe" } ] Problem is Dictionary(status) model give me id(uuid) but i need whole object without creating new serializer for Dictionary. i do univeral serializer for all models in my app Try this: class DictionarySerializer(serializers.ModelSerializer): class Meta: model = Dictionary fields = '__all__' class GeneralSerializer(serializers.ModelSerializer): status = DictionarySerializer(required=True) class Meta: model = None fields = '__all__' But it is not good for me because 1) Without other serializer 2) … -
List all the compositions by a specific composer in their profile details page
I want a public page showing the profile of a specific user (so I cannot grab the user id from the logged-in users). I'm not able to select their specific compositions. I am using a custom user model, so that I have a User class and then a Profile class which is linked to the User via OneToOneField (see code below). I also have a Composition class, which is linked to a specific composer via a ForeignKey. I am able to get the details of a specific profile and I'm also able to print out all the compositions (using Composition.objects.all()). My models.py: email = models.EmailField(unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) [...] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) [...] def get_absolute_url(self): return reverse('profile', args=[str(self.id)]) class Composition(models.Model): title = models.CharField(max_length=120) # max_length = required description = models.TextField(blank=True, null=True) composer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def get_absolute_url(self): return reverse("composition-detail", kwargs={"id": self.id}) def __str__(self): return "%s" % (self.title) My views.py: compositions = Composition.objects.filter(composer__id=id) context = { "object_list": compositions } return render(request, "profile.html", context) My urls.py: path('profile/<int:id>/', views.profile_details, name='profile') My template.html: {% for composition in object_list %} <li><a href="{{ composition.get_absolute_url }}">{{ composition.title }}</a></li> {% endfor %} [...] I'm expecting to see the compositions by … -
Retrieve automatically-set values from DRF serializer
I have a model where certain fields are automatically set (timestamp, pk). # models.py class thisModel(models.Model): timestamp = models.DateTimeField(auto_now_add=True) topic = models.CharField(max_length=50) message = models.CharField(max_length=100, default='') Below is my serializer: # serializer.py class thisSerializer(serializers.ModelSerializer): class Meta: model = thisModel fields = ('pk', 'topic', 'timestamp', 'message',) When creating my model, I need only specify the topic and message. data={} data['topic'] = 'paper' data['message'] = 'This is a message' serializer = thisSerializer(data=data) if serializer.is_valid(): # True serializer.save() # I would like to retrieve the PK and Timestamp here The model is created, but I have no way of retieving that model as I have no unique identifier for it. Doing serializer.data['topic'] and serializer.data['message'] returns these fields as intended. Doing serializer.data['pk'] returns an error: KeyError: 'pk' Any idea on how to retrieve these fields? -
How to validate form after putting in custom values in the view?
I am using custom forms where based on a button the user clicks, a different form loads. All of that is working but the form doesn't correctly validate it. I have changed the post form button to run my own ajax script. I pull the data from the form and then I post it along with the value of the certain option that they clicked. I then have the view get the correct form based on that option, and try to see if it is valid or not. The issue is, I can't get the data into the form the way I need for it to check it correctly. Here's the code views.py def step_form(request): if request.method == 'POST': step_type_id = request.POST.get('step_type_id') print(step_type_id) step_type = StepType.objects.get(pk=step_type_id) flow_id = request.POST.get("formData[flow]") print(flow_id) flow = Flow.objects.get(pk=flow_id) print(flow) order = request.POST.get("formData[order]") url = request.POST.get("formData[url]") passed = request.POST.get("formData[passed]") if passed == 'false': passed = False elif passed == 'true': passed = True else: passed = None print(passed) desired_result = request.POST.get("formData[desired_result]") fixture = request.POST.get("formData[fixture]") form_data = {'flow': flow, 'order': order, 'url': url, 'passed': passed, 'desired_result': desired_result, 'fixture': fixture} form = StepForm(step_type_id, form_data) print(form) if form.is_valid(): step = Step.objects.create(flow=flow, step_type=step_type, desired_result=desired_result, fixture=fixture, passed=passed, url=url ) step.save() return … -
How do I create a link to my React app from a Django template
I am in the process of converting some Django apps to React but am having issues with something I thought was simple. I need to link directly to my react blog post app. Back when my blog app was a Django app I would link it like this: <a href="{% url 'posts:details' 'title_of_blog_post' %}" class="alert-link"> Click here</a> Now that my app is a react app, I need to link to the specific blog post without using the full external link. The only way I've been able to link to the app is to use href="{% url 'posts-list' %}", but this just takes me to the landing page of the post app and not the specific post I need to render. App.js class App extends Component { render() { return ( <BrowserRouter> <Switch> <Route exact path='/posts/create' component={PostCreate}/> <Route exact path='/posts/' component={Posts}/> <Route exact path='/posts/:slug' component={PostDetail}/> <Route component={Posts}/> </Switch> </BrowserRouter> ); } } posts.urls.py path('', views.PostListCreateAPIView.as_view(), name='list-create'), re_path(r'^(?P<slug>[\w-]+)/$', views.PostDetailAPIView.as_view(), name='detail'), MySite.urls.py re_path(r'^posts/', TemplateView.as_view(template_name='posts/react.html'), name='posts-list'), path('walking', TemplateView.as_view(template_name='posts/walking.html')), path('api/posts/', include('posts.urls')), Any help you could provide would be much appreciated! -
How to make dropdown list to be appeared in dropdown menu form?
I have made a dropdown menu in django so that a user could select one option and it is working but whenever I click on dropdown menu, all the contents hide itself except the one I hover a mouse on it. How to make all appear so that it shows me?? forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image','payment_method','detail'] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) payment_method = models.CharField(max_length=10, choices=Paymet_choices) profile.html {{p_form|crispy}} -
Is there DRYer to get Detail View information from ForiegnKey and ManyToManyRelationships
I am creating a website which will require lots of detail on the bottom of each instance. I am currently having to write custom implementations for each related instance. Is there a way to write a function which will help me reduce the amount of code i am using? I have tried using getattr on model instances but can't seem to get it to work, perhaps someone can help? This is what i am currently using to pass data into the template. Each time the data dict is reset a new detail section is passed into the template and these are the chunks i would like to modulirise into a method call. def get_detail_fields(self): field_values = list() data = dict() data['headings'] = ['name', 'address', 'number'] for parent in self.parents.all(): data[parent.name] = [parent.name, parent.address.get(), parent.number] field_values.append(('parents', data)) for course in self.courses.all(): if course.find_next_course_instance(): data = dict() data['headings'] = ['session', 'name', 'start_date'] data[course] = [course, course.name, course.start_date] field_values.append(('course', data)) if self.competency: data = dict() data['headings'] = ['name', 'stage level', 'description'] competencies = self.competency.all() for competency in competencies: data[competency.name] = [competency.name, competency.stage_level, competency.description] field_values.append(('Competencies', data)) return field_values And this is what my tempalte is looking like <table> <tr> {% for heading in value.headings … -
Limit amount of foreign keys, each one referring to a day of the week
Let's say I have two models in my app: Car and CarAvailability. class Car(Model): availability = ForeignKey(CarAvailability) class CarAvailability(Model): WEEKDAYS = ( ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday') # ... basically all the days of the week ) day = CharField(max_length=20, choices=WEEKDAYS) What are my options to limit the amount of foreign keys (availability attribute) to a maximum of 7 and make sure of only one per weekday. I don't know if I'm making myself clear enough here, let me know if anything. -
Django view doesn't save model instances but running the functions correctly?
I have a function that process images that are uploaded by users. I made a view that when entered apply the function on the uploaded images. models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.FileField(upload_to = user_directory_path , verbose_name = 'Image') class Processed(models.Model): uploaded_image = models.ForeignKey(UploadedImages,on_delete=models.CASCADE,related_name='processed') analysedimage = models.ImageField(upload_to=analyses_directory_path, verbose_name='analysed Image', blank=True) views.py def AnalysedDetails(request,pk=None): Uimage = get_object_or_404(models.UploadedImages,pk=pk) analysed = models.Processed(uploaded_image=Uimage,analysedimage=main(Uimage.pre_analysed.path)) analysed.save() return HttpResponse("OK") but when i check the admin page to see the model it only saves the uploaded image and doesn't save the processed one and when I check the directory i find that only the uploaded image field is saved. I tried analysed=models.Processed(uploaded_image=Uimage.pre_analysed,analysedimage=main(Uimage.pre_analysed.path)) but it returns Cannot assign "": "Processed.uploaded_image" must be a "UploadedImages" instance -
How to set cookies on Client Server in CORS request
I have a React Frontend Client at foo.com and a Django Backend server at bar.com.I am using Django's Session Authentication for logging in.When the client at foo.com makes a CORS login request to bar.com ,the Backend server successfully sends the Set-Cookie Headers(csrftoken and sessionid) in the response but these cookies are set for Domain bar.com i.e for Backend domain.I want these cookies to be set for my Frontend domain i.e foo.com.How can I achieve this? -
why the response so slowly when first request to drjango server
Now i make prediction using tensorflow inside django .And there is one issus when i test.When django server is started,and the response from django server is so slowly when first request,it is hunted by sessison.run.And it is fast when make second,third request,how to fix this issue about first request slowly. I tried to add some tf app function ,but it doesn't work genfun=get_batch_generator(data_list) fo = codecs.open("./result", "w","utf-8") for input_data,y_true in genfun: y_pred = sess.run(pred, feed_dict={'text_left:0': input_data['text_left'],'text_right:0': input_data['text_right']}) for y in y_pred: fo.write(str(y[1])+"\n") sess are defined the outer file when run python manage.py runserver command class NNmodel(object) : ins_ = None @classmethod def instance(cls) : cls.ins_ = cls.ins_ if cls.ins_ else NNmodel() return cls.ins_ def __init__(self): self.flag_ = False self.pred = None self.sess = None def load(self,nn_model_file) : if self.flag_ == True : return self.flag_ = True gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3) self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options,allow_soft_placement = True)) with tf.gfile.FastGFile(nn_model_file, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) self.sess.graph.as_default() tf.import_graph_def(graph_def, name='') # Get graph graph = tf.get_default_graph() self.pred = graph.get_tensor_by_name("dense_9/Softmax:0") the response is so slow when make first request -
Django transaction.commit_on_success rolling back even though exception is not raised
I have a scenario where a transaction.commit_on_success() is being rolled back after the code block finishes execution without raising error. The DataBaseError is being caught and retried explicitly within that transaction. If there are 10 requests coming in simultaneously, for the one's where the retry executes, rollback happens for those objects even though a voucher is served in the first retry. Assuming I have brand, amount and currency already, below is my code base def get_coupon_code(brand, currency, amount, retry=4) try: qs = VoucherCode.select_for_update().filter( brand=brand, currency=currency, amount=amount ).values('id', 'voucher_code').order_by('id')[:1] try: return qs[0] except IndexError: return None except DatabaseError as err: if retry and hasattr(err, 'args') and err.args[0] == 1213: retry -= 1 time.sleep(4) return self.get_coupon_code( brand=brand, currency=currency, amount=amount, retry=retry) else: raise err try: with transaction.commit_on_success(): object = Coupon.objects.create(brand=brand) voucher_code = get_coupon_code(brand, currency, amount) object.voucher_code = voucher_code return object except Exception as error: raise MyCustomException() -
How to allow rendering view only if accessed via iframe from specific domain in Django?
I have a Django view which I want to be accessible only from an iframe inside a webpage inside domain.com. I don't want it to be accessible directly nor from any other domain. Here are a list of use cases: If user tries to access view directly in my website, a Forbidden error is thrown. If user goes to www.domain.com and the webpage contains an iframe pointing to my view, the content of the view is displayed. If user tries to copy same iframe code and paste it on another webpage from a different server, even if the server is pretending to be www.domain.com, he gets a forbidden error. Any other hacky way rather than use case 2 gets forbidden error. Is it possible to do this? How can it be done? I know of the X-Frame-Options: allow-from https://example.com/ header, but first, this doesn't block direct access, second is it hacker safe? -
Send mass emails with multiple tasks or one task with time.sleep?
I want to write a Python Script in Django with Celery that is responsible for sending a lot of emails. Let's say about 300 emails. Once I trigger this function it should send this emails to specific customers. Since I have some rating limits (5 emails/second) on my email provider who is responsible for sending this emails I need to send the emails in chunks. Is it better do create a separate task for every email chunk like this: for chunk in chunks: send_five_emails.apply_async(countdown=1) @task def send_five_emails(...): pass Or is it better to create one task with a sleep function inside it: send_emails.delay() @task def send_emails(...): for chunk in chunks: time.sleep(1) send_five_emails() -
Django: best practice to define dependencies between your settings?
I'm using environment variables for my settings in Django. For example: EMAIL_BACKEND = os.environ['DJ_EMAIL_BACKEND'] EMAIL_HOST = os.environ.get('DJ_EMAIL_HOST') EMAIL_HOST_USER = os.environ.get('DJ_EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('DJ_EMAIL_HOST_PASSWORD') EMAIL_PORT = os.environ.get('DJ_EMAIL_PORT') As you can see here, EMAIL_BACKEND is required, not the 4 other variables. However, when EMAIL_BACKEND has a value like dummy (e.g to test in local), the 4 other variables are not required to be set. However, I'd like to find a clean way to conditionally force to set these 4 variables according to the value of the first one. A dummy version could be something like: EMAIL_BACKEND = os.environ['DJ_EMAIL_BACKEND'] if EMAIL_BACKEND == "django.core.mail.backends.smtp.EmailBackend": EMAIL_HOST = os.environ['DJ_EMAIL_HOST'] EMAIL_HOST_USER = os.environ['DJ_EMAIL_HOST_USER'] EMAIL_HOST_PASSWORD = os.environ['DJ_EMAIL_HOST_PASSWORD'] EMAIL_PORT = os.environ['DJ_EMAIL_PORT'] else: EMAIL_HOST = os.environ.get('DJ_EMAIL_HOST') EMAIL_HOST_USER = os.environ.get('DJ_EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('DJ_EMAIL_HOST_PASSWORD') EMAIL_PORT = os.environ.get('DJ_EMAIL_PORT') Can you think of a less verbose, more organised way to do this? Thanks. -
How can I rename a field in django using an input field
I have an app that allows people to renames files. Issue is I haven't got much idea on how to do this yet. I want a user to be able to hover over the file of choice, then type in a new file name and then click enter and then that name they enter would rename that file. HTML: {% for video in videos %} {% if video.active %} <div class="folder"> <div class="folder-settings-tool" onclick="folderSettings(this)"> <!-- CHANGE COLOUR OF THE SETTINGS COG TO WHITE --> <img src="{% static 'public/image/icons/settings-work-tool.svg' %}"> </div> <div class="folder-settings"> <div class="title-change"> <p class="title-rename">RENAME</p><input type="text" name="title"> </div> <div class="archive"> <p class="archive-text"> ARCHIVE </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> <div class="make-final"> <p class="archive-text"> MAKE FINAL </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> <div class="downloadable"> <p class="archive-text"> DOWNLOADABLE </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> </div> <a href="{% url 'public:file_detail' model='video' pk=video.pk %}"> <div class="folder-text"> <p>VIDEO</p> </div> <div class="image"> <img src="{% static 'public/image/icons/folders.svg' %}"> </div> <div class="folder-info"> <div class="folder-title"> {{ video.title }} </div> <div class="folder-date"> <p><span class="folder-created">Created</span> {{ video.created }}</p> </div> </div> </a> </div> {% endif %} {% endfor %} Models: class Folder(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='%(class)ss_created', verbose_name … -
How can I see user information other than the logged-in user in Django?
I'm using Django 2.2 and PostgreSQL. After logging in, the user has a page where they can see other users' information. However, all users' login information appears on the page. I want to see information from other users except him. How can I do that? templates/neighbor.html {% csrf_token %} {% if neighbor_list %} {% for neighbor in neighbor_list %} <div class="card border-left-success py-2" style="background-color: rgb(240,240,240);"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-left"> <strong><p><a href="{% url 'store:neighbor_detail' neighbor.user.username %}">{{neighbor.user.first_name}} {{neighbor.user.last_name}}</a></p></strong> <p><strong><i class="fa fa-user"> : </i></strong>{{neighbor.user.username}}</p> <p><strong><i class="fa fa-envelope"> : </i></strong>{{neighbor.user.email}}</p> <p><strong><i class="fa fa-phone"> : </i></strong>{{neighbor.phone}}</p> <p><strong><i class="fa fa-fax"> : </i></strong>{{neighbor.fax}}</p> {% if neighbor %} <p><strong><i class="fa fa-map"> : </i></strong>{{neighbor.neighborhood}}, {{neighbor.avenue}}, {{neighbor.street}}, {{neighbor.block}}, No.{{neighbor.number}}, Kat.{{neighbor.storey}}, {{neighbor.district}}/{{neighbor.province}}</p> <p>{{neighbor.profile_image}}</p> {% endif %} </div> </div> </div> </div> </div> {% endfor %} {% endif %} store/views.py from store.models import StoreOtherInfo def neighbor(request): neighbor_list = StoreOtherInfo.objects.all() return render(request,'store/neighbor.html',{"neighbor_list":neighbor_list}) -
how do i generate a chart from this data
im setting up a system that records users who visit different pages on my site, but i have failed to plot a graph that shows how many visit which pages i have managed to capture the different users in the database but now retrieving them and plot them on the graph depending on what page they have viewed is an issue '''reports.py''' get_client_ip(request, action="Analytics page", description="User accessed the analytics page.") return render(request, "search.html", {"view":"reports", "home_page":home_page, "specie_page":specie_page, "login_page":login_page, "advanced_page":advanced_page, "sign_up_page":sign_up_page, "activation_page":activation_page, "specie_download":specie_download, "analytics_page":analytics_page}) ''' i expect it to plot a graph from the results but i dont know how to do it -
Django Nested Views
I'm developing an internal application and I would like to be able to nest my views to keep everything nice and organized. I plan on doing this by keeping different parts of the page in their own HTML files with their own Views (separate sidebar and navbar, separate charts, etc). views.py from django.shortcuts import render from django.views.generic import TemplateView import Recall.data_logger.models as DLM class ReportHome(TemplateView): template_name = 'data_logger/index.html' class SelectorSidebar(TemplateView): template_name = 'data_logger/sidebar.html' def get(self, request, *args, **kwargs): companies = DLM.Company.objects.order_by('company_name').all() return render(request, self.template_name, {'companies':companies,}) index.html <html> <head></head> <body data-gr-c-s-loaded="true"> {% include 'data_logger/navbar.html' %} <div class="container-fluid"> <div class="row"> {% include 'data_logger/sidebar.html' %} <!-- This is the part I need help with--> </div> </div> </body> </html> sidebar.html <div class="col-sm-3 col-md-1 sidebar"> <ul class="nav nav-sidebar"> {% for company in companies %} <li><a href="#">{{ company.company_name }}</a></li> {% endfor %} </ul> </div> I understand that by just using {% include 'data_logger/sidebar.html' %} it's just loading the HTML and bypassing SelectorSidebar, how do I direct it through the View?