Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pymongo.errors.ServerSelectionTimeoutError while running a docker image of django app
I am trying to run a docker image of my Django app. I am running a mongo image separately from another container. Need help to solve following error: pymongo.errors.ServerSelectionTimeoutError: xxx.xxx.xxx.xxx:27017: timed out, Timeout: 30s, Topology Description: <TopologyDescription id: 61aee0f6695286eb954e68ea, topology_type: Single, servers: [<ServerDescription ('xxx.xxx.xxx.xxx', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('xxx.xxx.xxx.xxx:27017: timed out',)>]> I have configured mongo db using djongo, DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'database-name', 'CLIENT':{ 'username': 'username', 'password': 'password', 'host': 'mongodb://xxx.xxx.xxx.xxx:27017/database-name', 'port': 27017, 'authSource': 'admin', 'authMechanism': 'SCRAM-SHA-1' } } } I have also created a user in mongo db using following command; db = db.getSiblingDB('database-name') db.createUser({ user: 'username', pwd: 'password', roles: [ { role: 'root', db: 'admin', }, ], }); Using the same credentials while configuring Mongo with Django. This is my requirements.txt asgiref==3.4.1 dataclasses==0.8 Django==3.2.9 django-filter==21.1 djangorestframework==3.12.4 djongo==1.3.6 gunicorn==20.0.4 importlib-metadata==4.8.2 Markdown==3.3.6 pymongo==3.12.1 python-dateutil==2.8.2 pytz==2021.3 six==1.16.0 sqlparse==0.2.4 typing_extensions==4.0.0 zipp==3.6.0 The Mongo containers are as follows, CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f479308130bb mongo-express "tini -- /docker-ent…" 16 hours ago Up 16 hours (healthy) 0.0.0.0:9081->8081/tcp, :::9081->8081/tcp mongo-express 4e6e0e60a473 mongo "docker-entrypoint.s…" 16 hours ago Up 16 hours (unhealthy) 0.0.0.0:27017->27017/tcp, :::27017->27017/tcp mongodb If I try to access mongo db from remote server using the user that I … -
Django Summernote Settings
I've installed django-summernote and most of it works fine except for the dropdown buttons for Style, Font Size, Color and Table. The example has them setup as follows: ... 'toolbar': [ ... ['style', ['style'], ['fontsize', ['fontsize']], ['color', ['color']], ['table', ['table']], ... ], I have tried placing a list of possible values, for example, a list of colors in color: ['color', ['black', 'red']], But this clearly isn't correct as the button doesn't show at all if I try entering a list of possible values. I have noticed that if I copy in any formatted text and select it, the fontsize button does display the actual size I copied but gives me no way to change it from the toolbar and my only option for sizing text is to use CTRL+1/2/3/4/5/6 for the relevant format as H1 to 6 whereas the examples shown online clearly have working dropdowns. I am using bs5 SUMMERNOTE_THEME = 'bs5' theme and have tried various config's in settings.py but nothing seems to enable the dropdowns. I have tried copying the scripts from various discussion groups and tutorials discussing summernote to no avail and checked all my settings and they all appear to be fine. It is saving … -
How to solve gateway time-out while connecting to google calendar api?
I am trying to connect to google calendar Api using Documentation . This works on local host and I am able to retrieve events from the user's google calendar. After hosting the website using apache, I can see all the pages live but One of the pages is connecting to the google calendar api and this page says 504 Gateway Time-out. def connect_google_api(): st = time.time() creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('/var/www/FolderName/ProjectName/credentials2.json',SCOPES) creds = flow.run_local_server(port=0) with open('token.json','w') as token: token.write(creds.to_json()) service = build('calendar','v3',credentials=creds) I am thinking that there is some problem while reading credentails2.json. Can any one point me where I am making mistake? -
Do I need to use "Marking extra actions for routing" in this REST Django API?
I'm currently having this issue. I have to set up an URL like this: .../users/<user_id>/user_action/ There are many users and when I pick one user (with user_id), I will be able to see the user's information. Then, go to /user_action, I will be able to POST actions for that specific user. In this case, do I have to use the Marking extra actions for routing or do I just need to make a separate Viewset for user_action (then link it to users/<user_id>/ in the urls.py)? -
How to override the max_length error message for an ImageField?
I am using Django 2.2. I have an ImageField. I need to override its default max length of 100 and override the error message it generates. Is it me or error messages for anything that inherits from FileField cannot be overridden? class PageTemplate(models.Model) background_image = models.ImageField( blank=True, null=True, verbose_name='Header Image', upload_to=page_template_image_path, max_length=150, error_messages={'max_length': "This is a test 1"}, validators=(validate_image_file_extension, validate_filename_size), ) The error message that I get is Ensure this filename has at most 150 characters (it has 157). And before anybody asks, yes, I remembered to run makemigrations and migrate. -
Calling Django REST API from a python function?
Is there any way I can call a DRF API from a python function. There is no URL allowed to this API, my requirement API should not be accessible from the front end. Thanks in Advance -
Django resubmits blank form after successful form
I'm new to Django and I'm trying to make a site where after a user inputs a start and end date, some data processing is done and then a result is displayed. I have this working, but after the form successfully completes and displays the data, a new POST and GET request run on the server and find no input. This is causing me problems with another form on the same project. I think I may need to use redirect to avoid double form submission? However, I am trying to process data with the post request and display, and to my understanding, the redirect would take the user to a new url and not pass the processed data with it. Thanks in advance! Here is part of my index.html <div class="search-container"> <form action="{% url 'get_data' %}" method="post"> {% csrf_token %} {{ timeform}} <input type="Submit" name="submit" value="Submit"/> </form> And here is my forms.py from django import forms class PickTimesForm(forms.Form): start_date = forms.CharField() end_date = forms.CharField() and here is views.py def plot_data(request): context={} trackform = PickTrackForm() context["trackform"]=trackform if request.method == 'POST': timeform = PickTimesForm(request.POST) if timeform.is_valid(): target_directory= '/home/bitnami/htdocs/projects/laserviz/data/' start_date = timeform.cleaned_data.get("start_date") end_date = timeform.cleaned_data.get("end_date") [data,lats,lons] = tf.getTracks(start_date,end_date,target_directory) [fig_html, track_info]= tf.makeMap(lons,lats) context["figure"]=fig_html context["track_info"]=track_info … -
How to compare two queryset to find same and different values and add to calendar
I'm using the HTMLCalendar module provided by Django. In addition to the event, I want to pull the date value from another class to default and display it in the calendar. First, when the assignment(person) visits the hospital, he enters next_visit. Here, if a patient visits the hospital at an saved next visit, we want to apply a 'text-decoration:line-through' to the next visit data. (get_html_url_drop) The expression for if n.assignment == c.assignment seems to be correct, but the else case doesn't give me the answer I'm looking for. Please help. That is, if the assignment is the same by outputting both the next visit and the cycle visit on a specific date, one assignment(next_visit) will be deleted. Strikethrough applies to that person's name because they visited on the scheduled date. [Leave/models.py] class Leave(models.Model): title = models.CharField(max_length=50, blank=True, null=True) from_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) memo = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) is_deleted = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) return f'<div class="event-title"><a href="{url}" style="color:black;"> {self.title} </a></div>' [Feedback/models.py] class Feedback(models.Model): cycle = models.CharField(max_length=500, default='', blank=True, null=True) day = models.CharField(max_length=500, default='', blank=True, null=True) dosing_date = models.DateField(blank=True, null=True) next_visit = … -
Switching from SQLite to Mysql in production causes error
I am using a digital ocean server. After switching to mysql database from sqlite, I got 502 Bad Gateway nginx/1.18.0 (Ubuntu) This is running fine when I run the project from the terminal using python manage.py runserver ip:8000 . I think there are faults in the gunicorn . How to solve this any idea? After checking the logs, sudo tail -F /var/log/nginx/error.log 2021/12/06 10:32:06 [error] 230230#230230: *15355 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 113.199.220.31, server: develop-330.gsa-cs.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "develop-330.gsa-cs.com" 2021/12/06 10:37:21 [error] 230230#230230: *15358 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 113.199.220.31, server: develop-330.gsa-cs.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "develop-330.gsa-cs.com" 2021/12/06 10:37:24 [error] 230230#230230: *15358 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 113.199.220.31, server: develop-330.gsa-cs.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "develop-330.gsa-cs.com" 2021/12/06 10:44:06 [error] 230230#230230: *15365 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 113.199.220.31, server: develop-330.gsa-cs.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "develop-330.gsa-cs.com" 2021/12/06 10:48:35 [error] 230230#230230: *15368 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 113.199.220.31, server: develop-330.gsa-cs.com, request: "GET … -
PyCharm (pro) - Django console: ModuleNotFoundError: No module named
I can't use the Django console because I keep having the following error and can't figure it out what to do.. I've tried extensively to search for a solution online but none it seems to work for me.. probably cause I don't know the reason of the problem If I don't use the console the app works just fine without any error but I can't do a proper debugging Here it is the error: /Users/alex/Documents/dev_py/project-crm/venv/bin/python3.10 /Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py --mode=client --port=57445 import sys; print('Python %s on %s' % (sys.version, sys.platform)) import django; print('Django %s' % django.get_version()) sys.path.extend(['/Users/alex/Documents/dev_py/project-crm', '/Users/alex/Documents/dev_py/project-crm/users', '/Users/alex/Documents/dev_py/project-crm/project_crm', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev']) if 'setup' in dir(django): django.setup() import django_manage_shell; django_manage_shell.run("/Users/alex/Documents/dev_py/project-crm") PyDev console: starting. Python 3.10.0 (v3.10.0:b494f5935c, Oct 4 2021, 14:59:20) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin Django 3.2.9 Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 6, in <module> File "/Users/alex/Documents/dev_py/project-crm/venv/lib/python3.10/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/alex/Documents/dev_py/project-crm/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Users/alex/Documents/dev_py/project-crm/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/Users/alex/Documents/dev_py/project-crm/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File … -
Chart.js Setup Using Ajax & Variables
I cannot get my Chart.js to show up on my webpage. I am utilizing two arrays for data/labels and am creating the chart in an onload js function. Tried several different methods from tutorials and other Stack posts. HTML is just <canvas id="piee"></canvas> and I brought chart.min.js into my project and load the script as <script src="{% static "js/chart.min.js" %}"></script> window.onload = function () { console.log("Child: ", document.getElementById("piee")) var ctx = document.getElementById('piee').getContext('2d'); var rep_name = $("#pie1").attr("data-rep-name") var ajax_url = $("#pie1").attr('data-ajax-url') var _data = [] var _labels = [] // Using the core $.ajax() method $.ajax({ // The URL for the request url: ajax_url, // The data to send (will be converted to a query string) data: { name: rep_name }, // Whether this is a POST or GET request type: "POST", // The type of data we expect back dataType: "json", headers: {'X-CSRFToken': csrftoken}, context: this }) // Code to run if the request succeeds (is done); // The response is passed to the function .done(function (json) { if (json.success == 'success') { var newMale = json.malePerc var newFemale = json.femalePerc console.log(newMale, newFemale) _labels.push("male", "female") _data.push(parseFloat(newMale), parseFloat(newFemale)) var newUVB = json.uvbPerc var newSize = json.specSize console.log("data: " + _data) var … -
الجمال واللياقة البدنية [closed]
الجمال واللياقة البدنية يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين - كمال اجسام - العناية بالوجه - العناية بالجسم - العناية بالبشرة - العناية بالشعر -
How do i connect EC2 instance for elastic search in Django?
I'm just trying to add dynamic search as a feature to my application, i used Django Elasticsearch DSL to achieve this https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html, but i'm not able to connect the running postgres EC2 instance. Any leads would be very much appreciated :) Here is the snippet where i have to add the creds - ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } Currently, i'm accessing the EC2 using username, password, of-course Host and Port address. -
I am creating a Web project, Frontend on Reactjs backend on Python Django and use Firebase realtime data base for store data
I Know first create restful api to get data from client side but, dont know the flow of project to make connections for CRUD operations in my project -
Link automatically OneToOneField when creating an objects
Considering this two models in my project: MODEL class Movie(models.Model): user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) title = models.CharField(max_length=250) year = models.DateField(default=auto_now_add=True) def __str__(self): return self.title class List(models.Model): user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) movie = models.OneToOneField(Movie, on_delete=models.CASCADE) [...] I'd like to link the List model to the Movie model when the System objects are created. This is my views file: VIEWS def movie_view(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): [...] List.objects.create( user = request.user.userinformation, list_movies = request.list_movies.list, [...] ) return redirect('add_movie') else: return redirect('index') else: form = FileForm() context = { 'form': form, } return render(request, 'add_movie.html', context) This part list_movies = request.list_movies.list may be the problem since I'm getting this error Django: 'WSGIRequest' object has no attribute error. How can I assign correctly the OneToOneField? -
How can i generate backup codes for two factor authentication
I am try to generate backup codes for the users of my system after they enable two factor authenciation -
Django Find difference in the same model instance
I've been searching around and I don't think I've found my answer quite yet. But I'm looking to be able to find differences in data and have a list of column names that show that. Take for instance I have a model just called my_model that has some columns. object = my_model.objects.get(id=1) # Perform edit some values. old_object = my_model.objects.get(id=1) object.save() # Check for differences model_fields = [field.name for field in my_model._meta.get_fields()] filtered_list = filter(lambda field: getattr(object, field, None) != getattr(old_object, field, None), model_fields) Purpose of this is to notify the user after they make an update on their end to send an email to that user to just give them a reminder that they changed whatever values they changed. -
Protected member accessed from outside the class, Django
I'm trying to condition if a value exist as a property in a model or not. I'm trying to do this Mode()._meta.get_field("id") But I got the following error from pylint Protected member accessed from outside the class Can someone help me please? -
How to assign a default choice value to a user when they sign up in django framework
I am writing a logic where when a users creates and account, i want to automatically assign the free membership to them and i know this should be done in the register view but i don't know why it's not working as expected. I still have to manually go to my admin page and manually assign a value to newly created user and that's not what i really wanted. Models.py class Membership(models.Model): MEMBERSHIP_CHOICES = ( ('Enterprise', 'Enterprise'), # Note that they are all capitalize// ('Team', 'Team'), ('Student', 'Student'), ('Free', 'Free') ) PERIOD_DURATION = ( ('Days', 'Days'), ('Week', 'Week'), ('Months', 'Months'), ) slug = models.SlugField(null=True, blank=True) membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) duration = models.PositiveIntegerField(default=7) duration_period = models.CharField(max_length=100, default='Day', choices=PERIOD_DURATION) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) def __str__(self): return self.membership_type #### User Membership class UserMembership(models.Model): user = models.OneToOneField(User, related_name='user_membership', on_delete=models.CASCADE) membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True) reference_code = models.CharField(max_length=100, default='', blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=UserMembership) def create_subscription(sender, instance, *args, **kwargs): if instance: Subscription.objects.create(user_membership=instance, expires_in=dt.now().date() + timedelta(days=instance.membership.duration)) views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') instance = UserMembership.objects.create(user=obj, membership=get_membership) … -
Multiple Django Apps using one database/model
New to Django...I'm trying to create a project with the following structure: CompanyName <--Project ingredients < -- Application CompanyName supplier <-- Application My issue is that my project is going to use a database/model like the following: suppliers (table) - name - created_by (foreign_key, auth.User) ingredients (table) - name - supplied_by (foreign_key, supplier.name) My question is do I create all the tables in a single models.py or do I break up each table into each application's manage.py? If I use separate models.py, how do you create the suppliers table and then the ingredients table since the ingredients table has a foreign key to suppliers? -
How to create a link that takes me to my DjangoRest api
I started studying Django a few days ago and i want that when I click on a button it takes me to the url of my api. This is my urls from my app: from django.urls import path, include from animes import views from rest_framework import routers router = routers.DefaultRouter() router.register('animes', views.AnimesViewSet, basename='animes') router.register('nota', views.NotasViewSet, basename='notas') urlpatterns = [ ... path('api/', include(router.urls), name='api') ] the problem from my template is here: <a class="botao__link" href="{% url 'api' %}"><button class="botao__botao" type="submit">API</button></a> when i write the url manually i can go to the api without problems , but I can't go clicking the button -
Django ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
I know others have had a similar issues with and getting this same error, but I think my situation is unique. I am running Django 3.1.4 and on my local machine, I can run python manage.py shell with no issue. On the server instance, running what should be the same project, and the same version of Django, I get: Django ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' When trying to run manage.py shell. To make things more cryptic, if I open the shell on my local machine and run: from django.utils.encoding import python_2_unicode_compatible I get the same error. So for some reason when I call manage.py shell from my local machine it doesn't try to import python_2_unicode_compatible, but when I run it from the server it does. I can't find where the discrepancy is. Here is the full stacktrace if that is helpful: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], … -
I can't manage to import and use a javascript function from a .js into a django template. Ideas?
I have a javascript file project_dashboard.js with a few things defined inside of it and an html file where I try to call such function (amont other things). For some reason, I keep getting the error that the function is not defined at HTMLButtonElement.onclick. What drives me crazy is that the first part of the .js is loaded and works (the css is changed if I click on table). So the script is there, but I can't use the function. project_dashboard.js $('table').on('click', 'tr.parent .fa-chevron-down', function(){ $(this).closest('tbody').toggleClass('open'); }); function EnablePositionEdit(position_id) { const checked_events = [] $("#edit_button_____" + position_id).toggle() $("#save_button_____" + position_id).toggle() $("#delete_____" + position_id).toggle() inputs = document.querySelectorAll(".availability_____" + position_id + " input") inputs.forEach(input => { input.removeAttribute("disabled") }) } html {% extends 'action/base.html' %} {% block extrastylesheets %} {% endblock extrastylesheets %} {% block content %} <head> {% load static %} <link rel="stylesheet" href="{% static 'action/css/project_dashboard.css' %}"> <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> </head> ... <div id="edit_button_____{{ position.id }}" style="display: block;"> <button class="btn" style="font-size:10px; color: rgb(59, 89, 152);" onclick = EnablePositionEdit('{{ position.id }}')> <i class="fa fa-pencil"></i> </button> </div> ... {% endblock content %} {% block extrascripts %} <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script> <script type="text/javascript" src="{% static 'action/js/project_dashboard.js' %}"></script> <script> $(document).ready(function() { $('.summernotable').summernote({ toolbar: [], }); }); … -
The intermediary model has no field
i'm newbie in Django world i'm creating a web app to manage products in an online store i created the models for Catergories and Products here are my models : from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=255, unique=True, ) description = models.TextField(max_length=1500) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) categories = models.ManyToManyField('Category', through='CategoryProducts', through_fields=('category_name','product_name')) def __str__(self): return self.name class CategoryProducts(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, ) product = models.ForeignKey(Product, on_delete=models.CASCADE, ) When i try to make migrations , Two errors apear : products.Product.categories: (fields.E338) The intermediary model 'products.CategoryProducts' has no field 'product_name'. HINT: Did you mean one of the following foreign keys to 'Category': category_name? products.Product.categories: (fields.E339) 'CategoryProducts.category_name' is not a foreign key to 'Product'. HINT: Did you mean one of the following foreign keys to 'Product': product? -
Mongodb result and python result difference
when I query in studio3t, I get a response in .net uuid type, and when I query in python, I get UUID Version=1. How can I translate this output in python? mongo response; pyton response; {'_id': UUID('0fc97e3a-8f0c-be4f-a5dc-b166af761afd'), 'Version': 1,