Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Foreign Keys ManyToManyField and Organizations that are members of other Organizations
I've been teaching myself django, and don't have a background in databases. I looked up entity relationship diagrams and have been reading the django manual and the below model seems to work, but is it the "right way" to do it? I have organizations that can have members, but the organizations can also be be parts of organizations, and members don't have to be part of an organization. The organizations and member companies can also have multiple locations. (Yes this really happens with industry consortiums...) Each may or may not have training materials. So in the class Organization I couldn't call itself, but I could have it be a member_of something in the member class. So what I came up with for a model and it seems to compile and is accessible in the admin interface. class Address(models.Model): # one HQ address, but could have other locations #name could come from either Organization or from Member HQ_address=models.BooleanField() country_code = models.CharField(max_length=2,default='') city =models.CharField(max_length=100,default='') url=models.URLField(max_length=200,default='') email=models.EmailField(max_length=254,default='') class Resource(models.Model):# can have 0 to many of several types of resources #books = models.ManyToManyField(Books) #videos = models.ManytoManyField(Videos) #courses = models.ManytoManyField(courses) pass class Member(models.Model): # a member by itself is not an organization # use the … -
Django Rest Framework Not Null Constraint
When i try to create a new by post by posting the following Json: { "title": "This is serialzer title", "content": "This is serialzer content", } I get the following error: NOT NULL constraint failed: blog_post.views Models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=255) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) views = models.IntegerField() slug = models.CharField(max_length=100) timeStamp = models.DateTimeField(default=now) def __str__(self): # return self.title + ' by ' + self.author return self.title + ' by ' + self.author.username class BlogComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timeStamp = models.DateTimeField(default=now) def __str__(self): return self.comment[0:13] + "..." + " by " + self.user.username views.py @api_view(['POST']) def api_create_blog_view(request): user = User.objects.get(pk=1) blog_post = Post(author=user) if request.method == "POST": serializer = PostSerializer(blog_post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py from blog.models import Post from rest_framework import serializers class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['title', 'content'] I don't know how to solve this please help me to solve this error.DB has already been cleared. … -
django forms and request in same http page
OK so I'm trying to create a page that will have a search form of Well, I get the contents of the search in the page ex: (http://127.0.0.1:8000/wellsheet/ODN20) I used this code urls.py file path('wellsheet/<slug:Evt_id>', views.wellsets, name='WellSheetg'), views.py def wellsets(request, Evt_id): serchedWl = WellSheets.objects.filter(WellID__WellID__exact=Evt_id) context ={ 'title': 'Eventstopost', 'Wellslist':serchedWl, 'WIDSHT':Evt_id, } return render(request, 'Home/WELLINFO/W_TchD/wellshts.html', context) in addition to this page I want to add another well ,and I have a model form to add in same page using crispy. urls.py path('wellsheet/<slug:WeelN>/', views.welshetad2.as_view(), name='AddWellSheet'), views.py class welshetad2(LoginRequiredMixin, CreateView): model = WellSheets template_name = 'Home/WELLINFO/W_TchD/wellshts.html' form_class = UploadWSF2 def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) but in my page I can't render the crispy form <div class="border p-3 mb-3 mt-3 w3-round-large w3-light-grey border-dark"> <form method="POST"> {% csrf_token %} <div class="form-row"><div class="form-group mb-0"> {{ form.as_p }} </div></div> this is my page page My goal is to see a page like this My Goal -
django template add two variables
how can I add two or more variables in django template? here is my template code: {% for cap in capital %} {{cap.capital_type}} {{cap.capital_amount}} {% endfor %} Total Capital: {{total_capital}} where {{total_capital}} will be sum of cap.capital_amount -
Django - weird debug output when using migrations management commands after installing matplotlib
Running GeoDjango in a Docker container - have added additional libraries via pip in the Dockerfile, and am now experiencing unwanted console output whenever I invoke any of the migrations commands, e.g. manage.py showmigrations/makemigrations/migrate. The output is as follows: user@host:/src$ ./manage.py showmigrations CONFIGDIR=/home/django/.config/matplotlib (private) matplotlib data path: /usr/local/lib/python3.7/site-packages/matplotlib/mpl-data matplotlib data path: /usr/local/lib/python3.7/site-packages/matplotlib/mpl-data loaded rc file /usr/local/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc matplotlib version 3.2.1 interactive is False platform is linux loaded modules: ['sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', 'zipimport', '_frozen_importlib_external', '_io', 'marshal', 'posix', 'encodings', 'codecs', '_codecs', ... Comprehensive modules listing snipped, it continues: Using fontManager instance from /home/django/.cache/matplotlib/fontlist-v310.json Loaded backend qt5agg version unknown. Loaded backend tkagg version unknown. Loaded backend agg version unknown. Loaded backend agg version unknown. Found GEOS DLL: <CDLL '/usr/local/lib/python3.7/site-packages/shapely/.libs/libgeos_c-5031f9ac.so.1.13.1', handle 5608f64e4c40 at 0x7f22a5aaaf10>, using it. Trying `CDLL(libc.so.6)` Library path: 'libc.so.6' DLL: <CDLL 'libc.so.6', handle 7f22c4809000 at 0x7f22aef3b650> GDAL_DATA not found in environment, set to '/usr/local/lib/python3.7/site-packages/fiona/gdal_data'. PROJ data files are available at built-in paths Entering env context: <fiona.env.Env object at 0x7f22a0798450> Starting outermost env No GDAL environment exists New GDAL environment <fiona._env.GDALEnv object at 0x7f22a0798490> created Logging error handler pushed. All drivers registered. GDAL_DATA found in environment: '/usr/local/lib/python3.7/site-packages/fiona/gdal_data'. PROJ data files are available at built-in paths Started GDALEnv <fiona._env.GDALEnv object at … -
Best Practice Using Django Signal (For user authentication?)
I am new to Django and want to know deeper about the concept of signals. I know how it works but really don't understand when should one really use it. From the doc it says 'They’re especially useful when many pieces of code may be interested in the same events.' What are some real applications that use signals for its advantage? e.x. I'm trying to make a phone verification after user signup. Because it can be integrated inside the single app and the event that interested for the signal is only this 'verify' function, therefore I don't really need signal. I can just pass the information from one view to the other, rather than using pre_save signal from the registration. I'm sorry if my question is kind of basic. But I really want to know some insight what is the real application, in which many codes interested in one particular event and what are some trade off in my application. Thanks!! -
Django SECRET_KEY environmental variable always empty
In mysite/settings.py I have: SECRET_KEY = os.environ["SECRET_KEY"] Using the GUI Control Panel ---> System Properties ---> Advanced ---> Environmental Variables, I have set the user environmental variables: Variable Value SECRET_KEY 123456 But am still getting the key is empty error when I run manage.py Failed to get real commands on module "mysite": python process died with code 1: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2020.1.2\plugins\python\helpers\pycharm\_jb_manage_tasks_provider.py", line 25, in <module> django.setup() File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\venv\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\venv\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\venv\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\venv\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\super\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\mysite\settings.py", line 11, in <module> SECRET_KEY = os.environ["SECRET_KEY"] File "C:\Users\super\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' -
Django 3 when sending a letter to mail, images in the letter are not displayed, how to fix it?
subject = name_cinema html_message = render_to_string('app_template/mail_template.html', context) plain_message = strip_tags(html_message) from_email = 'From <example12090@gmail.com>' to = email mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message) Layout mail_template.html, the problem is iz from the image, iz from the content of all the norms it is shown less than 4 varianti, there, de invoking the power of the image. {% load static%} connection <img src="{% static 'img/1234.png' %}" alt="1"> <img src="{% static 'img/1.png' %}" alt="2"> <img src="../../1234.png" alt="3"> 4<img src="https://www.meme-arsenal.com/memes/579eb482a8540ee55b0bf3db8695a783.jpg" alt="4"> enter image description here -
Why I can't import a file from a Django app into the urls.py file?
I'm trying to do a Django tutorial but I keep getting the same error I don't know why, I have follow every step in the same way. ERROR: { "resource": "/Users/mycomputer/Documents/Programacion/Python/Curso Django/password_generator_p/password_generator/urls.py", "owner": "_generated_diagnostic_collection_name_#0", "code": "unresolved-import", "severity": 4, "message": "unresolved import 'generator'", "source": "Python", "startLineNumber": 18, "startColumn": 6, "endLineNumber": 18, "endColumn": 15 } Import Settings I've already tried with: - from . import views - from . import views - from .. import views - from password_generator.generator import views - from generator.views import views - from password_generator_p import generator / from generator import views -
Having trouble making a view with 2 forms
I made a django view and I am able to display my configuration the way I want to except that the answers to my attributes are not editable. I have tried a few different ways to get this to work and am struggling to find a way to get the form to allow my answers to be changable. My Model class Configuration(models.Model): name = models.CharField(max_length=100, blank=True, null=True) config_type = models.ForeignKey('ConfigType', on_delete=models.PROTECT, null=True) company = models.ForeignKey('companies.Company', on_delete=models.PROTECT, blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True, blank=False, null=True) updated = models.DateTimeField(auto_now=True) sla = models.ForeignKey('SLA', on_delete=models.PROTECT, blank=True, null=True) install_date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) purchase_date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) purchase_price = models.DecimalField(decimal_places=2, max_digits=1000, blank=True, null=True) warranty_exp = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) end_of_life = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) #vendor = models.ForeignKey('companies.Company', on_delete=models.PROTECT, blank=True, null=True) manufacturer = models.ForeignKey('Manufacturer', on_delete=models.PROTECT, blank=True, null=True) mfg_part = models.CharField(max_length=50, blank=True, null=True) model_number = models.CharField(max_length=50, blank=True, null=True) serial_number = models.CharField(max_length=250, blank=True, null=True) tag_number = models.CharField(max_length=50, blank=True, null=True) notes = models.TextField(max_length=1024, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("configurations:configuration-update", kwargs={"id": self.id}) class Manufacturer(models.Model): name = models.CharField(max_length=50, blank=False) incative = models.BooleanField(default=False) def __str__(self): return self.name class SLA(models.Model): name = models.CharField(max_length=25, blank=False) def __str__(self): return self.name class ConfigType(models.Model): name = models.CharField(max_length=50, blank=False) inactive = models.BooleanField(default=False) … -
Django/Jquery inlineformset: why add-row button is hidden when using max_num option i my formset?
I am developping a Django project and I use nested inlineformset with jQuery to get add-row and delete-row buttons. It works but I would like to use inlineformset options extra=3 and max_num=4. The problem is that, with max_num option, the add-row button is hidden (as I can see in developer tool). I don't understand why. My first attempt was to display the button using JQuery (display=False -> display=True). The button is displayed but when I click it add a row the button disappeared... It should have a better way to do that... forms.py NAME = Thesaurus.options_list(2,'fr') ACCESS = Thesaurus.options_list(3,'fr') ApplicationFormset = inlineformset_factory( UtilisateurProjet, Application, #Utilisateur, Application, fields=('app_app_nom','app_dro'), widgets={ 'app_app_nom': forms.Select(choices=NAME), 'app_dro': forms.Select(choices=ACCESS) }, extra=3, can_delete=True, max_num=4, ) js <script src="{% static 'project/js/jquery.formset.js' %}"></script> <script> $('.link-formset').formset({ addText: 'Ajouter', deleteText: 'Supprimer', prefix: '{{ application.prefix }}' }); </script> -
Docker-compose can not connect mysql with django
when I use docker-compose to connect mysql with my djangoapp,I got this error:web_1 | django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)") and this db_1 seems also wrong ,enter image description here this is my Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /myblog RUN mkdir /myblog/db WORKDIR /myblog RUN pip install pip -U -i https://pypi.tuna.tsinghua.edu.cn/simple ADD ./requirements.txt /myblog/ RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple ADD . /myblog/ this is my docker-compose FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /myblog RUN mkdir /myblog/db WORKDIR /myblog RUN pip install pip -U -i https://pypi.tuna.tsinghua.edu.cn/simple ADD ./requirements.txt /myblog/ RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple ADD . /myblog/ [root@VM_0_12_centos lshblogs]# cat docker-compose.yml version: "3.0" services: db: image: mysql:5.7 expose: - "3306" volumes: - ./db:/var/lib/mysql environment: - MYSQL_DATABASE=lsh_blog - MYSQL_ROOT_PASSWORD=11111111 web: build: . command: python ./manage.py runserver 0.0.0.0:8000 volumes: - .:/myblog ports: - "8000:8000" depends_on: - db this is my database settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'lsh_blog', 'USER': 'root', 'PASSWORD': '11111111', 'HOST': 'db', 'PORT': '3306', } } this is the error stack db_1 | 2020-06-15 15:23:41+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started. db_1 | 2020-06-15 15:23:41+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql' db_1 | 2020-06-15 … -
Django - [WinError 10061] No connection could be made
Sorry, I know theres a lot of content here and elsewhere on the internet, but lets go... I deployed my application on a local server. Everything is working perfectly, but when trying to generate a PDF in the administration area, return this error. I searched about it and all I can find is about email sending settings. Although my generate_curriculo_pdf doesn't use sending emails, does it really have something related? Does anyone have any idea? ConnectionRefusedError at /admin/main/vagasusuarios/1/actions/generate_curriculo_pdf/ [WinError 10061] No connection could be made because the target machine actively refused it Request Method: GET Request URL: http://192.168.109.217/admin/main/vagasusuarios/1/actions/generate_curriculo_pdf/ Django Version: 2.2.13 Python Executable: c:\python\python.exe Python Version: 3.5.0 Python Path: ['.', 'c:\\python\\python35.zip', 'c:\\python\\DLLs', 'c:\\python\\lib', 'c:\\python', 'c:\\python\\lib\\site-packages', 'c:\\python\\lib\\site-packages\\setuptools-47.1.1-py3.5.egg', 'C:\\inetpub\\wwwroot\\settings'] Server time: Seg, 15 Jun 2020 12:36:45 -0300 Installed Applications: ['main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'localflavor', 'django.contrib.humanize', 'django_object_actions', 'bootstrap4', 'ckeditor', 'ckeditor_uploader'] Installed Middleware: ['whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "c:\python\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "c:\python\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "c:\python\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\python\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "c:\python\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "c:\python\lib\site-packages\django\contrib\admin\sites.py" … -
How to redirect back to current page in Django once a button is clicked?
Currently this view redirects back to homepage. def wishlist(request, title_slug): obj = get_object_or_404(Listing, slug=title_slug) profile = Profile.objects.all().filter(user=request.user).first() profile.wishlist.add(obj) return HttpResponseRedirect('/') I have this button in list view and detail view: <a href="{% url 'listing:wishlist' listing.slug %}"> <i class="fas fa-heart"></i> </a> No matter where the user adds an item to wishlist, it should be redirected back to that list view or detail view. Thank you -
How to validate google recaptcha(site need to verifiy) if i am using django as backend & angualarjs as frontend
For google recaptcha v2 validation we need to send the POST request with recaptcha token respons with secret key to google server api i.e.https://www.google.com/recaptcha/api/siteverify from backend only. For recaptcha implemenation i have used the ng-recaptcha module as i am getting the valid recaptcha response token in angularjs How do I get value of recaptcha token response from angular to django for sending post request. How angular communicate with django within same Application ? -
Creating user without username (or with auto-generated username)
I want to create a registration page that doesn't ask for an username, since i'm not planning on using it (i only need email and password). However, i'm not sure how to tell django that username is not mandatory. I'm having trouble registering users because they all get the same username (blank). My user model: class User(AbstractUser): departments = models.ManyToManyField(Department) def __str__(self): return f'{self.first_name} {self.last_name}' My form for registering: class UserCreateForm(UserCreationForm): class Meta(): fields = ('first_name', 'last_name', 'email', 'departments', 'password1', 'password2') model = get_user_model() The view: class SignUpView(CreateView): form_class = UserCreateForm success_url = reverse_lazy('loginPage') template_name = 'accounts/signup.html' What should i change in order to tell django to ignore the username field for the User model? Is a random auto-generated username a good idea to avoid this problem? If yes, how do i code it? -
Refused to execute *path_to_bundle* as script because "X-Content-Type: nosniff" was given and its Content-Type is not a script MIME type
I'm developing web app using Django as a backend and Vue js as a frontend. I connected them via webpack. When I develop app in Dev mode, everything is good, I don't use chunks, which are created using npm run build. But when it comes to Stage or Prod mode, when DEBUG=False on Django, and npm run build on vue js, to build all static files, I got error Refused to execute http://localhost:8000/static/sections_dist/js/chunk-common.34112dfe.js as script because "X-Content-Type: nosniff" was given and its Content-Type is not a script MIME type. Did not parse stylesheet at 'http://localhost:8000/static/sections_dist/css/chunk-common.677f6644.css' because non CSS MIME types are not allowed in strict mode. maybe I'm using incorrect webpack settings, please help me with that... My webpack.config.js: const BundleTracker = require("webpack-bundle-tracker") const path = require('path') module.exports = { publicPath: "/static/sections_dist/", outputDir: '../loppeonline/static/sections_dist/', chainWebpack: config => { // config.optimization // .splitChunks(false) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}]) config.devServer .public('http://0.0.0.0:8000') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({ 'Access-Control-Allow-Origin': ['*'] }) } } my base.html body, where I render bundles: <body> <div id="app"> </div> {% if not settings.DEBUG %} {% render_bundle 'chunk-common' 'js' 'SECTIONS' %} {% render_bundle 'chunk-vendors' 'js' 'SECTIONS' %} {% render_bundle 'chunk-vendors' 'css' 'SECTIONS' %} {% render_bundle 'chunk-common' 'css' 'SECTIONS' … -
Add extra field in response output in DRF 3.0
I have the following models class Restaurant(models.Model): name_of_the_restaurant = models.CharField(max_length=30, blank=True) opening_time = models.TimeField(auto_now=False, auto_now_add=False) closing_time = models.TimeField(auto_now=False, auto_now_add=False) And class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) city = models.CharField(max_length=30, blank=True) country = models.CharField(max_length=30, blank=True) postal_code = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) favourite_restaurant = models.ManyToManyField(Restaurant, blank=True, related_name='favourite_restaurant', related_query_name='favourite_restaurant') I have defined a serializer for Restaurant model which is mainly : class RestaurantSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = '__all__' Now in my ViewSet logic I am doing the following : class RestaurantListView(generics.ListAPIView): serializer_class = RestaurantSerializer def get_queryset(self): queryset = {'Error': 'Please pass valid url parameters'} city = self.request.query_params.get('city', None) postal_code = self.request.query_params.get('postalcode', None) country = self.request.query_params.get('country', None) if city is not None or postal_code is not None: queryset = Restaurant.objects.filter( Q(city=city) | Q(pincode=postal_code)) if country and city is not None and postal_code is None: queryset = Restaurant.objects.filter(country=country, city=city) return queryset def get(self, request, format=None): restaurant_qs = self.get_queryset() ids_list = [restaurant.id for restaurant in restaurant_qs] favourite_restaurant = is_favourite_restaurant(ids_list, self.request.user) serializer = RestaurantSerializer(restaurant_qs, many=True) return Response(serializer.data) where is_favourite_restaurant is a custom function function which returns queryset of FAVOURITE restaurant(s) of a user. Now in the output for this GET request I am getting result as : [ … -
Django language session not existing
I have made a website which supports two languages at the moment. It has been made with django.utils.translation (Using makemessages and compilemessages). The site is working fine locally on my own machine, and translating correctly. When i pull the code on the website server (and restart the app) it gives the following error: `Internal Server Error: /da/ Traceback (most recent call last): File "/home/myname/.virtualenvs/myEnv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/myname/.virtualenvs/myEnv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/myname/.virtualenvs/myEnv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/myname/myname/myname_django/home/views.py", line 62, in index 'value': get_value(request.session[LANGUAGE_SESSION_KEY]), File "/home/myname/.virtualenvs/myEnv/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 54, in __getitem__ return self._session[key] KeyError: '_language'` So for some reason it cannot find the language session, but i have no clue why -
Reverse for 'janre_detail_url' with keyword arguments '{'slug': 'detectiv'}' not found. 1 pattern(s) tried: ['cards/janre/<str:slug/>$']
Good afternoon. I have the following problem. I tried to fix it in various ways, but nothing helps. I would be happy to help. I read that the problem may be that there is an error somewhere that can't take data from the database, however I don't understand where this might be. I am a novice developer on Django. Thanks! models.py from django.shortcuts import reverse class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique=True) body = models.TextField(blank=True, db_index=True) tags = models.ManyToManyField('Tag', blank=True, related_name='posts') date_pub = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('post_detail_url', kwargs={'slug': self.slug}) def __str__(self): return self.title class Tag(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def get_absolute_url(self): return reverse('tag_detail_url', kwargs={'slug': self.slug}) def __str__(self): return '{}'.format(self.title) views.py from django.shortcuts import render from django.views.generic import View from django.http import HttpResponse from .models import Card, Janre def card_page(request): cards = Card.objects.all() return render(request, template_name='cards/card_page.html', context={'cards': cards}) def card_detail(request, slug): card = Card.objects.get(slug__iexact=slug) return render(request, template_name='cards/card_detail.html', context={'card': card}) def janres_page(request): janres = Janre.objects.all() return render(request, template_name='cards/janres_page.html', context={'janres': janres}) def janre_detail(request, slug): janre = Janre.objects.get(slug__iexact=slug) return render(request, template_name='cards/janre_detail.html', context={'janre': janre}) urls.py from django.urls import path from .views import card_page, card_detail, janres_page, janre_detail urlpatterns = [ path('', card_page, name='card_page_url'), path('card/<str:slug>/', card_detail, name='card_detail_url'), path('janres/', janres_page, name='janres_page_url'), … -
Django - getting model from another database
Is there a simple method to import model data from another database? Supose i have 2 databases: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'first_db', 'USER': 'admin', 'PASSWORD': '', 'HOST': 'localhost', }, 'second': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'second_db', 'USER': 'admin', 'PASSWORD': '', 'HOST': 'localhost', }, } One app with model in database: second_db class Client(models.Model): first_name = models.CharField(max_length=100, blank=True, null=True) and i wont to get data from this model and load it to default database: first_db data = Client.objects.using('second_db').all() Question: Is there option to do this without creating mirror empty app in default database? With usage of database Router or manually selecting a database with .using() Some related questions: link, link2 -
(admin.E202) 'core.Item_stock' has no ForeignKey to 'core.Item_stock'. in django
**I'm setting up Django admins with: model.py class Item_size (models.Model): size_label=models.CharField( max_length=50) size_catagory=models.ForeignKey('catagory',limit_choices_to={'cat_min__isnull':False}, verbose_name= ("catagory"), on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.size_label class Item_stock (models.Model): product=models.ForeignKey('Item',on_delete=models.CASCADE) size=models.ForeignKey('Item_size',default=0,on_delete=models.CASCADE) size_q=models.IntegerField(default=0) def __str__(self): return self.product.title And at admin.py class ItemStockInstanceInline(admin.TabularInline): model = Item_stock @admin.register(Item_stock) class ItemStockAdmin(admin.ModelAdmin): list_display = ['product', 'size', 'size_q'] inlines = [ItemStockInstanceInline] With this I'm getting the following error: ERRORS: <class 'core.admin.ItemStockInstanceInline'>: (admin.E202) 'core.Item_stock' has no ForeignKey to 'core.Item_stock'. -
Django getting the M2M instances into the save method
im trying to implement a notifications system that will enable me to notify a user if a new object is created in my database. In order to do that , i initially adopted a signals method. However , using the m2m_changed method does not allow me to distinguish between a create or a update scenario. Moreover i have been told that using signals for this is an anti-pattern. That being said , i am now attempting to use the save() method to handle the creation logic of my notifications. Models.py Here is a watered down version of my model class SalesProject(models.Model): sales_project_name = models.CharField(max_length=100) userProfile = models.ManyToManyField('UserProfile', blank=True) customer_information = models.ManyToManyField('CustomerInformation') def save(self, *args, **kwargs): print(self.customer_information.all()) super(SalesProject, self).save(*args, **kwargs) As you can see there are 2 M2M fields here , userProfile and customer_infomation. When the user updates the SalesProject instance by lets say adding a customer_infomation instance to the M2M relation , it does not reflect at print(self.customer_information.all()) as expected , since Django only adds the M2M field after the 'host' object is saved into database. Therefore with this in mind i have 2 questions: From what i understand , it is not possible to know if the m2m_changed signal … -
Cannot connect to postgresql databse from django settings.py on localhost
Forgive me as I this is my first django project using postgresql. For now I just want to connect to a test database which I have set up locally using pgadmin4. When I create the database I am not given the option to add a password, but when I run python manage.py migrate it is insisting on a password. When I then set the password to "password" on pgadmin, django won't accept it. It's probably something really obvious as I am quite new to Django, but I have tried searching and not found the answer to my problem. In settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test1', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', } } Last line of the error when I run python manage.py migrate: django.db.utils.OperationalError: fe_sendauth: no password supplied Any help much appreciated. Craig -
Django Polls App clickable radio buttons?
I've recently finished the Django polls tutorial, now I'm trying to make clickable links out of the radio choices buttons on the detail.html page. I've tried about everything but can't seem to get it to work. Could anyone send me in the right direction? <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> <a href="{% url 'choice' %}"/> {% endfor %} <input type="submit" value="Vote" /> </form>