Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React With Django, Not auto refreshing with npm run dev
I've built React components in Django, but every time I update my react component I have to run npm run dev + reload the browser to see the changes. How can I fix this issue to make react refresh automatically after changes? I have --watch on my script but still doesn't work package.json { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.12.3", "@babel/preset-env": "^7.12.1", "@babel/preset-react": "^7.12.5", "babel-loader": "^8.1.0", "react": "^17.0.1", "react-dom": "^17.0.1", "webpack": "^5.4.0", "webpack-cli": "^4.2.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.12.1", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "react-router-dom": "^5.2.0" } } index.js import App from "./components/App"; App.js import React, {Component} from "react"; import {render} from "react-dom"; import HomePage from "./HomePage"; class App extends Component { constructor(props) { super(props); } render() { return ( <div className="center"> <HomePage/> </div> ); } } export default App; const appDiv = document.getElementById("app"); render(<App />, appDiv); Homepage.js import React, {Component} from 'react'; class Homepage extends Component { constructor(props) { super(props); } render() { return ( <div> test 1 </div> ); } } export default Homepage; -
Django how to install Requierements text even if it does not exist in a project that you downloaded from GitHub?
I have downloaded a Django Project from Github but The project does not include a requirement text. So I can not install the packages and I can not start it. Is there any way to solve this problem? -
How to add "variable.html" in include function of Django instead of hard coding the template name?
I want to render different HTML templates for each product detail view. I used this url pattern path('product-detail/<int:pk>', views.ProductDetailView.as_view(), name='product-detail'), Here is the view for product detail view class ProductDetailView(View): def get(self, request, pk): product = Product.objects.get(pk=pk) return render (request, 'esell/productdetail.html', {'product':product}) Here is the detail template <h2>{{ product.title }}</h2> <hr> <p>Product Description: {{ product.description }}</p> I want different detail templates to show for different product clicking on the product url. I tried to name the different html templates based one their id name like this "1.html" and tried to add include function to render different templates based on their id name like this {% include '{{product.id}}.html' %} But it's not working. Is there any way to add variable like that in include or other way to complete this task? -
Python, django: I would like to put objects within the 'input' tag or 'select' tag on form. ..in order to transfer the objects to the booking_form
User put some information in the price inquiry form and hit the calculate button User is moved to the page displaying the price with the information user put in the form If user is happy with the price and wanna go ahead booking, then there is a booking button Once user hit the booking button, user can access to the booking_form On the booking form, User can see the information he put before, so he does not have to put them in again. -- this is what I wanted So far, I did successfully upto no 4. I would like to transfer the information user put and the price calculated into the booking_form. but input tag does not allow {{ object }} inside tag. To make you understood better, I have attached the 'price_detail.html' below. {% extends 'basecamp/base.html' %} {% block content %} <form action="{% url 'booking_form' %}" method="post"> {% csrf_token %} <div class="container py-4 py-sm-7 text-center"> <div class="py-md-6"> <h1 class="text-light pb-1"> The price : $ {{ price }} </h1> <p class="fs-lg text-light" >{{ flight_date }} | {{ flight_number }} | {{ suburb }} | {{ no_of_passenger }} pax</p> <br/> <button class="btn btn-warning" type="submit">Book now</button> </div> </div> </section> {% endblock … -
How can I add a Bootstrap class to a 'Button' element through javascript?
I am trying to create a button with the Bootstrap class = "btn btn-info" through javascript, but instead of creating a styled Button, it just creates a plain HTML button. Code let diva = document.createElement('div'); diva.class = 'fluid-container'; let newContent = document.createElement('textarea'); newContent.id = 'content'; newContent.class = 'form-control'; newContent.rows = '2'; newContent.style = 'min-width : 100%'; newContent.placeholder = 'Add argument infavor'; //button = <button class="btn btn-info col-5" type="button" id="against"><b>Against</b></button> let btn = document.createElement('button'); btn.type = 'submit'; btn.class = 'btn btn-info'; btn.innerHTML = "Submit"; diva.appendChild(newContent); diva.appendChild(btn); parent = document.getElementById("addingArgumentArea"); parent.appendChild(diva); I am trying to use btn.class but it's not working. Why is this not working because the same method worked for the textfield created above and what is the solution? -
ModuleNotFoundError: No module named 'commentdjango'
I am trying to add comments to posts on my blog on this guide https://pypi.org/project/django-comments-dab/ but when doing migrations I get this error, thanks for any help -
Checking the input of the selected time in the time interval
I have a time interval from 09: 00 to 23: 00. I choose the time of 13: 00. How do I determine if this time is included in my interval? -
how to add data into 2 separate tables in django rest_framework
I have created a simple API and want to add data into 2 tables. For example I have created 2 tables in models.py class User(models.Model): userid = models.AutoField(primary_key=True) name = models.CharField(max_length= 100) age = models.IntegerField() gender = models.CharField(max_length=100) class Meta: db_table = 'user' class Detail(models.Model): address = models.CharField(max_length=100) phone = models.IntegerField() details = models.CharField(max_length=100) class Meta: db_table = 'detail' serializers.py class UserSerializer(serializers.ModelSerializer): name=serializers.CharField(required=True) age = serializers.IntegerField(required=True) gender = serializers.CharField(required=True) class Meta: model = User fields= '__all__' class DetailSerializer(serializers.ModelSerializer): address = serializers.CharField(required=True) phone = serializers.IntegerField(required=True) details= serializers.CharField(required=True) class Meta: model = Detail fields= '__all__' suppose I am passing the json data as { "name" : "abc", "age" : 20, "gender" : "Male", "address" : "xyz", "phone" : 454545454, "details" : "lorem epsum" } is it possible to insert data into both the tables?. name, age & gender should be inserted into User table & and address , phone & details into Detail table. I have tried many things hence I have nothing to show in views.py -
Create dynamic graphene arguements class
Just started using graphene for my backend, I have three types of users, they all have username, email and user_type as required, but the rest are optional. Instead of of creating 3 mutation classes, I'm trying to implement just one generic CreateUser Class My current implementation is: class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: # user = graphene.ID() email = graphene.String(required=True) password = graphene.String(required=True) user_type = graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() street_address = graphene.String() city = graphene.String() state = graphene.String() zip_code = graphene.Int() date = graphene.Date() ... #so on def mutate(self, info, email, password, user_type, **kwargs): user = CustomUser.objects.create( username=email, email=email, user_type=user_type, password=password, ) ... # code where I use kwargs return CreateUser(user=user) QUESTION: Is there a way to create the class Arguments: dynamically at runtime? -
Optimal coding in django
I have been asked which of the following methods is more optimal? I want to show the best-selling and latest products to users.In method A, I query the database twice. In method B, I only query product models once, and in the template, I use filters to display the best-selling and newest. Is the second method more logical and better than the first method? I have been asked which of the following methods is more optimal? I want to show the best-selling and latest products to users.In method A, I query the database twice. In method B, I only query product models once, and in the template, I use filters to display the best-selling and newest. Is the second method more logical and better than the first method? A : def home(request): create = Product.objects.all().order_by('-create')[:6] sell = Product.objects.all().order_by('-sell')[:6] return ... B: def home(request): products = Product.objects.all() return ... my template: for sell: {% for product in products|dictsortreversed:'sell'|slice:":8" %} -------------------- for create : {% for product in products|dictsortreversed:'create'|slice:":8" %} -
Django AJAX form and Select2
I am rendering a form on to my site with AJAX (view below) def add_property_and_valuation(request): """ A view to return an ajax response with add property & valuation form """ data = dict() form = PropertyForm() context = {"form": form} data["html_modal"] = render_to_string( "properties/stages/add_property_and_valuation_modal.html", context, request=request, ) return JsonResponse(data) The form and modal render on button click with the following JQuery code: $(".js-add-property").click(function () { var instance = $(this); $.ajax({ url: instance.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#base-large-modal").modal("show"); }, success: function (data) { $("#base-large-modal .modal-dialog").html(data.html_modal); } }); }); The issue I am having is that I am trying to use Select2 and because the form is being rendered after the DOM has loaded Select2 isn't working. Does anyone have a way to work around this? Watch for the DOM to change and enable Select2? Many thanks -
How to run an asynchronous curl request in Django rest framework
How to run an asynchronous curl request in Django rest framework. The request should be running background. my code is like: def track(self, appUserId, appEventName, appEventData): asyncio.run(self.main(appUserId, appEventName, appEventData)) async def main(self, appUserId, appEventName, appEventData): async with aiohttp.ClientSession() as session: tasks = [] task = asyncio.ensure_future(self.sendData(session, { "userId": self.appUserIdSandbox if (self.sandBoxEnabled == True) else appUserId, "eventName": appEventName, "eventData": appEventData })) tasks.append(task) task_count = await asyncio.gather(*tasks) async def sendData(self,session, appEventData): response = {} payload = json.dumps(appEventData) headers = { "Authorization": self.__authKey, "Cache-Control": "no-cache", "Content-Type": "application/json", } async with session.post(self.__apiUrl, headers=headers, data=payload) as response: result_data = await response.json() return response -
Can you containerize different django applications belonging to a single project in different docker containers?
So basically, I have three different modules or apps in a single django project - These are registration application (registers the user), login application (login), status application (retrieves the data and displays the currently online users). I use redirects to redirect from one template to another such that the registration page will redirect to the login html page and so on. I have kept all the html files in a template folder. I have a common project for all these applications. I want to containerize each of these applications in to a single container, such that I would have three different containers but I am having troubles in understanding how the redirects would work? As these applications are interacting with each other, how would I be doing this? I would implement the databae on AWS or GCloud. -
How to add multiple language to Django project?
I am adding a second language to my Django website but when I chose the second language nothing changes. settings.py # provide a list of language which your site support LANGUAGE_CODE = 'en-us' LANGUAGES = [ ('en', 'English'), ('ar', 'Arabic'), ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # List where django should look into for django.po LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale'), ] urls.py from django.conf.urls.i18n import set_language from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from django.conf import settings urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('admin/', admin.site.urls), path('', include('company.urls')), path('', include('core.urls')), path('', include('movement.urls')), path('', include('warehouse.urls')), path('setlang/', set_language, name='set_language'), path('', include('maintenance.urls')), path('', include('reporters.urls')), path('', include('accounts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html {% load i18n static %} {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <div class="btn-group"> <button type="button" class="btn dropdown-toggle dropdown-icon" data-toggle="dropdown"> <i class="fa fa-language"></i> </button> <div class="dropdown-menu" role="menu"> {% for language in languages %} {% if language.code != LANGUAGE_CODE %} <a class="dropdown-item" href="{% url 'set_language' %}" class="dropdown-item" data-language-code="{{ language.code }}"> {{ language.name_local }} </a> {% endif %} {% endfor %} </div> </div> I also run these command py manage.py … -
Django: migrate subapp model.py file
My issue is the following. How to migrate a the models in models.py file that is not the automatically generated with django-admin startapp appname I have made a simple directory that illustrates my issue: example_app ├── app.py ├── models.py ├── tenants │ └── tenant1 │ ├── models.py │ └── tenant1_views.py ├── tests.py └── views.py so what I want is to migrate what is inside of tenant1.models.py I have not found any clue on how to achieve this, does anyone know? -
VScode autocomplete not working after using sshfs to mount a directory inside the workspace
I’m using VScode to develop a Django web application on the next environment: • OS and Version: Windows 10 • VS Code Version: 1.52.2 • Python Extension Version: v2021.5.842923320 • Remote – SSH Version: v0.65.4 From my Windows laptop, I work on an Ubuntu 20.04 VM using the Remote – SSH plugin, So I have configured a python3.9 virtual environment with Django3.2 and others python packages. Also, I have pylint installed and all works as expected. The issue arises when I mount a folder inside the application media folder (inside the workspace) from another station through sshfs. What happens is that autocomplete stops working and when y press Clr+Space I just get a loading message. Note that this folder that I mount through sshfs is very big more than 1 TB with many files including python scripts and also I note that even when I close the VScode I cannot unmount this folder because the fusermount said that the folder is used by some process (I guess is the VScode process inside the VM). After all, if I don’t open the VScode I'm able to mount and unmount this folder without a problem. I have also excluded this media folder … -
"Ran 0 tests in 0.000s"
I writed a test for my app's project django in my app folder. When i want to run test file give a error . please help to solve this problem. my file test name in my app is '' my code in temp_tests_file file: from django.test import TestCase from .models import Author,Book from MyProj.forum.tests import SimpleTest import datetime class Author_Tests(TestCase): def setUp(self): obj1 = Author.objects.create(first_name='Brayan',last_name='Trisi',date_of_birth=datetime.date(2005, 5, 12),date_of_death=datetime.date(2020, 5, 12)) obj2 = Author.objects.create(first_name='Rayan',last_name='Blair',date_of_birth=datetime.date(2000, 5, 12),date_of_death=None) obj3 = Author.objects.create(first_name='Mahmoud',last_name='Sameni',date_of_birth=datetime.date(1995, 8, 13),date_of_death=None) obj4 = Author.objects.create(first_name='Alex',last_name='Denizli',date_of_birth=datetime.date(1500, 8, 20),date_of_death=datetime.date(1990, 1, 1)) def test_is_alive(self): br = Author.objects.get(first_name='Brayan') ra = Author.objects.get(first_name='Rayan') ma = Author.objects.get(first_name='Mahmoud') al = Author.objects.get(first_name='Alex') self.assertFalse(br.is_alive()) self.assertTrue(ra.is_alive()) self.assertTrue(ma.is_alive()) self.assertFalse(al.is_alive()) def test_get_age(self): br = Author.objects.get(first_name='Brayan') ra = Author.objects.get(first_name='Rayan') ma = Author.objects.get(first_name='Mahmoud') al = Author.objects.get(first_name='Alex') da = datetime.date.today() self.assertEqual(da - ra.date_of_birth, datetime.timedelta(days=7694)) self.assertEqual(br.date_of_death - br.date_of_birth, datetime.timedelta(days=5479)) self.assertEqual(da - ma.date_of_birth, datetime.timedelta(days=9429)) self.assertEqual(al.date_of_death - al.date_of_birth, datetime.timedelta(days=178738)) class Book_Tests(TestCase): def setUp(self): obj1 = Author.objects.create(first_name='Brayan',last_name='Trisi',date_of_birth=datetime.date(2005, 5, 12),date_of_death=datetime.date(2020, 5, 12)) obj2 = Author.objects.create(first_name='Rayan',last_name='Blair',date_of_birth=datetime.date(2000, 5, 12),date_of_death=None) obj3 = Author.objects.create(first_name='Mahmoud',last_name='Sameni',date_of_birth=datetime.date(1995, 8, 13),date_of_death=None) obj4 = Author.objects.create(first_name='Alex',last_name='Denizli',date_of_birth=datetime.date(1500, 8, 20),date_of_death=datetime.date(1990, 1, 1)) ### ob1 = Book.objects.create(title='Bitcoin',author=Author.objects.get(first_name='Brayan'),summary='Anything about bitcoin',date_of_publish=datetime.date(1998, 12, 5)) ob2 = Book.objects.create(title='litecoin',author=Author.objects.get(first_name='Rayan'),summary='Anything about litecoin',date_of_publish=datetime.date(2012, 8, 1)) ob3 = Book.objects.create(title='Teter',author=Author.objects.get(first_name='Mahmoud'),summary='Anything about Teter',date_of_publish=datetime.date(2015, 8, 1)) o4 = Book.objects.create(title='Doge',author=Author.objects.get(first_name='Alex'),summary='Anything about Doge',date_of_publish=datetime.date(2019, 1, 17)) o5 = Book.objects.create(title='Dollar',author=Author.objects.get(first_name='Alex'),summary='Anything about Dollar',date_of_publish=datetime.date(1568, 4, … -
Django forms with CSRF protection in IOS 14+
IOS 14 came out few months ago, which defaults to blocking all third party cookies unless the user enables them specifically by disabling this option: Settings -> Safari -> Prevent Cross-site Tracking This presents a problem for Django forms with csrf protection that is served inside an <iframe> from a third-party domain like this: -----Parent website----- | | | ----------------- | | | | | | | Django form | | | | inside | | | | iframe | | | | | | | ----------------- | | | ------------------------- Django form sets a csrfmiddlewaretoken as a hidden form variable and also sets a cookie called csrftoken, and does the form security verification when the form is submitted. The problem comes when attempting to set the cookie csrftoken while inside an <iframe>, being in a third-party website context. In IOS 14, this cookie is rejected. The form still submits without this cookie but django rejects the form as expected. The exact error I am getting: Forbidden (CSRF cookie not set.), which is correct from django's point of view. The form works correctly when we disable the Safari setting, to allow cross-site tracking. But this needs to be done at … -
leaflet dynamic map generation in django templates
I am pretty novice in javascript and django. I am trying to figure out this scenario. My models are like these: class Post(models.Model): plan = models.ForeignKey(Plan, to_field='id', on_delete=models.CASCADE, blank=True) user = models.ForeignKey(Company_User, to_field='id', on_delete=models.CASCADE, blank=True) creation_date = models.DateField(default=timezone.now) modification_date = models.DateField(default=timezone.now) title = models.CharField(max_length=85) description = models.TextField() gps_path = models.TextField() class Marker(models.Model): post = models.ForeignKey(Post, to_field='id', on_delete=models.CASCADE, blank=True) lat = models.FloatField() long = models.FloatField() img = models.TextField() classes = models.CharField(max_length=100) description = models.TextField() repair = models.ForeignKey(Repair_Log, null=True, to_field='id', on_delete=models.CASCADE, blank=True) Then I have a view like this: def viewPostByDate(request): if not request.session.has_key('name'): return redirect('rsca_login') if request.session["type"] != 1 and request.session["type"] != 2: return redirect('rsca_home') elif request.method == 'POST': start_date = datetime.strptime(request.POST.get('start_date'), "%Y-%m-%d").date() end_date = datetime.strptime(request.POST.get('end_date'), "%Y-%m-%d").date() # get all the posts posts = Post.objects.all() company_posts = [] paths = [] posts_markers = [] for post in posts: if post.user.company_id == request.session["company_id"] and start_date <= post.creation_date <= end_date: company_posts.append(post) path = post.gps_path path = path.replace("(", "") path = path.replace(")", "") path = path.split(',') path = [float(i) for i in path] path = to_matrix(path, 2) paths.append(path) context = {'posts': company_posts, 'paths': paths} return render(request, 'rsca/view_post_on_map_by_date_2.html', context) Here paths is an array of 2D matrices where each row is a gps lat and … -
How to add Blog replay in django?
Hello I am new in django. I created an comment system where user can post comment. Now I want to add replay to my comment. How to automatically select parent comment in my html replay froms?. here is my code: views.py class BlogDetail(DetailView): model = Blog template_name = 'blog_details.html' def get(self,request,slug): blog = Blog.objects.get(slug=slug) queryset = BlogComment.objects.filter(is_published="0",blog=blog) form = CommentFrom() context = {'form':form, 'blog':blog, 'queryset':queryset } return render(request,'blog_details.html',context) def post(self,request,slug): blog = Blog.objects.get(slug=slug) form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.save() messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return redirect(reverse('blog-detail', kwargs={'slug':slug})) else: form() context = {'form':form, 'blog':blog, } return render(request,'blog_details.html',context) #models.py class BlogComment(MPTTModel): blog = models.ForeignKey(Blog,on_delete=models.CASCADE) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') sno = models.AutoField(primary_key=True) author = models.ForeignKey(User,on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=250) email = models.EmailField(max_length=2000) comment = models.TextField(max_length=50000) created_at = models.DateTimeField(auto_now_add=True,blank=True,null=True) updated_at = models.DateTimeField(auto_now=True,blank=True,null=True) CHOICES = ( ('0', 'published',), ('1', 'pending',), ('2', 'rejected',), ) is_published = models.CharField( max_length=1, choices=CHOICES,default='1' ) right now I can only add replay form my django admin panel by selecting parent comment. I want to add replay through my html replay froms. somethings like this: -
What is a NoReverseMatch error, and how can I solve it?
I'm making an Online shop using Django and trying to add quantity of each product from cart and it throws the error under : AttributeError at /order/add_cart_pro 'Order' object has no attribute 'order' What can I do and how can I solve it? this is my views : def add_cart(request) : pnum = request.GET.get("pnum") cart = Order.objects.get(prod_num_id = pnum) cart.save() # save 호출 return redirect( "add_cart_pro" ) def add_cart_pro(request): memid = request.session.get( "memid" ) cart = Order.objects.filter(order_id_id = memid) member = Sign.objects.get(user_id = memid) pnum = request.GET.get("pnum") template = loader.get_template("cart_view.html") for add in cart : cart += add.order.quan + 1 context = { "memid":memid, "cart":cart, "member":member, "pnum":pnum, } return HttpResponse( template.render( context, request ) ) -
How to Sort Nested QuerySet Objects using time stamp
I am new to Django restframework. I have an api, where I have to sort comments based on their of create.A comment can have multiple child comments in line. Whenever a comment(either child or parent) is created,that family should be displayed first. But ,I could able to sort only first layer of json as per timestamp. but I need to sort even by considering child created time ,and display that family firs. A sample Json is given for reference. [ { "id": 75, "comment_category": "technical", "comment": "", "x": null, "y": null, "children": [ { "id": 78, "comment": "Techni/..'\r\n.", "is_parent_comment_resolved": false, "timestamp": "2021-06-07T10:07:28.281312Z", "time_since": "9 minutes ago" } ], "is_parent_comment_resolved": false, "timestamp": "2021-06-07T09:22:57.027836Z", "time_since": "53 minutes ago" }, { "id": 74, "comment_category": "technical", "comment": "Technical", "x": null, "y": null, "children": [ { "id": 76, "comment": "", "is_parent_comment_resolved": false, "timestamp": "2021-06-07T09:23:32.079769Z", "time_since": "53 minutes ago" }, { "id": 77, "comment": "", "is_parent_comment_resolved": false, "timestamp": "2021-06-07T09:37:41.266583Z", "time_since": "39 minutes ago" }, { "id": 79, "comment": "techhhhhhhh", "is_parent_comment_resolved": false, "timestamp": "2021-06-07T10:13:00.016222Z", "time_since": "3 minutes ago" } ], "is_parent_comment_resolved": false, "timestamp": "2021-06-07T09:22:34.390586Z", "time_since": "54 minutes ago" }, { "id": 74, "comment_category": "technical", "comment": "Technical", "x": null, "y": null, "children": [ { "id": 76, "comment": "", … -
Jinja template inherited but not able to modify it on other files
This is my base.html: {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <style>/* Add a black background color to the top navigation */ .topnav { background-color: rgb(10, 113, 145); overflow: hidden; } /* Style the links inside the navigation bar */ .topnav a { float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* Change the color of links on hover */ .topnav a:hover { background-color: #ddd; color: black; } /* Add a color to the active/current link */ .topnav a.active { background-color: #04AA6D; color: white; } </style> <div class="topnav"> <a href="/">Home Page</a> <a href="/projects">Projects</a> <a href="/contact">Contact</a> </div> </body> </html> this is my projects.html: {% extends "important/base.html" %} {% block content %} <h1>Projects</h1> {% endblock content %} Iam not able to see anything on my projects pae even I did everything correctly this is my settings.py: INSTALLED_APPS = [ 'important', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Is there anything that I can change in this to make it work? please help … -
pymemcache with pickle django
I was trying to cache a Django model Instance like class MyModel(models.Model): ... several atributes, as well as foreign key attributes ... from pymemcache.client import base import pickle obj = MyModel.objects.first() client = base.Client(("my-cache.pnpnqe.0001.usw2.cache.amazonaws.com", 11211)) client.set("my-key", pickle.dumps(obj), 1000) # 1000 seconds # and to access I use obj = pickle.loads(client.get("my-key")) They both works fine, but sometimes executing the same line: client.get("my-key") generates very very strange errors like Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 823, in _fetch_cmd prefixed_keys) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 791, in _extract_value key = remapped_keys[key] KeyError: b'some-other-cache-key' and sometimes I get: Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 833, in _fetch_cmd raise MemcacheUnknownError(line[:32]) and sometimes I get Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 823, in _fetch_cmd prefixed_keys) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 790, in _extract_value buf, value = _readvalue(self.sock, buf, int(size)) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 1234, in … -
Assigning same integer to specific string for table in database
I'm gathering errors to the table SystemErrors which now looks like this id error_msg system_id 1 error1 1123 2 error1 341 3 error2 1415 The message of errors though is too long, so i need another column to the later verification which error it is. And i want in the same table another column which will be connected with Error column. If the row with error1 is added, i want column error_id with integer 1. Like this id error_msg error_id system_id 1 error1 1 38 2 error1 1 112 3 error2 2 323 Now my code looks like this class SystemError(models.Model): report = models.ForeignKey(SystemReport, on_delete=models.CASCADE) error_msg = models.CharField(max_length=2000) Can i do this in this table by assigning any connection with error_msg