Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RuntimeError: Model class nose.util.C doesn't declare an explicit app_label
What is causing this error in my django app only when I run unit tests? Why does it think nose.util.C is a model? RuntimeError: Model class nose.util.C doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. -
jqgrid use in Django template: Reverse for 'item-jqgrid-entity1'
Trying to revive a Django app that was working 2014-2015 then was turned off for almost 3 years and now is not willing to cooperate. Mac OS X el Capitan 10.11.6 Python 3.6 (also tried 3.4) Django 1.8.3 In short, how does notation (in template) {% url 'item-jqgrid-entity1' pk=original.id %} connects to django models Item and Entity1 WITHOUT having item-jqgrid-entity1 listed in url.py ? I am getting Reverse for 'item-jqgrid-entity1' with arguments '()' and keyword arguments '{'pk': 123}' not found. 0 pattern(s) tried: [] and it used to work somehow. If I introduce matching URL in urls.py, it works, but I want to know how it was working without it. For a given model (Item) the default template change_form.html was overriden. The custom one goes like this: {% extends "admin/change_form.html" %} {% load admin_urls %} . . var searchable_columns = { alteration_type: { searchoptions: { dataUrl: '{% url 'item-jqgrid-entity1' pk=original.id %}' } }, disease: { searchoptions: { dataUrl: '{% url 'item-jqgrid-entity2' pk=original.id %}' } }, } . . -
Accessing a hyperlinkedRelatedField object from a permission class
I am trying to make an api backend of something like reddit. I want to ensure that whoever is creating a post (model Post) within a particular subreddit is a member of that subreddit (subreddit model is Sub). Here is my latest effort, which works but seems pretty sloppy, and the serializer for some context. Post permissions.py class IsMemberOfSubOrReadOnly(BasePermission): def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return True elif request.data: # prevent creation unless user is member of the sub post_sub_pk = get_pk_from_link(request.data['sub']) user = request.user user_sub_pks = [sub.pk for sub in user.subs.all()] if not (post_sub_pk in user_sub_pks): return False return True Post serializers.py from .models import Post from redditors.models import User from subs.models import Sub class PostSerializer(serializers.HyperlinkedModelSerializer): poster = serializers.HyperlinkedRelatedField( view_name='user-detail', #queryset=User.objects.all(), read_only=True ) sub = serializers.HyperlinkedRelatedField( view_name='sub-detail', queryset=Sub.objects.all() ) class Meta: model = Post fields = ('url', 'id', 'created', 'updated', 'title', 'body', 'upvotes', 'sub', 'poster') The issue with this approach is that since 'sub' is a hyperlinkedRelatedField on the Post serializer what I get back from request.data['sub'] is just the string hyperlink url. I then have a function, get_pk_from_link that uses regex to read the pk off the end of the url. Then I can use that … -
obtain logs for django channel workers using upstart
Environment: OS: Linux 4.14.70-67.55.amzn1.x86_64 x86_64 x86_64 x86_64 GNU/Linux So I setup daphne and a worker process as described in this article. My upstart script looks the same as described in that article. Adding it here for quick look: start on runlevel [2345] stop on runlevel [016] respawn script cd /home/ubuntu/<app home> export DJANGO_SETTINGS_MODULE="<app>.production_settings" exec daphne -b 0.0.0.0 -p 8001 <app>.asgi:channel_layer end script Now there are couple of things I couldn't find out. How to run multiple workers using upstart (like supervisor by specifying numprocs as shown here) How to specify the log path for each worker in upstart Thanks. -
How to pass the context to a Django template with include?
I have started building a django project from the tutorial at https://docs.djangoproject.com/en/2.1/intro/tutorial01/ After finishing the base tutorial which creates a project with one app called "polls" I wanted to build a sort of home page that can hold many apps together. For this reason I built an app called "news" and now I'm looking at ways to compose the two apps together. So far I'm doing so in the main 'news' template, which is called 'news/base.html' and I'm including the different apps in the code. This is my 'news/base.html' file: {% include 'news/index.html' %} {% include polls_template %} {% include 'news/footer.html' %} The two templates 'news/index.html' and 'news/footer.html' are just html pages with no arguments, just for testing and they work fine. The polls_template variable instead is a template variable that I create in the news.views.base function and pass to the template in the context. This is the view snippet that does this: def base(request): t = loader.get_template('polls/index.html') return render(request, 'news/base.html', {'polls_template': t}) The template is showing just fine but it shows an empty poll since there is no argument. Now my problem is that I cannot find a way to pass a context variable to this template object in … -
Incorrect path to save the file in Django
I am now getting the file from my front-end and I set my model like this. model.py class User(models.Model): name = models.CharField(max_length=50) image= models.FileField(upload_to='image', default=None) view.py class UserViewSet(viewsets.ModelViewSet): serializer_class = LsRequestSerializer queryset = User.objects.all() http_method_names = ['post'] serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User field = '__All__' def create(self, validated_data): newUser = User.objects.create( name = validated_data['name'] image = validated_date['image'] ) return newUser However, when I did the HTTP.POST in Postman, it gave the wrong path to save the image. "http://localhost:8000/media/Koala.jpg" But based on my design in the model with path_to, it should give: "http://localhost:8000/media/image/Koala.jpg" What's wrong with my code? -
django list of a form
I am trying to create a page to enable viewing and modification of certain user details, without granting full admin access. My idea is to list elements from the UserChangeForm, already populated with each users details. e.g. First Name: |user_1's first name| Last name: |user_1's last name| Active |√| First Name: |user_2's first name| Last name: |user_2's last name| Active | | First Name: |user_3's first name| Last name: |user_3's last name| Active |√| etc Allowing to view, change and submit directly from that page. The view I've written pulls in the information correctly from the database. The web page creates the list, but each entry in the list is of the same users data. I see why that is the case, but I'm now going in circles trying to think how to get it to display correctly. View:- def profiles(request): """Show all users details""" users = User.objects.all().order_by('last_name') print(str(users)) for user in users: if user.is_superuser == False: print("\n" + user.first_name + ' ' + user.last_name + ' ' + user.username + ' ' + user.email) if request.method != 'POST': form = UserChangeForm(instance=user) else: form = UserChangeForm(instance=user, data=request.POST) if form.is_valid(): form.save() context = {'users': users, 'form': form} return render(request, 'users/profiles.html', context) … -
Why doesnt it save the changes to fields
I'm trying to change the field values of my objects in my database. I'm using the following commands I dont know why it isn't saving the changes from false to true. Please help. is_approved and is_superuser are attributs of User u. Thanks -
Django- how to find what is the validation error?
i have a custom user model. I have written a custom ModelAdmin for that. the following is ModelAdmin: class UserAdmin(BaseUserAdmin): form = UserAdminChangeForm # add_form = UserAdminCreationForm list_display = ['complete_name', 'phone_number', 'admin', 'staff'] list_filter = ['admin', 'staff', 'is_active'] fieldsets = ( (None, {'fields': ('phone_number', 'password')}), ('Personals', {'fields': ('complete_name', 'email', 'expertise', 'image_profile')}), ('Permissions', {'fields': ('admin', 'staff', 'is_active',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ( 'phone_number', 'complete_name', 'admin', 'staff', 'is_active', 'password', 'password2' ), }), ) the problem is, when I try to create a user from admin panel. the panel displays this error: Please correct the error below. and the first field is highlighted. but it doesn't show any error messages that i've created. how to find what is the validation error? -
Django DRF permissions on create related objects
I struggle to enforce security on objects creation on Django REST framework. Basically, I can enforce security at the object level with 'has_object_permission' : the logged in user must be the owner of the object to manipulate it. Actually, as stated in the doc, I narrow objects retrieval in the queryset so, i got 404 instead of 403. That I think is not a problem (even better, as it hides the objects existences) But I do not succeed at disallowing another user to create a related object.... I use ModelSerializer and ModelViewSet. here are some naive snippets : models.py : class Daddy(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Kiddy(models.Model): title = models.CharField(max_length=12) daddy = models.foreignKey(Daddy, on_delete=models.CASCADE) serializers.py : class KiddySerializer(serializers.ModelSerializer): class Meta: model = Kiddy fields = '__all__' viewsets.py : class KiddyViewSet(viewsets.ModelViewSet): serializer_class = KiddySerializer queryset = User.objects.none() permission_classes = (IsAuthenticated, IsOwner, ) def get_queryset(self): dad_uuid = self.kwargs['dad'] return Kiddy.objects.filter(daddy__pk=dad_uuid).filter(daddy__owner=self.request.user) router.py : router = routers.DefaultRouter() router.register(r'dad', KiddyViewSet, base_name='kid') urls.py : path('api/<uuid:cv>/', include(router.urls)) Objects are accessed with those urls : http://..../api/4ecddcdd-1c0a-4d0b-8254-b0c0d2607e6d/ ---> list all kids http://..../api/4ecddcdd-1c0a-4d0b-8254-b0c0d2607e6d/1 ---> object kid permissions.py : class IsOwner(permissions.BasePermission): """ Object-level permission to only allow owners of an object to … -
How to pass variables to SCSS from a Django View
I have a simple problem, but cannot find the literature to find a solution for. I would like to let the user choose night mode, day mode, vibrant mode, etc. on my Django website. For that to work, I need to pass that variable to my SCSS file. How do I go about that? How can I pass a variable from the Django view to a SCSS file? I have looked at this answer, but this does not show it by an example and is not about SCSS files. I'd appreciate if you could provide a short example with your answer as well as the relevant documentation page. -
geodjango return geojson from POST request form
Currently I have a django FORM on my mapping application where the user enters an sss, block, lot and it returns the acreage of a water for that parcel. models.py class Post(models.Model): ssn = models.CharField(max_length=50) block = models.CharField(max_length=50) lot = models.CharField(max_length=50) views.py class HomePageView(TemplateView): template_name = 'index.html' text="" def get(self, request): form = HomeForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): form.save() cur = conn.cursor() qry = '''select round((sum(st_area(st_intersection(st_transform(a.geom,3424),st_transform(b.geom,3424))))/43560)::numeric,2) open_water_acres, ST_asGeoJson(st_union(st_intersection(a.geom,b.geom))) geojson, hl_parce_1 ssn, hl_parce_2 block, hl_parce_3 lot from reporter_parcels a join reporter_open_waters b on st_intersects(a.geom, b.geom) where hl_parce_1 = '{}' and hl_parce_2 = '{}' and hl_parce_3 = '{}' group by hl_parce_1, hl_parce_2, hl_parce_3 '''.format(str(form.cleaned_data['ssn']),str(form.cleaned_data['block']),str(form.cleaned_data['lot'])) cur.execute(qry) row=cur.fetchone() #print (row) self.text = row[0] args = {'form': form, 'text': self.text} return render(request, self.template_name, args) Part of the HTML <form method="post"> {% csrf_token %} {{ form.ssn }} {{ form.block }} {{ form.lot }} <br> <button type="submit">Submit</button> </form> Now this works perfectly good and returns the correct results. What I want to be able to return a serialized geojson of that SQL query (and will use leaflet ajax to add in JS -- I will be able to figure out this part) So my question is do I … -
'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I keep getting this error: NoReverseMatch at /accounts/password_reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name The following is my code so far: from django.conf.urls import url from . import views from django.urls import include from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ url(r'^login/$', views.login_view, name='login_view'), url(r'^register_view/$', views.register_view, name='register_view'), url(r'^logout/$', views.logout_view, name="logout_view"), url(r'^profile_view/$', views.profile_view, name="profile_view"), url(r'password_change/$',auth_views.PasswordChangeView.as_view(template_name='password_change.html',success_url='/accounts/password_change_done')), url(r'password_change_done/',auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html')), url(r'password_reset/$',auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html',email_template_name='registration/password_reset_email.html',subject_template_name='registration/password_reset_email.txt',success_url='/accounts/password_reset_done/',from_email='mpho.maleka3@gmail.com')), url(r'password_reset_done/',auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html')), url(r'password_reset_confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html',success_url='/accounts/password_reset_confirm/'), name='password_reset_confirm'), url(r'password_reset_complete/',auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html')), ] -
Cannot resolve keyword 'created' into field. Choices are: date, id, post, user, user_id?
Hi I am trying to add a field into my model called 'created' however I get the following error, I have made the migrations: Cannot resolve keyword 'created' into field. Choices are: date, id, post, user, user_id Traceback: FieldError at /home/ Cannot resolve keyword 'created' into field. Choices are: date, id, post, user, user_id Error during template rendering In template C:\Users\josep\beginnerProjects\tutorial\accounts\templates\base.html, error at line 0 cmd/terminal: "Choices are: %s" % (name, ", ".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword 'created' into field. Choices are: date, id, post, user, user_id models.py: class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views.py: class HomeView(TemplateView): template_name = ('home/home.html') def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('created') args = {'form': form, 'posts': posts} return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) -
Render django form multiplechoice
I have been searching online for how to apply colors/themes to checkbox forms items in django but could not find how to do it. What I'd like to do is probably easy as pie, but despite all the topics and blogs I red, I still cannot manage to do it. So here is my forms simplified: class MyForm(forms.Form): def __init__(self, data, *args, **kwargs): super(MyForm, self).__init__(data, *args, **kwargs) self.fields['checkbox'] = forms.MultipleChoiceField( label='Set of questions to know you better', required=True, widget=forms.CheckboxSelectMultiple(attrs={'disabled': 'disabled', 'class': 'form-control'}), choices=((1, 'Proposition 1'), (2, 'Proposition 2'), (3, 'Proposition 3'), (4, 'Proposition 4')), initial=[True, True, False, True] ) And I would like to know how I should modifiy my html which currently looks like {% csrf_token %} {{ form.as_p }} so that all choices with an initial set to True have a given css applied to them and the ones set to False another one. Hope my question makes sense. Please don't hesitate if not. Best: Eric -
Add to a manytomany field from views.py
So i have an object class that has a link class with a manytomany field. How can i update the manytomany field. models.py class Device(models.Model): char_length = 255 ## Device main characteristics id = models.AutoField(primary_key=True) # Description field description = models.CharField(max_length=char_length, blank=True) # Node number node = models.CharField(max_length=char_length, blank=True) # Device hostname hostname = models.CharField(max_length=char_length, blank=True) def __str__(self): return self.hostname class Dependency(models.Model): device = models.ForeignKey(Device, related_name='dependencies', on_delete=models.CASCADE) dependency = models.ManyToManyField(Device, blank=True) Here is the views.py def new_build(request): if request.method == 'POST': devices = Device.objects devices.all().delete() with open('static/inventory.yml', 'r') as inv_data: inventory = yaml.load(inv_data) for host in inventory: device = Device() device.node = host[:4] device.hostname = host if inventory[host]['dependencies']: # for dependency in inventory[host]['dependencies']: device.dependencies.dependency.add(inventory[host]['dependencies']) device.save() device = Device.objects return render(request, 'network_devices/table-base.html', {'device': device}) So, hopefully you an see i have an inventory file that builds the database. However, i need each device to have dependencies and this is a list that is provided in the yml file. the dependencies are the hostnames of other devices. hope this makes sense. -
Django - Defaulting a Form Field's Value
When I am about to create a model instance via the UI, I'd like to default a field (let's say 'status' to value 'draft'). I tried to do this in the Form in `init(): Form def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) status_id = Status.objects.get(name=constant.status['draft']).uuid self.fields['status'].initial = status_id This works fine: the value is defaulted. However, when I submit the form I get a validation error saying that this field cannot be empty and in the form, the value is empty. I tried doing this in the view as well (same result): View def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) default status to 'Draft' status_id = Status.objects.get(name=constant.status['draft']) form = ModelCreateForm(initial={'status': status_id}) -
Django csrf token in form does not match with the cookie value
I've a form with the csrf_token field. This field does not have the same value as the csrf token in the cookie. Is this a problem? I don't get a message that the csrf protection failed but shouldn't they have the same value? -
what methods should a model contain (django)
When I have a model Car where users can upload a single picture to, I can create a property ImageFile in django to achieve that. Now I would also like to get the metadata from this file and save them to the database. Now Iam very unsure where I should place this method an how I should design it. It would be obvious, to have a method like _set_exifdata() or _update_exifdata() that is called everytime I set an Image to the model. Or a method get_exifdata(imagefile) that returns a dict of exifdatas. But should this method be part of the Car model? Actually, I wont need it anywhere else, so it does not make sense to put it in a general helper class. But on the other hand, I would prefer to split methods in "retrieving data" and "setting data", so _update_exif() for example would do both of it in once, and maybe thats ok in design ways, but maybe its not and there is some rules of model design I should know and respect here. I hope someone can help me with some guidelines for model design (especially for django) and what methods should be part of methods and … -
Cannot assign \"(<Company: Waft Company>,)\": \"BusinessModel.company\" must be a \"Company\" instance
I am trying to update the business model. However, I am getting an error " Cannot assign \"(<Company: Waft Company>,)\": \"BusinessModel.company\" must be a \"Company\" instance.". I believe, I am using company instance to save to the following company as company is FK in BusinessModel. Isn't company a company instance? Here is my helper function for getting the instance def get_instance(_object, encoded_id, slug=False, otherwise=None): try: if slug: return _object.objects.get(slug=encoded_id) else: return _object.objects.get(pk=from_global_id(encoded_id)[1]) except _object.DoesNotExist: return otherwise Here is what I have done class BusinessModel(models.Model): ZERO = '0' ONETOFIFETYTHOUSAND = '1 - 50000' FIFETYTHOUSANDTOONELAKH = '50000 - 1Lakhs' TOTAL_INVESTMENT = ( (ZERO, '0'), (ONETOFIFETYTHOUSAND, '1 - 50000'), (FIFETYTHOUSANDTOONELAKH, '50000 - 1Lakhs'), ) FRANCHISE_FEE = TOTAL_INVESTMENT company = models.ForeignKey(Company, related_name='company_business_model', on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, related_name='industry', on_delete=models.SET_NULL) segments = models.ForeignKey(Segment, on_delete=models.SET_NULL, null=True) total_investment = models.CharField(max_length=50, choices=TOTAL_INVESTMENT, default=None) franchise_fee = models.CharField(max_length=50, choices=FRANCHISE_FEE, default=None) is_refundable = models.BooleanField(default=False) space = models.CharField(max_length=50, blank=False, null=False, help_text="space in square feet") # choice field class BusinessModelInput(graphene.InputObjectType): company = graphene.String() industry = graphene.String() segments = graphene.String() total_investment = graphene.String() franchise_fee = graphene.String() is_refundable = graphene.String() space = graphene.String() expanding_country = graphene.String() expanding_city = graphene.String() expanding_regions = graphene.String() class UpdateBusinessModel(graphene.Mutation): class Arguments: input = BusinessModelInput(description="These fields are required", required=True) id = … -
Ideal Django model for School Period
I am building an school time management app. I made a model like this and some contrainst. class Period : number = models. AutoField() start = models. TimeField() end = models. TimeField() I would like to here your advises. By the way, is there anyway to change to number field ordered by start field automatically? -
IntegrityError: UNIQUE constraint failed
I'm getting this error, and tried to resolve by following other posts, but it was no good. I'm beginner to Django rest_framework and trying to build the rest API with Python. I have 5 models.Few of them are related to each other by Foreign key. The Project and File(models) have foreign key relations between them. All the models have id field as UUIdField with unique=True attribute. I don't have data in Project model. When I try to insert data in Project model via the admin interface, the data successfully gets inserted. But when I try to insert the same instance of File model to two different Project model, it gives me the error message: UNIQUE constraint failed: testapp_project.file_id I'm trying to insert same file to two different projects, and it gives error. Here are my models: class Project(models.Model): id=models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) file = models.ForeignKey(File, on_delete=models.CASCADE, related_name='projects' ) type = models.CharField(max_length=200) def __str__(self): return self.title class File(models.Model): File_Status = Choices("Working","Uploading","Finished") id=models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True) name=models.CharField(max_length=200) filetype=models.ForeignKey(FileType, on_delete=models.CASCADE) software=models.ForeignKey(Software, on_delete=models.CASCADE) description=models.TextField() created=models.DateTimeField(auto_now_add=True) modified=models.DateTimeField(auto_now_add=True) status=models.CharField(choices=File_Status, max_length=200, default=File_Status.Working) def __str__(self): return self.name -
Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19")
I am working on a django project, trying to use GeoDjango. In my setting.py, I added 'django.contrib.gis',to installed app but getting this error. File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\contrib\gis\admin\__init__.py", line 5, in <module> from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\contrib\gis\admin\options.py", line 2, in <module> from django.contrib.gis.admin.widgets import OpenLayersWidget File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\contrib\gis\admin\widgets.py", line 3, in <module> from django.contrib.gis.gdal import GDALException File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\contrib\gis\gdal\__init__.py", line 28, in <module> from django.contrib.gis.gdal.datasource import DataSource File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\contrib\gis\gdal\datasource.py", line 39, in <module> from django.contrib.gis.gdal.driver import Driver File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\contrib\gis\gdal\driver.py", line 5, in <module> from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\contrib\gis\gdal\prototypes\ds.py", line 9, in <module> from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 43, in <module> % '", "'.join(lib_names) django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I have no idea what the error is all about. Could anyone help me out. -
Django signals - multiple requests on same model?
I am using a pre_save signal to store the user who performed the last operation on a particular instance. To achieve this, I'm using a middleware. In the process_request function of it, the signal is registered with the appropriate function, set_user as shown below. mark_who_did = curry(self.set_user, user) models.signals.pre_save.connect( mark_who_did, dispatch_uid=(self.__class__, request,), weak=False ) Then, I'm disconnecting this signal in the process_response function of the middleware. models.signals.pre_save.disconnect(dispatch_uid=(self.__class__, request,)) This works fine when concurrency is not involved. However, suppose we have three concurrent requests - the signal is connected three times, and the set_user method is invoked nine times, for each user-request combination. As per my understanding, each request should have been operating independently, but that is obviously not the case. Is there something I'm missing, or is there something I could change in my code to fix this? -
django multi database djongo
I have a project with 2 database on mogodb. So i m using djongo for that. database used for auth and one link with my custom models. So in my settings i did : # Database DATABASE_ROUTERS = [CrawlerRouter] DATABASES = { 'default' : { 'ENGINE': 'djongo', 'NAME': 'djangodb' }, 'crawler_db' : { 'ENGINE': 'djongo', 'NAME': 'crawler', } } And i created a simple router : class CrawlerRouter: def db_for_read(self, model=None, **hints): print("read crawler_db") print(model) if model == None : return None return 'crawler_db' def db_for_write(self, model=None, **hints): print(model) print("db_for_write crawler_db") if model == None : return None return 'crawler_db' def allow_relation(self, obj1, **hints): return None def allow_migrate(self, db, app_label= None, model_name=None, **hints): if (db in ['auth', 'contenttypes', 'sessions', 'admin']): return False return True Then i created a model : from django.db import models Create your models here. class Channel(models.Model) : created_at = models.DateField() name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: app_label = "channel" db_table = "channels" But when it pass by db_for_read, the model is always None , so it never hit my database with the name 'crawler' with the alias 'crawler_db'. Could you help me? i m beginner with django and i can't find my mistake …