Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
conditionally change django template variable
tl;dr I need a template variable to change by concatenating strings along the way. my issue I'm looping through a queryset in my template, and inside the loop I'm checking if certain fields on the object match the current user. If so, then my variable changes and is finally applied as a class to an element. {% for item in items %} {% with class="" %} {% if request.user == item.field1 %} /* append to class variable, ex: class=" field1" */ {% endif %} {% if request.user == item.field2 %} /* append to class variable, ex: class=" field1 field2" */ {% endif %} <div class="{{class}}"></div> {% endwith %} {% endfor %} So, if my request.user equals both item.field1 and item.field2 then my element would look like this: <div class=" field1 field2"></div> And if my request.user equals only item.field2 then my element would look like this: <div class=" field2"></div> -
Reuse a Django_filter for multiple models
I have a very basic filter setup (using django-filter) which allows me to query my data from my django rest api using date ranges: /api/v2/metrics/?date=2017-01-01 /api/v2/metrics/?start=2017-03-03&end=2017-04-01 /api/v2/metrics/?start=2017-03-03 etc. My filters look something like this: class DateFilter(filters.FilterSet): start = filters.DateFilter(name='date', lookup_expr='gte') end = filters.DateFilter(name='date', lookup_expr='lte') class Meta: model = GaData fields = ['date'] And my API view sets are: class GaDataViewSet(viewsets.ModelViewSet): queryset = GaData.objects.all() serializer_class = GaDataSerializer filter_class = DateFilter def get_queryset(self): # This returns metrics only for the logged in user user_id = self.request.user.id return GaData.objects.filter(owner=user_id) class CountriesViewSet(viewsets.ModelViewSet): queryset = GaCountries.objects.all() serializer_class = GaCountriesSerializer def get_queryset(self): # This returns metrics only for the logged in user user_id = self.request.user.id return GaData.objects.filter(owner=user_id) Now, the DateFilter is linked to the GaData model, I could re-write an identical filter and link it to my other model (GaCountries) but I think that there must be a better way, so that I don't need to write the same piece of code for each model. How can I use a filter for multiple models, or can I simply somehow overwrite the model? Thanks -
How can I change the folder of a plugin in Django CMS?
I've created a new plugin using: //create a new plugin > ./manage.py startapp hero And added it to the settings.py It created a structure to which I've added files: - hero - static hero.css - templates hero.html __init__.py cms_plugins.py models.py I want to put all the plugins in a new directory: - plugins - hero - other plugin How can I change a plugin's folder in Django CMS? -
NameError: name 'state' is not defined
I have an error in python code (in my django app): NameError: name 'state' is not defined I got error in this place: self.import(state, *args, **options) The import method is below calling (but in the same class) def import(self, state, *args, **options): with Handler(mode) as self.evis: for model in get_models(): self.update_objects(model) self.remove_objects(model) -
Checking if form input exists [Django]
I have a Django form that a user enters one input into. After submitting they are taken to a URL associated with their input. The database contains user_input and associated_url fields. The user_input has the value unique=True set. When a duplicate input is entered the following displays on the website This value user_input already exists in the database even though I didn't set this so it. This may be feature of form.is_valid()? So it immediately recognizes duplicate values, but I am trying to set it so that if a duplicate value is entered then it will just take the user to the associated_url for that value. i.e. Existing database table: user_input associated_url hello https://stackoverflow.com If a user were to input hello into the form again, it would immedietly take them to https://stackoverflow.com instead of showing This value user_input already exists in the database Code: def Primary(request): form = Form() if request.method == 'POST': form = Form(request.POST) if form.is_valid(): ... saving to database, redirect etc. I need to be able to check if the input value is a duplicate. If it is then get the associated_url from the same row as the duplicate user_input entry and redirect the user there. To … -
How to sort GET query according to the specified rules
I'm using url_replace to add GET query like below. @register.simple_tag def url_replace(request, field, value): get_params = request.GET.copy() get_params[field] = value return get_params.urlencode() <p>[ Category ]</p> <ul> {% for cat in cats %} <li><a href="?{% url_replace request 'category' cat.slug %}">{{ cat.name }}</a></li> {% endfor %} </ul> <p>[ Job Type ]</p> <ul> {% for type_value, type_name in types %} <li><a href="?{% url_replace request 'type' type_value %}">{{ type_name }}</a></li> {% endfor %} </ul> It arranges GET query every time clicks specified link. For example: 1) current URL: /jobs/ click <a href="?{% url_replace request 'category' cat.slug %}">{{ cat.name }}</a> URL changes: /jobs/?category=cat.slug then click <a href="?{% url_replace request 'type' type_value %}">{{ type_name }}</a> URL changes: /jobs/?category=cat.slug&type=type_value 2) current URL: /jobs/ click <a href="?{% url_replace request 'type' type_value %}">{{ type_name }}</a> URL changes: /jobs/?type=type_value then click <a href="?{% url_replace request 'category' cat.slug %}">{{ cat.name }}</a> URL changes: /jobs/?type=type_value&category=cat.slug But I want to sort these GET queries always category first and next is type. always: /jobs/?category=cat.slug&type=type_value not: /jobs/?type=type_value&category=cat.slug How can I do this? -
Can I use a django rest framework ModelViewSet to render its form and pass the list json to a regular view?
I want to use the rest framework api to render the json data from the list method and the form from the post in a template. I have been searching in the rest-framework docs for the renderer clases, Html rendering and form rendering but came to no solution. This is the relevant code //models.py class Collaborator(models.Model): user = models.OneToOneField(User, related_name='collaborator', on_delete=models.CASCADE ) area = models.ForeignKey(Area, verbose_name=_('Área del colaborador'), related_name='collaborator' ) position = models.ForeignKey(Position, verbose_name=_('Cargo del Colaborador'), related_name='collaborator' ) photo = models.ImageField(_('Fotografía del colaborador'), null=True, blank=True, help_text=_('Fotografía del Colaborador'), ) birth_date = models.DateField(_('Fecha de Nacimiento'), null=True, blank=True ) join_date = models.DateField(_('Fecha de Ingreso'), null=True, blank=True ) payment = models.DecimalField(_('Sueldo'), max_digits=8, decimal_places=4, null=True, blank=True ) fire_reason = models.TextField(_('Razón de despido / renuncia'), blank=True, null=True, help_text=_('Detallar la razón de por qué salió el colaborador.') ) class Meta: ordering = ( 'id', 'user', 'area', 'birth_date', 'join_date', 'payment', ) verbose_name = _('Colaborador') verbose_name_plural = _('Colaboradores') def __unicode__(self): # __unicode__ on Python 2 return '%s %s' % (self.user.first_name, self.user.last_name ) //serializers.py class UserSerializer(ModelSerializer): class Meta: model = User fields = ( 'username', 'password', 'first_name', 'last_name', 'email', 'groups', 'is_active' ) class CollaboratorSerializer(ModelSerializer): user = UserSerializer(many=False) class Meta: model = Collaborator fields = ( 'id', 'user', 'photo', 'area', … -
Django - The process cannot access the file because it is being used by another process
I'm trying to run Django on my Windows 10, I'm sort of newbie on Django, I'm using Compressor Toolkit, my problem is, I can run the manage.py but the localhost says base.html, error at line 9 The process cannot access the file because it is being used by another process. <!DOCTYPE html> {% load compress %} {% load staticfiles %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, inital-scale=1"/> <title>{% block head_title %} Hydroqua Indonesia {% endblock head_title %}</title> {% compress css %} <link rel="stylesheet" type="text/x-scss" href="{% static '/css/global.scss' %}"> <link rel="stylesheet" type="text/x-scss" href="{% static '/css/style.scss' %}"> <link rel="stylesheet" href="{% static '/node_modules/bootstrap/dist/css/bootstrap.min.css' %}"> {% endcompress %} </head> <body> {% include 'navbar.html' %} {% block content %}{% endblock content %} {% compress js %} My friend could run the compressor smoothly from his Linux, I've installed every component needed but I dont know if I missed some. -
How I can drop an index if exist using django migrations.RunSQL and MySQL
I'm trying to drop an index using migrations.RunSQL but I having the issue that doesn't exist, is there a way to Drop an index only in the case of exist? Something like migrations.RunSQL("DROP INDEX IF EXISTS index_id ON table"). Django 1.8.18 MySQL 5.6 Thank you so much -
how do i include my footer.html in my base.html
can somebody help me how to include a page in base html.because i just wondering whether i have to define the url and also in view.py.because all example i have checked in stackflow non is working for me because i have tried all of them. TemplateDoesNotExist at / includes/footer.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11 Exception Type: TemplateDoesNotExist Exception Value: includes/footer.html Exception Location: /usr/lib64/python2.7/site-packages/django/template/engine.py in find_template, line 148 Python Executable: /usr/bin/python Python Version: 2.7.13 Python Path: ['/home/harrugg2/projects/django/membersite', '/usr/lib/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] Server time: Thu, 27 Apr 2017 15:50:50 +0300 this my base.html {% load staticfiles %} <html> <head> <title>member site</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <!-- Core CSS - Include with every page --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <link rel="stylesheet" href="{%static 'css/Footer.css' %}"> </head> <body> <nav class="navbar navbar-custom"> <!--div class="page-header"--> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Member site</a> </div> <form class="navbar-form navbar-left"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> {% if user.is_authenticated %} <div class="nav navbar-nav navbar-center"> <ul … -
Specifying a function in Django settings
I write a Django app which should have a setting whose value is a Python function. How to put the function into settings.py? To use a function name I would need to import the module defining the function from settings.py. Is it good idea to import something from settings.py? Any other way to specify a function? -
assign today date to filtered date django
I'm filtering on my contacts in get_queryset function like this, and displaying contacts that are created in the past, also I'm displaying their created dates. filter_date = self.request.query_params.get('filter_date', None) if filter_date is not None: queryset = queryset.filter(next_action_date__lte=filter_date) So how can I after I filter them convert past dates to today, literally convert past dates to today? -
Django channel BadStatusException on handshake?
Here is the code to my setting.py redis_host = os.environ.get('REDIS_HOST', 'localhost') CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6379)], }, "ROUTING": "djangojobs.routing.channel_routing", }, } and routing.py is defined as from channels import include def message_handler(message): print(message['text']) channel_routing = [ route("websocket.receive", message_handler) ] I am connecting to websockets using python websocket client as import websocket ws = websocket.WebSocket() ws.connect("ws://localhost:8000") Now the error message that i keep on getting is Traceback (most recent call last): File "", line 1, in File "/home/georoot/code/djangoJobs/env/lib/python3.6/site-packages/websocket/_core.py", line 214, in connect self.handshake_response = handshake(self.sock, *addrs, **options) File "/home/georoot/code/djangoJobs/env/lib/python3.6/site-packages/websocket/_handshake.py", line 65, in handshake status, resp = _get_resp_headers(sock) File "/home/georoot/code/djangoJobs/env/lib/python3.6/site-packages/websocket/_handshake.py", line 122, in _get_resp_headers raise WebSocketBadStatusException("Handshake status %d", status) websocket._exceptions.WebSocketBadStatusException: Handshake status 200 Is there some more configuration i am missing ? or where am i going wrong ? -
Django and aiohttp together
Under my Django project I have created a directory for a aiohttp service. 1) How is the best way to structure it? This is my current structure: myproject/ myservice/ __init__.py server.py myproject/ __init__.py settings.py urls.py uwsgi.py manage.py 2) If my service needs to import some settings from myproject.settings, how can I do it? Should I move server.py under the root? I get: ImportError: No module named 'myproject' -
How to customize login in django
I have a registration page for teachers having fields like email, mobile number, password etc, the table is named as Teacher. I want to login page too for the same. What I am doing is: Added following in url page: url(r'^login/$', auth_views.login, {'template_name': 'login.html'},name='login'), Added following in settings.py: AUTH_USER_MODEL = 'myapp.Teacher' Added login.html: {% extends "base.html" %} {% load widget_tweaks %} {% block body_block %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="login-panel panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Please Sign In</h3> </div> <div class="panel-body"> <form method="post" action="{% url 'login' %}"> {% csrf_token %} <p class="bs-component"> <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> </p> <p class="bs-component"> <center> <input class="btn btn-success btn-sm" type="submit" value="login" /> </center> </p> <input type="hidden" name="next" value="{{ next }}" /> </form> </div> </div> </div> </div> </div> {%endblock body_block%} Now … -
Django-Haystack add filtering to my search
I've got a search view at the moment but would like to create a form to add check box filtering to the search results. from haystack.generic_views import SearchView from haystack.query import SearchQuerySet from haystack.forms import SearchForm class NoteSearchView(SearchView): template_name = 'search.html' form_class = SearchForm def get_queryset(self): queryset = SearchQuerySet() return queryset I want to create a category filter of 'Sports', 'Fiction', & 'Non-Fiction'. Any thoughts on how to achieve this? I thought maybe I could use the ModelSearchForm but override the default values in some way. Thank you. -
How to display a foreign key value instead of the id?
I have the following models : class FlightSchedule(models.Model): tail_number = models.ForeignKey(TailNumber, null=False) flight_number = models.CharField(max_length=30, null=False) flight_group_code = models.ForeignKey(FlightGroup, null=False) origin_port_code = models.ForeignKey(Port, null=False, related_name="Origin") destination_port_code = models.ForeignKey(Port, null=False, related_name="Destination") flight_departure_time = models.TimeField() start_date = models.DateField() end_date = models.DateField() # route_id = models.CharField(max_length=30, null=True) def __unicode__(self): return u'%s' % self.flight_number class Meta: verbose_name_plural = "Flight Schedule" class FlightScheduleDetail(models.Model): flight_date = models.CharField(max_length=30, null=False) # tail_number = models.ForeignKey(FlightSchedule, null=False, related_name="tail_number_schedule") flight_number = models.ForeignKey(FlightSchedule, null=False, related_name="flight_number_schedule") route_id = models.CharField(max_length=30, null=False, unique=True) flight_status = models.ForeignKey(Status, null=True, default=1) def __unicode__(self): return u'%s' % self.route_id class Meta: verbose_name_plural = "Flight Schedule Details" and the serializer is as below : class FlightScheduleDetailSerializer(serializers.ModelSerializer): class Meta: model = FlightScheduleDetail fields = '__all__' class FlightScheduleSerializer(serializers.ModelSerializer): flight_number_schedule = FlightScheduleDetailSerializer(many=True) class Meta: model = FlightSchedule fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time', 'flight_number_schedule'] Here tail_number , flight_number is a foreign key. When I create an API, I get the response as the id of the fields. How can I display the name in the json? My views.py is as below : @api_view(['GET']) def flight_schedule(request): schedule = FlightSchedule.objects.all() serializer = FlightScheduleSerializer(schedule, many=True) return Response(serializer.data) -
How can one replicate Django admins add new row functionality?
I am looking for a way to implement the "add new model_name" functionality from Django to admin to normal form in templates. How could I achieve it? -
Django postgres islike query
The objective is to have a fast search for similar values, in order of similarity. This is the query in Django: Model.objects.annotate(similarity=TrigramSimilarity('field_name', query)).filter(similarity__gt=0.3).order_by('-similarity').values('field_name')[0:30] The above is converted to this query: SELECT "table"."field_name" FROM "table" WHERE SIMILARITY("table"."field_name", query_value) > 0.3 ORDER BY SIMILARITY("table"."field_name", query_value) DESC LIMIT 30 That takes around 1.3 seconds, but if I run this in psql: SELECT field_name FROM table WHERE field_name % 'query_value' ORDER BY similarity(field_name, 'query_value') DESC LIMIT 30 It's much faster and has the same correct output. How can I achieve this with Django, besides putting in the raw sql command? Another question is how to add SELECT DISTINCT field_name to that. Currently when trying to add it I get ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list even though I only use the selected field_name in the ORDER BY simlarity function. Thanks a lot! -
Mutually exclusive many-to-many relationship in Django models
I'm trying to create a simple model to keep track of discount coupons in Django 1.10 (with Postgres 9.5 as underlying database) and I was wondering if there's a way to make sure that a coupon instance (id, perhaps is a more accurate term?) doesn't appear in two M2M relationships at the same time. I'm sure everyone is familiar with how discount coupons work but, just in case, let me explain my use case: Some coupons would be always applied. For instance: "Free delivery in your first purchase", or "10% off Pepsi for the rest of your life"... things like that. Some other coupons would be applied through a code (a simple string, really) that the user would have to input somewhere (like "Get a 5% off with the code "5-OFF" "... yeah, I'll probably have to work on the obfuscation of the codes :-D ) The user could say "No, I don't want to apply this coupon to this order, I'll use it later". For instance: if the user can use a one-time 5% off coupon, but wants to keep it for a large purchase. Let's say the customer knows he's going to make a large purchase in the … -
No migrations after changing apps.py
Django 1.11 Trying to catch signals in frames application. For convenience I have changed the project structure. That is I have created one more level over frames application. The directory is also called frames. └── photoarchive ├── frames │ ├── frames │ │ ├── admin.py │ │ ├── apps.py │ │ ├── forms.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ ├── model_mixins.py │ │ ├── models.py │ │ ├── signals.py │ │ ├── templates │ │ │ └── frames │ │ │ ├── frame_detail.html │ │ │ ├── frame_form.html │ │ │ └── frame_list.html │ │ ├── tests.py │ │ ├── urls.py │ │ ├── view_mixins.py │ │ └── views.py init.py default_app_config = 'frames.frames.apps.FrameConfig' apps.py from django.apps import AppConfig class FrameConfig(AppConfig): name = 'frames' def ready(self): import frames.frames.signals I delete migrations from all applications (by a shell script). Then makemigrations, migrate. And no migrations for frames application appear. In other applications everything is ok. And if I comment that only line in init.py, migrations appear. But my idea with signals is ruined. Could you give me a kick here? -
Django Memory Issues
My app has been having some serious memory issues. I am running Python 3.6, Django 1.10, running memchached on Heroku. Database contains about 1,000,000 rows of data. In an attempt to get app to better perform I have change most query's related and prefetch related. None of this seemed to help so I have scaled up the Dyno's in an attempt to wrangle the memory issues but no matter how many I run I am still getting memory issues. There is really no load on the Dyno's themselves. Just straight memory issues. The memory will shoot up to 768 mb and will not release this memory till I restart the dynos or app itself. I am looking for any suggestions into improving the memory issues. I have thought of running garbage collection at some point to lower the memory but I have never actually used this in django. If anyone has experience with that will be helpful. Other than that I am pretty much mind blown where the memory leaks can be. Thanks in advance. -
Tastypie foreign key dehydrate
I have the tastypie resource: class ProjectPermissionResource(ModelResource): project = fields.ToOneField(ProjectResource, 'project', full=True, readonly=True) ... As you see, the project resource is returning full with all fields. I need to remove some fields, so I tried to use the dehydrate_project method: def dehydrate_project(self, bundle): # delete some project fields here return bundle But after adding this method I get "maximum recursion depth exceeded while calling a Python object". Stucked after this. Need to delete some fields from project (in details I need only ot id, name and so on...) -
Leave DECIMALFIELD blank if criteria is not met
I am attempting to leave a DECIMALFIELD blank. I would like my "if statement" to leave the field blank if it doesn't meet the criteria. My model is already set to blank=True, null=True. def clean_xrate(self): xrate_date = self.cleaned_data.get(str("date")) currency = self.cleaned_data.get("currency") curr = currency if not xrate_date: raise ValidationError('Error') elif curr == 'USD': xrate = 'NULL' <---This doesn't work. ☹️ else: prior_date_rate = cr.get_rate(curr, 'USD', xrate_date) xrate = "{0:.4f}".format(prior_date_rate) return xrate Thanks in advance for your help! -
ValueError at /createuser/ invalid literal for int() with base 10: 'satya'
i am trying to create user . first i am checking if user exists or not but for first time it gives me this error: ValueError at /createuser/ invalid literal for int() with base 10: 'satya' and when i refresh this page works fine. my code: for i in range(0, len(username)): try: print(username[i]) user = User.objects.get(username = username[i]) except User.DoesNotExist: user = User.objects.create_user(username=username[i], email=email[i], password=password[i],first_name=firstname[i],last_name=lastname[i] ) group.user_set.add(username[i]) except ValueError: pass thanks in advance!!