Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The model is sorting the items by id not alphabetically
I have a main model called Produto. On this model, the items shows up like they have, alphabetically(see below). Also I have another one, called EstoqueSede, that has a FK to the Produto model(It's a stock application, so i have a product Produto model to register the items separated to the stock and two another stock models to hold the current amounts and some other values(of the mainstock and the substocks), because i have two stocks that access the product model Produto and this two models are not showing alphabetically(see below either), just the main model Produto. Like i said, when a try to query the Produto model, the items shows as the intention, but when i show the EstoqueSede model items, instead of show the items alphabetically as the Produto model, it shows the items in the order that it was created in the database MySql, but actually, is ordering by the ID's of the EstoqueSede model... When i override the get_queryset(self, obj) on Admin of the EstoqueSede, i could get those values alphabetically when i click in the model(see also below), but when i want to order the items within the model, with the /?=0 or /?=-0 url(or … -
How to ensure code runs every time a view is called - Django
With respect to Django generic Views, how do you get a function to run every time a view is called? For example, when I do: class infoRequestPage(CreateView): model = InfoRequest form_class = moreInfoForm template_name = 'info_request.html' success_url = reverse_lazy('HomePageView') pageVisit = InfoRequest( infoName = autoName, infoRegion= autoRegion,) pageVisit.save() print("test") It will return test as expected, but only the first time I load the page.However, if I update the source code and change the print command to something different like "testing", it will run again. But like last time, only the first time the page loads. I have tried to clear the cache, and restart browser, but both do nothing. It seems to run only once until the code is changed. -
How to suppress controls of a related model on django admin
I have two related models on django 2.2.4. I only want to allow one model to be editable, for the other it is only allowed to be related to the first one. The model that is not editable is a State model. Must never change. The second model is a User model. Must use the State model as a field related only. Here is the code: class State(models.Model): def __str__(self): return str(self.name) name = models.CharField(max_length=30) class User(models.Model): def __str__(self): return str(self.name) name = models.CharField(max_length=200, blank=False) state = models.ForeignKey(State, models.DO_NOTHING, blank=True, null=True) So there are two questions: 1) I would like to hide the State model from the admin, avoiding that any data could be changed. Is that possible? 2) In the User model in the admin, in the screen to insert a User, there are shortcuts to edit the State model. Is there a way to get rid of these controls? -
Is there a logout_required equivalent to login_required in Django?
Django provides the very useful @login_required views.py decorator, which you can also call as a function (login_required()) in urls.py. It redirects a user without authentication to settings.LOGIN_URL. Is there a similar decorator for @logout_required, such that the view is only rendered if the user is not authenticated, otherwise redirected to settings.LOGOUT_URL or equivalent? -
Proper Angular-side (frontend-side) implementation of token-based Authentication check
About my problem I am a total beginner which implements a web app (frontend Angular6, backend django[MySQL]). I am aiming to deploy it to a production environment, so I concern about authentication and authorization issues. The purpose of this post is about how to properly implement a Token-based (simple or even better JWT Auth) or even another proposed Authentication system. What I have came across So, in each angular tutorial about token-based authentication that I have watched at youtube, there is being implemented an "authentication service", say authService, that stores either token (in case of constant token) or token along with refresh_token (in case of JWT-Auth) at localStorage whenever a user logs in to the app. Thus, if they (tutorials) want a component to be loaded only to logged-in users, they attach a "CanActivate Guard", say authGuard, to that component. The problem comes right here. The authGuard checks if there is a logged-in user by checking only the existence of the corresponding data (e.g. a key-value pair, where key="token") within localStorage variable. Also, there is not being any kind of verification (e.g. communication with the backend) for the value of that token and finally, this token will be attached to … -
How to route tasks to queues while using Docker
I’m setting up multiple workers which execute tasks based on given queues with in a docker environment. I'm unable to see queues that I have declared in settings.py I've seen that the worker command that is on the top(in container command) is only getting executed and the rest are not being executed. This is how I'm trying to route celery tasks in settings.py # Celery settings CELERY_BROKER_URL = 'redis://:secret@redis:6379/0' CELERY_RESULT_BACKEND = 'redis://:secret@redis:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_TASK_ROUTES = { 'app1.tasks.*': {'queue': 'emails'}, 'app2.tasks.*': {'queue': 'parser'}, 'app3.tasks.task1': {'queue': 'sms'} } This is how Im writing my tasks.py file. @app.task(bind=True, queue='parser') def parser(self, extension, data, file): return True This is how Im giving commands in my docker-compose.yml file in a container version: '3.3' services: api: restart: always build: ./app volumes: - ./app:/app/ depends_on: - redis command: bash -c 'python3 manage.py makemigrations --noinput && python3 manage.py migrate --noinput && celery -A app worker -l info -Q email-n worker1 && celery -A app worker -l info -Q parser-n worker2 && celery -A app worker -l info -Q sms-n worker3 && celery -A app worker -l info && celery -A app beat -l info && python3 manage.py … -
In django, is it a bad practice to retrieve database records with slug fields loaded by fixtures?
I am working on a code base where the original developer created a 'ProductType' model with several rows in the database representing a few product types. Throughout the code, there are statements like ProductType.objects.get(slug='foo_product_type'). These statements will cause a hard crash if fixtures haven't loaded the ProductType record with slug = 'foo_product_type'. What is the best practice to define the ProductType with slug 'foo_product_type'? It seems like python code shouldn't depend on fixtures being loaded, but I really can't think of another solution. I have worked with using choices= on the model definition, but that seems to be more for data integrity as opposed to loading a record with details like price so that doesn't help me. I currently load fixtures after migrating a new database, and that works, but I'm curious if anyone has a better solution. if ProductType.objects.get(slug='foo_product_type'): when ProductType with slug 'foo_product_type' doesn't exist. When the fixture is loaded, the object is grabbed for use in code. When record is missing, app crashes. -
dataframe is not correctly showing in django templete
Actually i'm applying some pandas function to my dataframe its working correctly on my console but when i pass my dataframe to templete is not showing correctly i tried with to_html but in that pandas function is not applying correctly and give Error of this " 'Series' object has no attribute 'to_html' " therefore now I'm passing the data to template page view.py def checking(request): df = pd.read_csv('nba.csv') df = df[:10] return render(request,'data.html', {'df': df } data.html inside div tag <div> {{ df }}<div> dataframe table should be show in data.html but it was showing all the result in one line not changing any of the row and column -
Is there a way for a Django Project running on an Apache Server bilaterally communicate with an external python script?
I have a Django project running on an Apache2 server for a web application that shows the status of certain external drives. I used to have some linux commands called in a python script that dealt with mounting/unmounting hard drives inside the project. However I had to move the commands to a new external python script as the computer didn't recognize the changes of mount/unmount of the drives since it was hidden inside the virtual environment. I now need this external python script to communicate to the Django project's python script to tell if a drive was mounted along with the Django project to tell the python script to unmount a certain drive. I tried creating a WebSocket to provide bidirectional communication as pipes are only a single direction. But I can't get the WebSocket to connect/run when it's called in the Django app. def Tcp_connect( HostIp, Port): global s s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HostIp, Port)) return def Tcp_Write(D): s.send(D + '\r') return def Tcp_Read( ): a = ' ' b = '' a = s.recv(1) while a != '\r': b = b + a a = s.recv(1) return b def Tcp_Close( ): s.close() return def start(self,request): Tcp_connect( '127.0.0.1', 17098) … -
How to write not in sql query in Django
Im new to Django. Anyone help me to write "Not In" sql query in django. query = 'SELECT basic_uom FROM uom_master WHERE id="'+ id +'" and basic_uom not in (SELECT next_uom from uom_master WHERE id="'+ id +'") and basic_uom not in(SELECT std_uom FROM std_uom_master WHERE id"'+ id +'"ORDER BY next_uom ASC' data = uom_master.objects.raw(query) Here how to write this without raw() query set. -
FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
I got that error when i execute runserver and i try to access the API I check imports, models, serializer, viewsets and urls. Don't know what does it means "The system cannot find the path specified: ''" Here you have a screenshot of the error: API I got that exception when i go to http://127.0.0.1:8000/api/v1.0/notes/ Environment: Request Method: GET Request URL: http://127.0.0.1:8000/api/v1.0/notes/ Django Version: 2.2.4 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'note', 'rest_framework'] Installed Middleware: ['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:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\core\handlers\base.py" in _get_response 145. response = self.process_exception_by_middleware(e, request) File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\core\handlers\base.py" in _get_response 143. response = response.render() File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\template\response.py" in render 106. self.content = self.rendered_content File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\response.py" in rendered_content 70. ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\renderers.py" in render 725. context = self.get_context(data, accepted_media_type, renderer_context) File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\renderers.py" in get_context 656. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\renderers.py" in get_raw_data_form 564. data = serializer.data.copy() File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in data 559. ret = super().data File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in data 265. self._data = self.get_initial() File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in get_initial 409. for field in self.fields.values() File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\django\utils\functional.py" in __get__ 80. res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\lrond\Desktop\projectEnreda\env\lib\site-packages\rest_framework\serializers.py" in fields 360. … -
Provided og:image URL, [url to AWS S3] could not be processed as an image because it has an invalid content type
Building my company website and want the image to display when I share the link on facebook. The correct meta description and titles show up for each page but not the images. The facebook debugger tool keeps giving me this error and everytime I share a link it says that it has an invalid content type. I want my logo to appear for everytime I share a link on facebook so I have it extended in my base.html file. This is in my base.html page: <meta property="og:image:url" content="{% static 'img/ssg600.png' %}"/> <meta property="og:image:secure_url" content="{% static 'img/ssg600.png' %}"/> <meta property="og:image:type" content="image/png" /> <meta property="og:image:width" content="600"/> <meta property="og:image:height" content="600"/> <meta property="og:type" content="website"/> The static link is attached to my aws s3 account and before I even started working with these meta tags, the image was displaying on FB just fine. Now its not working and I can't figure out why. -
Reverse for 'about_me' not found. 'about_me' is not a valid view function or pattern name
What's happening. I still have trouble displaying the title list. Where did I make a mistake? views.py def dashboard(request): bookmarks = Text_field.objects.order_by('created') return render(request, 'Site/dashboard.html', {'bookmarks': bookmarks}) def about_me(request, pk): about = get_object_or_404(Text_field, pk=pk) return render(request, 'Site/about_me.html', {'about': about}) dashboard.html {% extends "Site/base.html" %} {% load static %} {% block content %} {% for bookmark in bookmarks %} <div> <p>Stworzono dn. {{ bookmark.created }}</p> <h1><a href="{% url "about_me" pk=about.pk %}">{{ bookmark.title }}</a></h1> <p>{{ bookmark.text|linebreaksbr }}</p> </div> {% endfor %} {% endblock %} urls.py path('about/<int:pk>/', views.about_me, name='about_me'), -
when i applied python manage.py migrate
from django.db import models from django.contrib.gis.db import models class incides(models.Model): name=models.CharField(max_length=100) location=models.PointField(srid=4326) def __str__(self): return self.name class Meta: verbose_name_plural='incides' class welcome(models.Model): fips = models.CharField(max_length=20) iso2 = models.CharField(max_length=20) iso3 = models.CharField(max_length=3) un = models.IntegerField() name = models.CharField(max_length=50) area = models.IntegerField() pop2005 = models.BigIntegerField() region = models.IntegerField() subregion = models.IntegerField() lon = models.FloatField() lat = models.FloatField() geom = models.MultiPolygonField(srid=4326) def __str__(self): return 'Name: %s' % self.fips ''' -
PostgreSQL Environment variables in Docker Compose 'No password has been set for the database'
I am working on a project using Django and am trying to load an .env file to the PostgreSQL image in my docker-compose.yml script. However, for some reason, I can't load them. After I run the 'docker-compose up' command, one of the warnings I get from db_1 is as follows: . . . db_1 | **************************************************** db_1 | WARNING: No password has been set for the database. db_1 | This will allow anyone with access to the db_1 | Postgres port to access your database. In db_1 | Docker's default configuration, this is db_1 | effectively any other container on the same db_1 | system. db_1 | db_1 | Use "-e POSTGRES_PASSWORD=password" to set db_1 | it in "docker run". db_1 | **************************************************** . . . To help reproduce the problem, here's my folder structure: My project structure: ├── config/ │ ├── .env ├── src/ │ ├── manage.py │ └── core │ | ├── __init__.py │ | ├── settings.py │ | ├── urls.py │ | ├── wsgi.py ├── docker-compose.yml ├── Dockerfile └── requirements.txt My Dockerfile: FROM python:3.7.0 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ My docker-compose.yml: version: '2' … -
Django pages won't load after installing pgAdmin4
I just installed pgAdmin4 so I could inspect my database visually and forgot to change the port from 5432 to 7000 and now when I run the django server by doing python3 manage.py runserver 7000 it just keeps loading and never actually loads the page. When I try to run the server with 5432 or 8000 it says that both are in use. When I set up the server I used localhost on port 5432 I deleted the server in the pgAdmin page and it didn't help. If you need more context please tell me and I'll modify the question. -
Reverse for 'index' not found. 'index' is not a valid view function or pattern name
I have a simple return HttpResponseRedirect(reverse('index')) where 'index' is the name of the view. on running the server the index view is correctly displayed but gives out this error "NoReverseMatch at /vehicle_movement/checkinview"on redirecting. I was working on django 1.1 for the same project but switched to django 2.2 later. Redirect was working fine with url django 1.1 but gives this error with path django 2.2. Another change that i have done is earlier in 1.1 project the index view url was written in the main url.py but now it is written in the apps urls.py. This is views.py def index(request): return render(request,'vehicle_movement/index.html',{}) def CheckinView(request): if request.method == "POST": checkin_form = CheckinForm(data = request.POST) if checkin_form.is_valid(): checkin_form.save() return HttpResponseRedirect(reverse('index')) else: HttpResponse("Error") else: checkin_form = CheckinForm() return render(request,'vehicle_movement/checkin.html',{'checkin_form':checkin_form}) This is the Main urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include(('vehicle_movement.urls','vehicle_movement'),namespace = 'vehicle_movement')), ] This is app urls.py app_name = 'vehicle_movement' urlpatterns = [ path('', views.index, name='index'), path('index', views.index, name='index'), ] This is the structure Warehouse -Warehouse -init.py -settings.py -urls.py -static -templates -vehicle_movement -urls.py -views.py The TEMPLATES_DIR TEMPLATES_DIR = os.path.join(BASE_DIR,'templates') `` -
Custom tags (templatetags) not loading
I'm trying to create a template tag so I can find out which group the current user belongs to. I have the same set up in another project but that one is working, but this one does not. This is what I have: Project structure: myproject - home -- templatetags --- __init__.py --- custom_tags.py -- __init__.py -- urls.py -- ... settings.py: INSTALLED_APPS = [ ..... 'home.templatetags', ] custom_tags.py: from django import template register = template.Library() @register.filter def has_group(user, group_name): return user.objects.filter(group_name=group_name). home_base.html: {% extends 'navbar.html' %} {% block content %} {% load custom_tags %} {% endblock %} Traceback: Internal Server Error: / Traceback (most recent call last): File "D:\Projects\1-2-1\monthlymeeting\venv\lib\site-packages\django\template\defaulttags.py", line 1021, in find_library return parser.libraries[name] KeyError: 'custom_tags' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Projects\1-2-1\monthlymeeting\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Projects\1-2-1\monthlymeeting\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Projects\1-2-1\monthlymeeting\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Projects\1-2-1\monthlymeeting\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "D:\Projects\1-2-1\monthlymeeting\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "D:\Projects\1-2-1\monthlymeeting\home\views.py", line 9, in get return render(request, self.template_name, {'entry': 1}) File "D:\Projects\1-2-1\monthlymeeting\venv\lib\site-packages\django\shortcuts.py", line 36, in render content = … -
Creating a custom Django widget that uses several input fields and JavaScript
What would be the best way to go about creating a functionality layer to turn a basic text widget from form.CharField into one with several fields and JavaScript functionality, yet would still map to the same CharField, when submitted. I can think of a way where the original text input widget would be hidden with JS and then the array of new fields would be created, but I am not sure how well that would scale when several of these fields would have to be instantiated. I'm hoping there would be a better, cleaner way to do this. -
What is the difference between creating a model instance using the default Manager and Customer Manager
While going through the official Django documentation I came across the Model Instance reference section in which it is mentioned that you can create an instance of the model using the custom Model using self.create. I wanted to know what's the difference between using the create method and the custom create_method when both are using the same fields and in both the cases the data is being saved in the DB. Documentation: https://docs.djangoproject.com/en/2.2/ref/models/instances/#creating-objects class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title) return book class Book(models.Model): title = models.CharField(max_length=100) objects = BookManager() book = Book.objects.create_book("Pride and Prejudice") Difference between these two book2 = Book.objects.create(title="Pride and Prejudice") -
Django db_index=True not create index after migration
I have an abstract model: class ChronoModel(models.Model): created = models.DateTimeField( u"Create time", auto_now_add=True, db_index=True ) modified = models.DateTimeField( u"Last change time", auto_now_add=True, db_index=True ) class Meta(object): abstract = True ordering = ('-created', ) And I have several models inherited from ChronoModel. My problem is same for all of them - for example one of this models: class BatchSession(ChronoModel): spent_seconds = models.BigIntegerField( u"spent_seconds", default=0, editable=False) max_seconds = models.BigIntegerField( u"max_seconds", null=True, blank=True) comment = models.CharField( u"comment", max_length=255, null=True, blank=False, unique=True) class Meta(ChronoModel.Meta): verbose_name = u'Session' verbose_name_plural = u'Sessions' ordering = ('-modified',) db_table = 'check_batchsession' def __unicode__(self): return u'#{}, {}/{} sec'.format( self.id, self.spent_seconds, self.max_seconds) After creating and applying migration there is not index on fields "created" and "modified" Command python manage.py sqlmigrate app_name 0001 | grep INDEX Shows me BEGIN; .... CREATE INDEX `check_batchsession_e2fa5388` ON `check_batchsession` (`created`); CREATE INDEX `check_batchsession_9ae73c65` ON `check_batchsession` (`modified`); .... COMMIT; But mysql returns me: mysql> SHOW INDEX FROM check_batchsession; +--------------------+------------+--------------------------------------------------+--------------+-------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | +--------------------+------------+--------------------------------------------------+--------------+-------------+ | check_batchsession | 0 | PRIMARY | 1 | id | | check_batchsession | 0 | check_batchsession_comment_558191ed0a395dfa_uniq | 1 | comment | +--------------------+------------+--------------------------------------------------+--------------+-------------+ 2 rows in set (0,00 sec) How can I resolve it? Django 1.8.18 … -
How to prevent deletion of Django model from Django Admin, unless part of a cascade
I have a project using Django 2.2.4. I have a Django model called Company. I use a post_save signal to make sure that as soon as a new Company is created, a new model instance called "Billing" is created, which is associated with that Company. This contains the company's billing information. This works great. Since my Billing object is associated with a Company, and I use on_delete=models.CASCADE, as soon as the Company is deleted, the Billing object associated with that company is automatically deleted as well. This works great too. Since the Billing object for each company is now automatically created and deleted along with the Company, there's no need for admins using the Django Admin web interface to ever have to manually create, or delete Billing objects. I want to hide this functionality from them. Normally, the common way to prevent Django Admin from allowing someone to add or delete an object is by adding this to that model's ModelAdmin in admin.py: class BillingAdmin(admin.ModelAdmin): ... # Prevent deletion from admin portal def has_delete_permission(self, request, obj=None): return False # Prevent adding from admin portal def has_add_permission(self, request, obj=None): return False This works, and does indeed hide the ability for Admins … -
Why am I getting an error SyntaxError: unexpected EOF while parsing whereas I did not get it before
I am at the beginning of my project, I a priori finished the first feature (registration), and my site has already worked without error. But since this morning, it appears an error (it seems to me of syntax) that had never appeared before. Would it come from an update? Yet I did not do it voluntarily. The error : (venv) D:\Users\Robin\Documents\programmation\RepertoireGit\MaisSemence82\MaisSemence82>manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Robin\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Robin\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\Users\Robin\Documents\programmation\MaisSemence82\venv\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module return … -
pass value from PHP to Django
I have a PHP login page which authenticates the user and redirect the user to Django application but I need to post the username to Django application to know which user has logged in. I have tried to pass the user name as variable from PHP application and I have a get method but it's not the right way as the user can access the application just by changing username to some dummy name in the URL. PHP redirection: header("location: http://192.168.113.75:9200/NewHandBook/login?user=".$Username); Django get method: def login(request): userName = request.GET.get("user") print("Login user" + userName) return render(request, 'login/login.html', userName) -
django annotate with queryset
I have Users who take Surveys periodically. The system has multiple surveys which it issues at set intervals from the submitted date of the last issued survey of that particular type. class Survey(Model): name = CharField() description = TextField() interval = DurationField() users = ManyToManyField(User, related_name='registered_surveys') ... class SurveyRun(Model): ''' A users answer for 1 taken survey ''' user = ForeignKey(User, related_name='runs') survey = ForeignKey=(Survey, related_name='runs') created = models.DateTimeField(auto_now_add=True) submitted = models.DateTimeField(null=True) # answers = ReverseForeignKey... So with the models above a user should be alerted to take survey A next on this date: A.interval + SurveyRun.objects.filter( user=user, survey=A ).latest('submitted').submitted I want to run a daily periodic task which queries all users and creates new runs for all users who have a survey due according to this criteria: For each survey the user is registered: if no runs exist for that user-survey combo then create the first run for that user-survey combination and alert the user if there are runs for that survey and none are open (submitted__isnull=False) and the latest one's submitted date plus the survey's interval is <= today, create a new run for that user-survey combo and alert the user Ideally I could create a manager method …