Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, how to know the exact type of child's class (if possible)
this is my models.py class UserWidget(models.Model): user = models.ForeignKey(User, related_name="widgets") widget = models.ForeignKey(Widget) options = JSONField(default="{}") category = models.ManyToManyField(WidgetUserCategory) class UserWidgetAtomic(UserWidget): atomic = models.ForeignKey(Atomic) class UserWidgetNonAtomic(UserWidget): nonatomic = models.ForeignKey(NonAtomic) On my views.py I do this: widgets = category.userwidget_set.all() or this (it doesn't matter) widgets = user.widgets.all() I would like to know (if possible) while iterating the type of the subclassed object. for example for item in widgets: if item.__class__.__name__ == "UserWidgetAtomic": do this elif item.__class__.__name__ == "UserWidgetNonAtomic": do that Is this possible? How? -
Parse output from Django timesince to float days with javascript
I have the output of the tag filter timesince such as 9 minutes How can I parse it to days in javascript, so it can return me an float in days, for example 0.00x days -
Tinify: connection error (cafile must be None or a byte string)
I am getting the following while using the tinify API for compressing the image: error while uploading image Traceback (most recent call last): --- File "/srv/webapps/xxxxxx.com/xxxxxx/temp/adminviews.py", line 1539, in do_admin_add_file --- new_image=True) --- File "/srv/webapps/xxxxxx.com/xxxxxx/temp/models.py", line 283, in create --- obj.save(force_insert=True, using=self.db, new_image=new_image, resize=resize) --- File "/srv/webapps/xxxxxx.com/xxxxxx/temp/models.py", line 316, in save --- ic.compress(self.image_name,metadata='bannertype :'+self.banner_type) --- File "/srv/webapps/xxxxxx.com/xxxxxx/temp/adminviews.py", line 2069, in compress --- compressed = tinify.from_file(image) --- File "/srv/webapps/xxxxxx.com/virtualenvs/xxxxxx/local/lib/python2.7/site-packages/tinify/init.py", line 65, in from_file --- return Source.from_file(path) --- File "/srv/webapps/xxxxxx.com/virtualenvs/xxxxxx/local/lib/python2.7/site-packages/tinify/source.py", line 11, in from_file --- return cls._shrink(path) --- File "/srv/webapps/xxxxxx.com/virtualenvs/xxxxxx/local/lib/python2.7/site-packages/tinify/source.py", line 26, in _shrink --- response = tinify.get_client().request('POST', '/shrink', obj) --- File "/srv/webapps/xxxxxx.com/virtualenvs/xxxxxx/local/lib/python2.7/site-packages/tinify/client.py", line 52, in request --- raise ConnectionError('Error while connecting: {0}'.format(err), cause=err) --- ConnectionError: Error while connecting: cafile must be None or a byte string I had pyOpenSSL version 0.14 installed. After updating pyOpenSSL to version 0.15, it worked perfectly. What could be the reason for that ? -
Django form submission - unexpected behaviour
I have a form on one of my Django webpages, which currently displays information about Budgets for a particular Project. Budget & Project are both models within the database. Each Project can have multiple Budgets, but only one of those Budgets will be the 'current Budget'. The way the information is displayed, is that there are a number of 'tile' icons called 'Presentations', (one for each Budget). When one of the 'Presentation' tiles is selected, a form is displayed below the tiles, for the user to fill in information about that presentation (notes, who is attending, date, etc). The last 'tile' icon in the list will always be a blank tile, titled "Add presentation", which the user can click to add a new presentation for the project- and it will display a blank copy of the form beneath the existing tiles. The form includes two fields for uploading images (the images will be associated with that particular Project through the Budget object that they are uploaded to. Once the form has been filled out, and the image files added to the form, the user should click the 'Submit' button at the bottom of the form to upload this all to … -
Validate formset according master's form field value
I have a admin master detail, using tabular inline forms. I have some special validations to accomplish: If "field_type" is "list", validate that at least one item in the formset has been added. But if not (field_type has another value), do not validate. If "field_type" is "list", then, make visible the formset, otherwise hide it. This is javascript. I also must validate that on the server. I do that on the clean() of ValueItemInlineFormSet. The problem is that is now validating formset always and it should just happen when field_type = "list". How can I get the value of my master field into the formset? class ValueItemInlineFormSet(BaseInlineFormSet): def clean(self): """Check that at least one service has been entered.""" super(ValueItemInlineFormSet, self).clean() if any(self.errors): return print(self.cleaned_data) if not any(cleaned_data and not cleaned_data.get('DELETE', False) for cleaned_data in self.cleaned_data): raise forms.ValidationError('At least one item required.') class ValueItemInline(admin.TabularInline): model = ValueItem formset = ValueItemInlineFormSet class MySelect(forms.Select): def render_option(self, selected_choices, option_value, option_label): if option_value is None: option_value = '' option_value = force_text(option_value) data_attrs = self.attrs['data_attrs'] option_attrs = '' if data_attrs and option_value: obj = self.choices.queryset.get(id=option_value) for attr in data_attrs: attr_value = getattr(obj, attr) option_attrs += 'data-{}={} '.format(attr, attr_value) if option_value in selected_choices: selected_html = mark_safe(' selected="selected"') … -
Subcategories Django Shop
I have 2 categories Man and Woman and I want to create subcategories and connect it in product This is my models.py class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateField(auto_now_add=True) update = models.DateField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name I think I can create this class class Subcategory name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) category = models.ForeignKey(Category) and add it to Product class subcategory = models.ForeignKey(Subcategory) but i don't think is a good way -
How do I fix Boostrap from breaking grid?
What I have: -I am using Django to populate my Makes on a view. Here is my template: <div class="container"> <div class="row"> <div class="btn-group" id="makesTable"> {% if makes %} {% for make in makes %} <button type="button" name="button" class="btn btn-default" id="{{ make.id }}"> <br /> <img class="center-block" src="[REDACTED]" /> <br /> <p>{{ make.name }}</p> </button> {% endfor %} {% endif %} </div> </div> </div> I am currently having an issue with responsive design. I would like for the buttons to be arranged in a 5x7 grid, however, sometimes, I get the following issue: This is how I want it to look This is how it breaks -
Mezzanine - Django Page - RichText
I have a class like below class sitepage(Page, RichText): featuredimage = FileField(_('File'), blank=True, max_length=200, upload_to='featured', format='Image') featuredimagetitle = models.CharField(_('Featured Image Title'), blank=True, max_length=200) featuredimagebgchoices = ( ('R', 'Red'), ('B', 'Blue'), ('G', 'Green'), ('O', 'Orange'), ) featuredimagebg = models.CharField(_('Featured Image Background'), max_length=1, default='R', choices=featuredimagebgchoices) featuredimagebrief = models.TextField(_('Description - Featured Image'), blank=True, max_length=1000) However I am unable to render content it on template file sitepage.html with this {{ page.sitepage.content|richtext_filters|safe }} What am I doing wrong ? -
UpdateView with additional fields in Django
I'm building an app where users can submit a ThesisLink, which contains metadata of their MSc or PhD thesis. Before a thesis link is published, a vetting editor must have the possibility to change fields (for example, in the case of a broken link) or outright reject the thesis link. Submitters should be mailed when their thesis link is accepted, accepted with certain changes, or rejected. I came to the conclusion that I want some sort of UpdateView, where all the fields of the model are already filled out, and ready to be edited by a vetting editor. But I also want fields that are not on the model, like refusal_reason, or editor_comment. And I want to notify users by mail when a change happens. How to extend the update view to do this? Or should I abandon the UpdateView altogether and build something on top of FormView? This is what I have so far: # urls.py urlpatterns = [ url(r'^vet_thesislink/(?P<pk>[0-9]+)/$', views.VetThesisLink.as_view(), name='vet_thesislink') ] # views.py @method_decorator(permission_required( 'scipost.can_vet_thesislink_requests', raise_exception=True), name='dispatch') class VetThesisLink(UpdateView): model = ThesisLink fields = ['type', 'discipline', 'domain', 'subject_area', 'title', 'author', 'supervisor', 'institution', 'defense_date', 'pub_link', 'abstract'] template_name = "theses/vet_thesislink.html" And in the template: # templates/theses/vet_thesislink.html <form action="" method="post">{% … -
Upload image file via ajax whit django
I am trying to upload an image file to my server. I am sending it via AJAX, and via POST. But when I submit, my form is not valid and gives me the following validation error: <Ul class = "errorlist"> <li> photo <ul class = "errorlist"> <li> This field is mandatory </ li> </ li> but im selecting a image file. template <div class="row"> <div class="col-md-12"> <fieldset> <legend>Agregar Foto</legend> <form id="save-form" action="{% url 'cargar_fotos' id %}" method="POST" runat="server" enctype="multipart/form-data">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="row"> <div class="col-md-12"> <label for="">Tipo Foto</label> </div> </div> <div class="row"> <div class="col-md-12"> {{form.tipo_foto}} </div> </div> <div class="row"> <div class="col-md-12"> {{form.foto}} </div> </div> </div> <div class="col-md-6 well"> <img id="foto-preview" src="#" alt="" style="display:none"/> </div> </div> <div class="row"> <div class="col-md-12"> <button type="submit" class="btn btn-large btn-success pull-right" id="save"> <i class="glyphicon glyphicon-save"></i> Guardar <img src="/static/imagenes/preventivos/loading.gif" style="display:none" id="loading" /></button> </div> </div> </form> </fieldset> </div> </div> AJAX $("#save-form").submit(function(event){ event.preventDefault(); $("#save").prop('disabled',true); $("#loading").show(); var form = $("#save-form"); var data = form.get(0); $.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serialize(), /*data, cache:false, processData: false, contentType: false,*/ success: function(data){ $("#save").prop('disabled', false); $("#loading").hide(); $("#dialog").empty().html(data); }, error: function(jqXHR, textStatus,msg){ $("#btnSearch").prop('disabled', false); $("#loading").hide(); $( "#dialog-confirm" ).dialog({ closeOnEscape: false, open: function(event, ui) { $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); }, resizable: false, … -
GDAL error when trying to enable PostGIS on PostgreSQL on Ubuntu 16.04
In order to enable geographical data on my Django project, I am trying to enable the GeoDjango extensions on my Ubuntu 16.04 box. PostGIS and GDAL are required obviously and do not seem to play well together. From the psql shell, when running the following command: CREATE EXTENSION postgis; I get this error: ERROR: could not load library "/usr/lib/postgresql/9.5/lib/rtpostgis-2.2.so": /usr/lib/libgdal.so.1: undefined symbol: sqlite3_column_table_name This error seems familiar among Django and Python users, and solutions evocate fixing the virtualenv. But this case is purely from the database, there is no Python involved. sqlite3 version conflicts seems a common pitfall too, even if I am not able to trace such issue in this case. Also, I have checked if the library file has the symbols, and it seeps that it is the case: nm -D /usr/lib/libgdal.so.1 | grep sqlite3_column U sqlite3_column_blob U sqlite3_column_bytes U sqlite3_column_count U sqlite3_column_decltype U sqlite3_column_double U sqlite3_column_int U sqlite3_column_int64 U sqlite3_column_name U sqlite3_column_table_name U sqlite3_column_text U sqlite3_column_type The sqlite3_column_table_name symbol is found in the library and the error message says the opposite. How can I fix my environment to get PostGIS running? -
Token based authentication with Dajngo rest_framework
hi guys i'm new to django rest_framework api's, now i'm practising through the django rest_framework documentation and struck at authentication, especially token based authentication.i'm able to create token for user witch already created. now the thing is how to give permissions to users add, delete, update the information by providing the token i have done some stuff, that is.. thank U in advance models.py class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) highlighted = models.TextField(default = '') class Meta: ordering = ('created',) views.py from snippets.models import Snippet from snippets.serializers import SnippetSerializer,UserSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.contrib.auth.models import User from rest_framework import generics from rest_framework import permissions from snippets.permissions import IsOwnerOrReadOnly class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def perform_create(self, serializer): serializer.save(owner=self.request.user) permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,) class SnippetDetail(APIView): """ Retrieve, update or … -
Alias for app URI in Django project urls.py
My Django project "animals" has an app called "birds". In animals/urls.py the "birds" URIs are routed to birds/urls.py like this: urlpatterns=[ url(r'^birds/', include('birds.urls')), url(r'^b/', include('birds.urls')), # alias ] The "birds/" is the official, permanent base URI; "b/" is accepted as a shortcut/alias. How can I have the "b/" URIs (permanently) redirected to "birds/", such that even though users can enter "b/penguin", the address bar of the browser will (ultimately) show "birds/penguin"? I prefer not to touch any code in the "birds" app, because it should not know (care) how the project maps URIs to the app. I have tried to use RedirectView.as_view(pattern_name='birds')) but this results in a 410 Gone response. And RedirectView.as_view(url='/birds/')) redirects /b/penguin to /birds/, killing my bird. -
Tox automatically installing unwanted package
I am trying to get the coverage of my tests using TOX and Travis CI. Unfortunately when creating the virtual envs, TOX install my package from PIP, thus not testing the coverage of the actual source code... How can I prevnt that to happen. I guess the easiest way to explain is to try: Clone this: https://github.com/millerf/django-channels-jsonrpc Create a venv $>virtualenv venv/ And finally: $> pip install tox $> tox -ecoverage The coverage does not include channels_jsonrpc/, as tox installed the package in his own venv... how can I prevent the install of one package with tox? -
Django - Passing variables from a function to another
I need some of your help please, I'm working with pysftp this is working great but now I'm trying to make it work to my project in Django worked great in console but I want to get the data from a form so I won't need to use the console to do that. here's my view: def sftp_form(request): if request.method == 'POST': form = sftpForm(request.POST or None) if form.is_valid(): data = form.cleaned_data host = data['host'] usuario = data['usuario'] clave = data['clave'] print host print usuario print clave else: form=sftpForm() return render(request, 'sftp.html', {'form':form}) def SFTP_subir(): host = raw_input('ingrese el host: ') # I want form's host here. usuario = raw_input('ingrese el usuario: ')# I want form's usuario here. clave = raw_input('ingrese la clave: ')# I want form's clave here. try: transferencia = sftp.Connection(host=host, username=usuario, password=clave) remotepath= 'remotepath' localpath="mylocalpath" transferencia.put(localpath,remotepath) print ('\n' + 'Sucess.') except Exception, e: print str(e) as you can see in my code sftp_subir() it's asking me for host,usuario and clave from console, but I want to make it work with sftp_form() host,usuario and clave. -
How to implement dictionary-like field in Django model?
The problem: a group of several people can use instruments of different types, but the instruments of the same type are not distinguishable. For instance, a group could use 3 hammers and 4 axes, but we don't need to distinguish individual axes or hammers. How to design a Django model in this case? My thoughts: class Person(models.Model): name = models.CharField() class Group(models.Model): title = models.CharField() members = models.ForeignKey(Person) equip = ??? I've found this question on StackExchange and a code snippet for a Django Dictionary model, but I am still not sure what approach to choose. Also, do I really need a dictionary here? -
How to create a two field search system in Python django
Hi I want to create a two field search system in Python django. That operates like this, one field for organisation name and another field for location, that has drop down for location, then the user clicked search and the results brings back organisations with the name and filter it based on the location and give me an accurate result for it.... Thank you -
Django Python Processing 2 Models in 1 form
I want to extend the User model in Django by a couple new fields. After that, I need to create 1 form where you can register your username + password from the User model and also the fields from my custom model. This is my model for the custom User fields: class Gebruiker(models.Model): id = models.OneToOneField(User, primary_key=True) voornaam = models.CharField(max_length=100) achternaam = models.CharField(max_length=100) email = models.CharField(max_length=300) gb_datum = models.DateField() plaats = models.CharField(max_length=52) postcode = models.CharField(max_length=6) huisnummer = models.IntegerField() nfid = models.IntegerField() hn_toevoeging = models.CharField(max_length=3, blank=True) def __str__(self): return self.voornaam + self.achternaam And this is my view for the form. In this form I also want to add the fields for the Gebruiker model while keeping the rest of the form. How can I do this? class UserFormView(View): form_class = UserForm template_name = 'home/registration_form.html' # display blank form def get(self, request): form = self.form_class(None) # form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned/normalized data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns User objects if credentials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('home:index') return … -
can't authenticate user in postgres docker container
containerizing a django app built with the pydanny cookiecutter for deployment to an EC2 instance. the docker_compose.yml is pretty straigtforward: version: '2' volumes: postgres_data: {} postgres_backup: {} services: postgres: build: ./compose/postgres volumes: - postgres_data:/var/lib/postgresql/data - postgres_backup:/backups env_file: .env .... nothing exotic in the dockefile; just pointers to backup and restore scripts and commands to make them executable: FROM postgres:9.4 # add backup scripts ADD backup.sh /usr/local/bin/backup ADD restore.sh /usr/local/bin/restore ADD list-backups.sh /usr/local/bin/list-backups # make them executable RUN chmod +x /usr/local/bin/restore RUN chmod +x /usr/local/bin/list-backups RUN chmod +x /usr/local/bin/backup I've tried several variations on my db env variables, the latest of which looks like: # PostgreSQL POSTGRES_PASSWORD='postgrespass' POSTGRES_USER='postgres' the container builds and initializes without problem on: docker-compose build postgres docker-compose up -d but when I try to make and migrate initial data to the db with: docker-compose run django /usr/local/bin/python manage.py makemigrations the db is unresponsive – "Postgres is unavailable - sleeping" and docker logs db returns: DETAIL: Connection matched pg_hba.conf line 95: "host all all all md5" FATAL: password authentication failed for user "'postgres'" obviously I have some permission issues, but I'm not quite sure how to address them. My containers are running on an Ubuntu 16.04 AMI. -
"list_editable" and "list_filter" don't work in admin objects list using custom get_queryset() method
I use custom abstract model with manager throughout my project. class BaseQueryset(models.QuerySet): pass class BaseManager(models.Manager): queryset_class = BaseQueryset def get_queryset(self, exclude_no_published=True): """ exclude all objects with is_published=False by default """ q = self.queryset_class(self.model) if exclude_no_published: q = q.exclude(is_published=False) return q def all_objects(self): """ allows geting all objects in admin """ return self.get_queryset(exclude_no_published=False) class BaseAbstractModel(models.Model): is_published = models.BooleanField(default=True) objects = BaseManager() class Meta: abstract = True All models inherit from this abstract model and I need a way to represent all objects in admin. So I wrote my own mixin for admin classes with get_queryset method class AdminFullQuerysetMixin(object): def get_queryset(self, request): """" Allows showing all objects despite on is_public=False """ qs = self.model.objects.all_objects() ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs All works fine, I can see all objects in admin whether with is_published False or True. But such attributes like list_filter or list_editable don't work, when I use it in admin objects list page. There is no exception provided, just text at the top of the list: "Please fix ann errors below". What methods except get_queryset should I override for solving my problem? -
Select field in form based on queryset in the same model
I want a drop-down populated with the results of a queryset in my form for my coach_id field. I only want the user to be able to select one option, not multiple. I'm trying to use a ModelMultipleChoiceField... unsuccessfully..... class PersonForm(forms.ModelForm): coach_id = forms.ModelMultipleChoiceField(queryset=Person.objects.filter(assign_as_coach="Person is a coach"), widget=forms.Select()) class Meta: model = Person fields = [ 'id', 'first_name', 'surname', 'email', 'coach_id', 'assign_as_coach', 'position', 'contract_type'] # exclude = ['initials', 'sam'] labels = { 'first_name': _('First Name'), 'surname': _('Surname'), 'email': _('Email'), 'coach_id': _('Select Coach'), 'assign_as_coach': _('Assign as a coach?'), 'position': _('Position'), 'contract_type': _('Contract Type'), } widgets = { 'first_name': forms.TextInput( attrs={'placeholder': 'First Name', 'id': 'person-first-name'} ), 'surname': forms.TextInput( attrs={'placeholder': 'Surname', 'id': 'person-surname'} ), 'email': forms.TextInput( attrs={'placeholder': 'Email Address', 'id': 'person-email'} ), # 'coach_id': forms.Select( # attrs={'placeholder': 'Select Coach', 'id': 'person-coach-id'} # ), 'assign_as_coach': forms.Select( attrs={'placeholder': 'Assign person as a coach?', 'id': 'person-is-coach'} ), 'position': forms.TextInput( attrs={'placeholder': 'Current position', 'id': 'person-position'} ), 'contract_type': forms.Select( attrs={'placeholder': 'Select Contract Type', 'id': 'person-contract'} ), Here is my model: class Person(models.Model): FT = "Full-Time" PT = "Part-Time" C = "Contract" Z = "Zero hours" CONTRACT_CHOICES = ( (FT, "Full-Time"), (PT, "Part-Time"), (C, "Contract"), (Z, "Zero hours"), ) Y = "Yes" N = "No" IS_COACH_CHOICES = ( (Y, … -
Django template cannot access JSON Key in duplicate quotations: {" 'Key' ": " Value "}
My Django app is interacting with an API and displaying results in the templates. The API result has some normal Key Value pairs and some custom fields which have a Key in double and single quotations. The key is formatted as " 'custom_field_123' " in the result JSON: {'cost_price': '0.00', "'asset_field_1234'": None, "'asset_field_5768'": None} I know this isn't correct JSON format but it's what I have to deal with. In the Django templates I can use: <p>{{tower.name}}</p> for regular format keys. But the template language will not recognize: <p>{{tower.'custom_field_123'}}</p> Or <p>{{tower.('custom_field_123')}}</p> Is there a way to access these values or will I have to rename the keys in quotations to access them in the template. -
Filling in .po files for translation of phrases with variable content
I wasn't able to find in the doc, but I have no idea how to translate phrases that contain variable content. I have the following phrase in my Django view: apple_count = 100 a = _('I have %d apples' % apple_count) After running makemessages, I have the following content in .po file: msgid "I have %d apples" msgstr "" I have tried several combinations, like this one: msgid "I have %d apples" msgstr "У меня есть %d яблок" and this one: msgid "I have apples" msgstr "У меня есть яблок" And yet no success. What I am doing wrong ? -
Django url unique url open
I use django 1.10.5. I have a problem with open unique url, views: entry = get_object_or_404(Post, slug=slug) model field: slug = models.SlugField(editable=False) i need to detect slug with identical string, for example i have slug xyz and xYz i need to open other pages, now django display 500 page on production. url(r'^(?P<slug>[\w-]+)/$', views.single_post, name='single_post'), how i can detect if is identical? -
Mock model to use a different database in django
In my settings I defined 2 databases: DATABASES = { "default": default_db, "test": test_db } In my app code, I have the following: def my_method() records = do_something() MyModel.objects.filter( start=truncate_minutes(utc_now()), country=country ).delete() MyModel.objects.bulk_create(records) do_something() I want to mock the MyModel.objects, than in my test it will be using a different database like this: MyModel.objects.using("test").bulk_create(records) or MyModel.objects.using("test").filter( start=truncate_minutes(utc_now()), country=country ).delete() How can I do it from my test method without changing the existing code? @mock("MyModel) def test_my_method(self, mock_my_model): ...