Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djanog URLs: How to stop access to an url from the address bar?
I have a problem with my urls in my urls.py i have an url that must only be accessed with ajax, but recently i found out that i can call the ajax function if i type the url in the addressbar path('mydata-vacation/', views.mydata_vacations, name='mydata-vacations') if i go to my-website/mydata-vacation/ will execute the ajax command and it will render the page How to prevent it from doing that? my view is def mydata_vacations(request): user_data = get_user_data(request) user_id = user_data['id'] user_demands = Demands.objects.filter(user_id=user_id, type_of_demand='vacation').order_by('-id') context = user_data context['demands'] = user_demands return render(request, 'manager/vacation_table.html', context) and ajax is $.ajax({ type: "POST", url: '/mydata-vacations/', async: true, data: { csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(), }, success: function (response) { $(".table-row").html(response); $('.accept-btn').css('display','none'); $('.vacations-btn').css('display', 'flex') } }); the code works well but my question is how to deal with the url not to be accessible trough the browser addressbar -
Use template tag return value for conditional logic in template
I have a template tag that returns True or False. For example: @register.simple_tag def is_home(context): if homepage: return True else: return False I want to use this tag to change an icon in the template: {% if is_home %} <svg data-src="{% static 'images/cart_white.svg' %}" width="35" height="30"/> {% else %} <svg data-src="{% static 'images/cart.svg' %}" width="35" height="30"/> {% endif %} However the template tag is not called like this. Only if I call it like this: {% is_home %} it works but I cannot use the result for the conditional. Any idea how can I use the result for logic? -
Django Apache Error 502 Proxy Error
I have written a small Django app for my team running on a Windows 2012 server. As webserver I am using Apache + wsgi. Everything works fine, so I can access the webpage via ipadress + port: 123.45.67.89:8000 if I use a computer with usual webbrowser. Here is my problem: I want to access the page from Iphone. In our company we have the AirWatch Browser for accessing internal servers. The access to 123.45.67.89/phpmyadmin works fine. This is configured by Windows IIs services. But when I try to access 123.45.67.89:8000 I got a error 502. Now, I have read to configure my httpd.conf to listen the correct port. That I have checked but still does not work. As this is all propprietary I have no clue what I can check for further error. Do you have a hint? Thank you in advance. settings.py ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) PORT = config('PORT') .env ALLOWED_HOSTS=123.45.67.89, .localhost, 127.0.0.1 PORT=8000 httpd.conf Listen 123.45.67.89:8000 Timeout 600 ServerName 123.45.67.89 -
How can I use a catch all route using `path` or `re_path` so that Django passes all unmatched requests to my index view?
My url patterns look like this: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), re_path('.*', IndexView.as_view()), ] This works but it matches all URLs, including those prefixed with admin and api. I want those URLs to still match, and for any unmatched URLs to render IndexView. Before 2.0 I used this regex for this purpose. I tried using it in re_path but that didn't work, which is what led me to trying the above. url(r'^(?P<path>.*)/$', HtmlView.as_view()) Use case is a SPA where I handle 404s client side. Many thanks in advance. -
Why does initial migration have dependencies?
Without any prior migrations I have added custom User model in core app to enable custom authentication by following the documentation entry Django 2.0 / Customizing authentication in Django Then I made migrations: $ python manage.py makemigrations Migrations for 'core': core/migrations/0001_initial.py - Create model User At 0001_initial.py migration class begins with: class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] I have looked through the official documentation Django 2.0 / Migrations and this file obviously is an initial migrations since it has initial = True. But why does it have a whole chain of dependencies starting with 0009_alter_user_last_name_max_length? Did I made any mistake? When migrations are ran this is the output: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, core, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying core.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying sessions.0001_initial... OK When custom User model is omited 0001_initial.py starts with: class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] Additionally, I wasn't able to find β¦ -
Elasticsearch & haystack & django case insensitive query
{ "query":{ "bool":{ "must":[ { "wildcard":{ "title":"*Dior*" } } ] } }, "size":56, "from":0, "sort":[ { "created_at":"desc" } ] } this is the query I send when make a query, it is case sensitive unfortunally, as far as I know the elastic search is by default case insensitive, should I set the analyzer to lowercase filter? or should be this query enough to work? I'am using this: https://django-haystack.readthedocs.io/en/master/autocomplete.html?highlight=EdgeNgramField its working with django and haystack and elasticsearch, but I didnt found any information about case-insensivity problem in the link above(haystack EdgeNgramField), so the question is should I modify the search query or make some configuration to the server-side of haystack? I really didnt found much info about this thing so plaese help -
Static Files from Site working, but not from app
Some confusion about static files (Python 3.6 Django 2.. IIS 8.5) My static files from site are found but the static files from the app are not found. GET http://127.0.0.1:81/static/css/pyapp.css 404 (Not Found) I tryed to add: STATICFILES_DIRS =[(os.path.join(BASE_DIR, 'pyapp/static')),]"< to the settings.py but did not help. Do I have to add a web.config also in the app static like in the site static folder? ββββpyapp β ββββmigrations β β ββββ__pycache__ β ββββstatic β β ββββcss | β β ββββpyapp.css <=== this is not found β ββββtemplates β β ββββpyapp | β β ββββmy.html <=== this works β ββββ__pycache__ ββββpyweb ββββstatic <=== this works β ββββadmin β ...... ββββ__pycache__ -
class methods not found when extending Django User model
In Django 2.0, python 3.6.5 on Ubuntu: class UserProxy (django.contrib.auth.models.User): foo = django.contrib.auth.models.User.normalize_username ('abc') # OK bar = normalize_username ('abc') # ERROR class Meta: proxy = True The bar= line throws this exception: NameError: name 'normalize_username' is not defined Why isn't this method visible without the explicit namespace? The same error is thrown from within UserProxy.objects.create_user, which expects self.model.normalize_username to exist. -
How do I set the parameters for postgres conf file?
I have a 4 GB server with 80GB hard disk. The website is really slow when switching between pages. I checked top processes and postgres processes with 70 -100 % cpu usage keep popping up. they dont last for more than 4 seconds usually and then its a new one. In my postgres database table i have about 12 tables but one of them has about 90 million entries( rows). This is the table causing the slowdown. But how do i tune my postgres parameters like shared_buffer size and all for optimum performance? -
How to configure django-auth-adfs?
I'm using a demo project from https://github.com/jobec/django-auth-adfs/tree/master/demo/adfs Here are my settings: AUTH_ADFS = { "SERVER": "sso.example.com/FederationMetadata/2007-06/FederationMetadata.xml", "CLIENT_ID": "******-****-****-****-********", "RESOURCE": "localhost:8000", "REDIR_URI": "localhost:8000/oauth2/login", "CA_BUNDLE": False, "CLAIM_MAPPING": {"first_name": "given_name", "last_name": "family_name", "email": "email"}, } The program runs fine, but there is no way to enter the Admin panel or the user panel. By clicking on the link Admin or Login, without requesting a login and password, go to the page "Login failed". I can not figure out where I wronged the app. -
How to fix xxxx(name_of_the_model) matching query does not exist
when I tried to return an object with Django ORM query set am getting the answer but if I use raw query(with multiple joins ) am getting an exception as matching query does not exist. if I execute the same query in php-my-admin am getting the result. can anyone help why am getting this exception and how to fix it? thanx in the advance.. -
Integrating a data producer as worker to Django Channels 2.x
I am developing an application where realtime data that will be pushed to clients will come from an external API. A simple version of it can be thought like a foreign exchange currency tracker. The user will specifiy which currencies she wants to track (USD, Euro, GBP etc) and receive realtime updates. Currency data will come from an external API through long polling and can be updated very fast. My question is how to integrate this data producer to channels? In all channels examples I found worker's work is triggered by an event (i.e. but in my case it will start at the beginning, work continously and instead of receving events it will just push new values to channel layer so subscribers can be notified. So I am not sure consumer pattern is the right one. To summarize my questions: Shall I use a consumer for this task and how to setup it? Considering API will be accessed by long polling async or sync consumer? Start polling external API at its connect method or just send a one-time event for this? From where and when to send this "start working" event? I also want to use redis to store values β¦ -
Passing URL as a context in Django
I'm very very new to Django. I'd like to parse a txt file in javascript through a django template. The file is placed in static and gets loaded. Now I just need to make sure that the correct name is being passed along. What would be the best way of doing this ? <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Geoinfo SDE StateTree</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" type="text/css" /> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.4.0/papaparse.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script> <script type="text/javascript"> //IMPORTANT TO INCLUDE THESE LINES OR STATIC FILES SUCH AS WIL_sde_states.txt WILL NOT LOAD {% load staticfiles %} function reverse(s){ return s.split("").reverse().join(""); } var current_url = window.location.href var txt_file = reverse(reverse(current_url).substr(0, reverse(current_url).indexOf('/'))); var doc_location = "{{textfile}}" console.log(doc_location) console.log(txt_file) Papa.parse("{% static textfile %}", { download: true, complete: function(results) { var tree = results.data; var nodes = new vis.DataSet(); var edges = new vis.DataSet(); var levels = []; etc......... The reason I need this is because I want to render/create different state-trees depending on which URL I'm currently situated. From what I've read its impossible to pass a javascript variable to a django static tag so I haven't been able to maneuever that way either. I've tried passing it through context but the code pasted below β¦ -
Update Related Models When Deleting DJANGO
I have a model that can be deleted in my app - Project User I want when the model is deleted every other Model that relates to it must be updated to a system user - so update all the references to this Project User to another user. Is that possible Thanks Appreciate all the suggestions. -
Connecting to signals sent by specific senders do not work as expected
I have models strucute as below class WalletTransactions(models.Model): ... fields here ... class WalletBalance(models.Model): ... fields here ... Signal handler like below @receiver(post_save, sender=WalletTransactions) def update_balance(sender, instance, created, **kwargs): print instance.payment_type #field in model And finally registration post_save.connect(update_balance, dispatch_uid=uuid.uuid4()) Now I am expecting update_balance to be called only when save on WalletTransaction is called as per doc. But when I am trying to login to my application, the update_balance is being called when save on Session is called throwing following error. AttributeError at /login/ 'Session' object has no attribute 'payment_type' What could be the mistake here? -
JSON response cannot find page
Hello guys I'm trying to get a json response but I think i'm making mistakes defining the urls. Here is my script bellow. views.py from django.shortcuts import render from django.views.generic import TemplateView from django.core.serializers import serialize from django.http import HttpResponse from .models import ww_manholes from django.http import JsonResponse class MapView(TemplateView): template_name = 'index.html' def layer_datasets(request): ww_manholes = serialize('geojson', layer.objects.all()) return HttpResponse(ww_manholes, content_type='json') index.html <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title>Map</title> <style type="text/css"> #gis {width: 80%;height:600px;} </style> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}"> </script> </head> <body> <br> {% leaflet_map "gis" %} </body> </html> urls.py child app from django.conf.urls import include, url from django.urls import path from django.views.generic.base import TemplateView from views import Mapview, layer_datasets urlpattern = [ path('index/', MapView.as_view(template_name="index.html")), #url(r'^layers/$', layer_datasets, name = 'layer'), path('layer/', views.layer_datasets, name='layer'), ] urls.py parent app from django.urls import path from django.conf.urls import url, include from django.contrib import admin from layer.views import MapView urlpatterns = [ url(r'^admin/', admin.site.urls), path('index/', MapView.as_view()), ] The tutorial I'm seeing uses url instead of path and I'm finding it difficoult since I'm a begginer to understand. -
Pyinstaller unable to find staticfiles for django admin
I'm using pyinstaller to convert django project into application. Everything works fine except for django admin. Pyinstaller is unable to find static files for django admin. How can I make it look for static files for django admin? -
Django form initial value changes after save
I use a custom form inherited from django's UserCreationForm to add user. How ever i have to set different initial value for username field.It works perfectly but after hitting save button the user get saved with a different username than the initial value shown in the form.You can find the code below from django.contrib.auth.forms import UserCreationForm class AdminUserCreationForm(UserCreationForm): """ AdminForm for creating an instance of custom USER_MODEL. """ email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email") field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initial['username'] = random_username_generator() self.fields['username'].disabled = True self.fields['password1'].required = False self.fields['password2'].required = False def clean_username(self): username = self.cleaned_data['username'].lower() try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError('A user with username {} already exists'.format(username)) def clean_email(self): email = self.cleaned_data['email'].lower() try: User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError('A user with email {} already exists'.format(email)) def save(self, commit=True): import ipdb; ipdb.set_trace(); user = super(AdminUserCreationForm, self).save(commit=False) # user = self.instance qb = QuickBlox() qb_password = reset_password_generator() user.qb_password = qb_password + 'vx' user.save() attempt = LoginAttempts() attempt.user = user attempt.save() send_invite_mail(user) return user -
Unable to call viewset from the android app using django server
The problem I am experiencing is that when my android app makes a GET request it is not calling the IgnitionViewSet. We have made it so when IgnitionViewSet is called it updates the data. It works when you go through the browser and make a get query. class IgnitionViewSet(viewsets.ModelViewSet): """ API endpoint that allows to view variables from the ignition database. """ serializer_class = IgnitionSerializer permission_classes = [HasGroupPermission] required_groups = { 'GET': ['Admin', 'Facility', 'Operator'], 'PUT': [], 'POST': [], } def dispatch(self, request, *args, **kwargs): ignition.getIgnitionData() return super(IgnitionViewSet,self).dispatch(request, *args, **kwargs) def get_queryset(self): return Ignition.objects.all() 1) How can I make it so it is called when a GET request is made from my android application? 2) Is it because we are not viewing it from the android application? On android app we only want the updated data which we will display later. -
Django rest framework is not logging in the non superusers after calling user model to the serializers
i want to get user data with get method in api but when I used custom user model its is not logging in logginf this error { "non_field_errors": [ "No active account found with the given credentials" ] } how can i handle this? only the super user in loggin in rest of the users are not loggin in serializer.py from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name','username','password','email') views.py from django.contrib.auth.models import User class CurrentUserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer urls.py router.register('Users',views.CurrentUserView) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'languages', 'corsheaders'] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', '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',] -
Django - calculate average of time between created_at and done_at
Lets say i have 100 objects in db and each object has created_at and done_at time. I want to calculate average of duration for all objects. Have idea like this: first to calculate durations of all objects and then get average. But is there other good way that will help? -
Django Forms saving request.user in ManyToMany fields
I have a simple Group model that users can be added. class Group(models.Model): name = models.CharField(max_length=50) users = models.ManyToManyField(settings.AUTH_USER_MODEL) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='admin_on_group') date_created = models.DateTimeField(auto_now_add=True) date_modifies = models.DateTimeField(auto_now=True) def __str__(self): return self.name I have a basic CreateView for the group. The logged in user who creates the group get saved in the field 'created_by'. I however ALSO want to save the same logged in user in the field 'users' so that he can participate as a normal member of the group. The problem is that the view ends up ONLY saving the logged in user and the other users passed in from the form field 'users' are not saved. For example, If a user called 'george' creates a group, he should be added in the 'created_by' and 'users' as well. As of now, when i select other users in the form, only george gets saved in both fields. class GroupCreateView(CreateView): form_class = GroupForm template_name = "groups/group_create.html" def form_valid(self, form): form = form.save(commit=False) form.created_by = self.request.user form.save() # Apparently you can only add M2M relationships saves after first #saving form.users.add(User.objects.get(pk = self.request.user.pk)) return HttpResponseRedirect(reverse('group_list')) def get_form_kwargs(self): kwargs = super(GroupCreateView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs I have a β¦ -
Celery not configuring different queues
I've installed celery 4.1.1 and setup queues and routes but the worker accepts data only via name 'celery'. BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_DEFAULT_QUEUE = 'default' CELERY_TASK_SERIALIZER = 'json' CELERY_DEFAULT_ROUTING_KEY = "default" CELERY_DEFAULT_EXCHANGE = "default" CELERY_DEFAULT_EXCHANGE_TYPE = "direct" CELERY_QUEUES = { 'default': { "exchange": "default", "binding_key": "default" }, 'recon_queue': { "exchange": "recon_queue", "routing_key": "recon_queue" } } CELERY_ROUTES = { 'reconciliation.tasks.sync_bag': {'queue': 'default'}, 'common.consumer.kafka_consumer': {'queue': 'recon_queue'} } CELERYBEAT_SCHEDULE = { "kafka_consumer": { 'task': 'kafka_consumer', 'schedule': crontab(minute='*/01'), }, } The periodic task is run via celery beat. This command works fine - celery -A inferno worker -l info -Q celery -c1 This worker does all the tasks itself. But these commands dont have any effect celery -A inferno worker -l info -Q default -c1 celery -A inferno worker -l info -Q recon_queue -c1 -
Django rest createAPIView with choice list
I'm struggling with a particular case I'm using the API Create View from Django Rest to create an entity called post, the model of post has a foreignkey pointing to another model called group, the serializer of post has the group as a GroupModelSerializer field, when I create the post I get group fields to fill in the form, if I set the field of group as read_only, they'll be ignored during the POST method How to get a list of groups to choose from when creating my post entity Here's my code: my post serializer: class PostModelSerializer(serializers.ModelSerializer): user = UserModelSerializer(read_only=True) group = GroupModelForCreateSerializer() class Meta: model = Post # the model to get fields from fields = [ 'id', 'group', 'user', 'content', 'timestamp', ] my group serializer: class GroupModelSerializer(serializers.ModelSerializer): class Meta: model = Group # the model to get fields from fields = [ 'id', 'moderators', 'name', 'description', 'timestamp' ] my API create view from Rest Framework : class PostCreateAPIView(generics.CreateAPIView): serializer_class = PostModelSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): serializer.save(user = self.request.user) -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. file init
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Exception appeared when i added: import signals in init.py file (apps/application/_init_py) from models import Review in signals.py file (apps/application/signals.py) I want to send an http request when there is an insert in the model Review. So i need to import Review model (in _init_py file) to execute the following code: @receiver (pre_save, sender = Review) def my_handler (sender, ** kwargs): ....