Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2: project root url namespace not working
I have the following url patters in the project root's urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('main/', include('main.urls', namespace='main')), ] But django complains with the following message: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. According Django's documentation, the pattern of 'main' should be correct. What's the problem? -
How to do logging in flask?
The python logging module will have problem in multiprocessing. Because there is no lock between processes while they writinig to the same log file. But the flask or django programes will always run in multiprocessing enviroment when they are hosted by uwsgi. Uwsgi run multiple workers. One worker is one process that hosted the flask/django program. So this is a situation that write log into one file from multiple process How flask or django to solve this? -
Django User Profile Model Sign Up Form
I'm developing django project. Now I'm making sign up form with profile model. But I got a problem. models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) usernickname = models.CharField(db_column='userNickName', max_length=50, blank=True, null=True) userbirth = models.DateField(db_column='userBirth', blank=True, null=True) class Meta: managed = False db_table = 'profile' @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py : from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): userBirth = forms.DateField() class Meta: model = User fields = ('username', 'password', 'userBirth') widgets = { 'username': forms.TextInput(), 'password': forms.PasswordInput(), 'userBirth': forms.DateField(), } views.py : def join(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.userbirth = form.cleaned_data.get('userbirth') user.save() user = User.objects.create_user(username=user.username, password=user.password) user.save() return redirect('index') else: form = UserForm() return render(request, 'registration/join.html', {'form':form}) and when sign up, InternalError at /join/ (1054, "Unknown column 'profile.user_id' in 'field list'") this error returns. when log in to /admin, same error returns. I don't have any idea.. I refernced this blog: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html#sign-up-with-profile-model -
Use input type text of html as {% csrf_token %}
I am trying to run a client server application using django using ajax post. All the tutorials that i went across uses a form as the {% csrf_token %} but i want the input type text to be used as the {% csrf_token %} . Also, I want the method post to be used. Right now, I am doing it as follows - <form class="forms" method="POST"> {% csrf_token %} <input type="text" name="chat" id="chatb" placeholder="Hi there! Type here to talk to me." onfocus="placeHolder()"> </form> So, here I am making a form. But, I want an alternative of not using forms. Also, i want to save the previously entered data. -
Wagtail - getting routablepageurl of page category in other page
I have filter of category on mydomain.com/gallery/album/2017 class Gallery(RoutablePageMixin,Page): short_description = models.CharField(max_length=300,blank=True) content_panels = Page.content_panels + [ FieldPanel('short_description'), InlinePanel('image_gallery', label="image gallery"), ] def get_posts(self): return AlbumImageGallery.objects.all() @route(r'^albums/(?P<album>[-\w]+)/$') def post_by_category(self, request, album, *args, **kwargs): self.get_posts = self.get_posts().filter(album__slug=album) return Page.serve(self, request, *args, **kwargs) def get_context(self, request, *args, **kwargs): context = super(Gallery, self).get_context(request, *args, **kwargs) context['albums'] = Album.objects.all() context['album_image'] = AlbumImageGallery.objects.all() context['get_posts'] = self.get_posts context['gallery'] = self return context In my Html ` <a href="{% routablepageurl gallery "post_by_category" each.slug %}"> {{each.album_name}}</a>` Now i want to get mydomain.com/gallery/album/2017 from my other page class MymodelPage(Page): ... get_context(): context['gallery_images'] = Image.objects.all() context['gallery'] = Gallery.objects.get() MymodelPage.html error NoReverseMatch at /media-corner/ Reverse for 'post_by_category' with arguments '('',)' not found. 1 pattern(s) tried: [u'albums/(?P<album>[-\\w]+)/$'] I want to get gallery url/slug on my Modal RoutablePageMixin i tried to pass url page its gives me error -
Django translation makemessage error
I'm creating django multilingual website. Settings.py USE_I18N = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ], }, }, ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('de', _('German')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) template: <h5>{% trans "Hello, this is testing page" %}</h5> urls: from django.conf.urls.i18n import i18n_patterns from django.conf.urls import include, url urlpatterns = [ url(r'^rev/', rev, name="rev"), url(r'^userprofile/', userprofile, name="profile"), ] views: @login_required def rev(request): return render_to_response('rev.html', {'client': request.user.client, 'user': request.user}) @login_required @require_http_methods(["GET"]) def userprofile(request): return render(request, 'userprofile.html', { 'user': request.user, 'form': UserProfileForm(instance=request.user) }) So, using python makemessage -l de command I got next error: CommandError: errors happened while running msguniq msguniq: \u041d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u0442\u044c \u0438\u0437 \xabASCII\xbb \u0432 \xabUTF-8\xbb. msguniq \u043f\u043e\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u043d\u0430 iconv(). \u042d\u0442\u0430 \u0432\u0435\u0440\u0441\u0438\u044f \u0431\u044b\u043b\u0430 \u0441\u043e\u0431\u0440\u0430\u043d\u0430 \u0431\u0435\u0437 iconv(). I think, that I set urls incorrect. All answers about it are at least 3-4 years old, on newest django version , setting urlpatterns = i18n_patterns[....] causes error: TypeError: 'function' object is not subscriptable GNU gettext installed. Why Am I really getting this error, and I know, that … -
Dynamic Django Sidebar
I'm trying to create a dynamic sidebar in Django, which gets loaded using the following models. class MenuItem(models.Model): display_name = models.CharField(max_length=100) active = models.BooleanField(default=True) def __unicode__(self): return self.display_name class Meta: default_permissions = () class MenuParent(MenuItem): pass class MenuTitle(MenuParent): pass class PageGroup(MenuParent): parent = models.ForeignKey(MenuTitle) icon = models.ForeignKey(Icon) class Page(MenuItem): parent = models.ForeignKey(MenuParent) icon = models.ForeignKey(Icon) page_name = models.CharField(max_length=100, blank = True, null = True) user_access = models.ManyToManyField(User, verbose_name="Gebruikers", blank=True) group_access = models.ManyToManyField(Group, verbose_name="Groepen", blank=True) objects = PaginaManager() class Meta: verbose_name_plural = "Pagina's" The different subclasses are made such that a page can be directly under a title, or under a group. A group can only be under a title. I created a manager to get all the pages that a user has access to, either through user_access or through group_access. I however cannot get this to work decently. Could anyone help me create this manager? And a second question. If I want to add an order in which the menu item's are displayed, how would you go at this? -
Using distinct on annotations
I am trying to get a distinct list of items. The db has a created field which is datetime and I need it as a date for my query. So I added an annotation. The problem is that distinct won't work on the annotation... distinct_failed_recharges = recharges.filter( status=FAILED ).annotate( created_date=TruncDate('created') ).distinct( 'created_date', 'sim', 'product_type', 'failure_reason' ).values_list('id', flat=True) This is the error that I get: django.core.exceptions.FieldError: Cannot resolve keyword 'created_date' into field -
Do I need to append dispatch_uid to signal in this case?
On Django Documentation, I read this : https://docs.djangoproject.com/en/2.0/topics/signals/#preventing-duplicate-signals In some circumstances, the code connecting receivers to signals may run multiple times. This can cause your receiver function to be registered more than once, and thus called multiple times for a single signal event. Then, If I use signal as, class CustomauthConfig(AppConfig): name = 'myapp' def ready(self): import myapp.signals And @receiver(post_save, sender=TestModel) def update_log(sender, instance, **kwargs): TestModelLog.objects.create(description=instance.description, datetime=instance.updated) Question: Is it right that I don't need dispatch_uid? Or if I have to use dispatch_uid, Would you give me a sample for using dispatch_uid? My purpose is to prevent duplicates -
post data to a django view from angularjs controller
I have an existing views.py file in my django app something like this: from django.shortcuts import render def segment_image(request): if request.method == 'POST': form = segment_form() else: if form.is_valid(): info = request.POST['info_name'] output = script_function(info) return render(request, 'your_app/your_template.html', { 'output': output, }) return render(request, 'your_app/your_template.html', { 'form': form, }) def script_function(info): '''here goes my main logic''' x=y=w=h=102 return x,y,w,h which used to interact with a django template and a django form.But, now i am in the process of shifting everything to a angular frontend app so i replaced the form with a angular $http post. index.html <div class="col-xs-12 col-sm-12 col-md-6 col-lg-4" ng-repeat="image in images track by image.pk"> <h3> Image {{ image.pk }} <button class="btn btn-warning" ng-click="deleteImage(image)">Delete</button> <button class="btn btn-primary" ng-click="segmentImage(image)">Segment</button> </h3> <a href="{{ image.image }}"> <img class="img-responsive" ng-src="{{ image.image }}"> </a> </div> app.js ... $scope.segmentImage = function(image) { $http({method:'POST', url:'127.0.0.1:8000/image/segment_image/', data:{'image': image}}) .then(function successCallback(response) { console.log('success') },function errorCallback(response) { console.log('failed') console.log(response.config) console.log(response.statusText) } )}; ... Now what changes do i need to make to my views.py so that it can recieve the image from angularapp and pass it to my script_function, and render the return values(x,y,w,h) back to index.html -
How to add filter functionality to filter multiple values with checkbox from database in django?
I want to filter jobs by selecting multiple categories by selecting checkbox that I need to filter. How can we filter those categories dynamically from database in django. How can I send selected values to views.py so that I can get required results. -
Django: Capturing and manipulating multiple thumbnails into one image
One of the challenges that I have and I am not able to find a way to target it is manipulating images in django. For example: if we have a scanned image which contains multiple small images - lets call them thumbnails - as you see in the following attached image: Multiple small images into a big image Taking in consideration that we do not know the coordination of every thumbnail. We do not know where the thumbnail starts and ends. How can we know when thumbnail starts and ends? Is it a good idea to slice and crop every thumbnail - and then storing it as png - because we want to check some colors values into it - RGB colors I hope that I have succeeded to explain the problem. Thank you -
Circular Import in Django
I have been trying to run a client-server application using Django. When I am trying to run my server in Django , it is giving me the following error. django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The project urls.py - from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('chat.views')), ] App's views.py - from django.shortcuts import render from django.http import JsonResponse def home(request): if request.method == 'POST': if request.is_ajax(): //code return JsonResponse(data) return render(request,'index.html') Where am I going wrong? -
DRF: serialize Generic relations nested representation with "many" = True
As described in the docs for serializing targets of generic relationships using the to_representation: Specifically: If you need the target of the relationship to have a nested representation, you can use the required serializers inside the .to_representation() method: def to_representation(self, value): """ Serialize bookmark instances using a bookmark serializer, and note instances using a note serializer. """ if isinstance(value, Bookmark): serializer = BookmarkSerializer(value) elif isinstance(value, Note): serializer = NoteSerializer(value) else: raise Exception('Unexpected type of tagged object') return serializer.data Now, considering that such a need would arise when the targets of the Generic relation are of varied "instance types", I was attempting to get a more concise serialized output of the form: Serializer: class MySerializer(serializers.ModelSerializer): ... related = RelatedSerializerField(required=False, many=True) with the desired nested output: { "related": { "instance_type_a_key": [ { <serialized output of instance_type_a's serializer>, <serialized output of instance_type_a's serializer>, ... }, ], "instance_type_b_key": [ { <serialized output of instance_type_b's serializer>, <serialized output of instance_type_b's serializer>, ... }, ], ... ... }, ... ... } Since the to_representation is at the level of each individual instance, I couldn't find a way to achieve the desired representation at this granular level. Is there higher level construct, before/after to_representation that will allow … -
Limiting choices in foreign key dropdown in Django using Generic Views ( CreateView )
I've two models: First one: class A(models.Model): a_user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) a_title = models.CharField("A title", max_length=500) Second one: class B(models.Model): b_a = models.ForeignKey(A, verbose_name=('A'), unique=False, on_delete=models.CASCADE) b_details = models.TextField() Now, I'm using CreateView to create form for Value filling : class B_Create(CreateView): model = B fields = ['b_a','b_details'] Then using this to render these field in templates. Now, my problem is, while giving the field b_a ( which is the dropdown ), it list downs all the values of model A, but the need is to list only the values of model A which belongs to the particular logged in user, in the dropdown. I've seen all the answers, but still not able to solve the problem. The things I've tried: limit_choices_to in models : Not able to pass the value of A in the limit_choices form_valid : Don't have the model A in the CreateView, as only B is reffered model in B_Create passing primary key of A in templates via url : Then there is no instance of A in the template so can't access. Also, don't want to handle it in templates. I'm new to Django and still learning, so don't know to override admin form. … -
Redirecting user to profile after sign up
I am overriding the sign up view in allauth by using my own. I can sign up and the user will be logged in, but I'd like to redirect the user to their profile page. I have an app called profiles that has a view called Index in the profiles.urls Index can take in 2 parameters, a slug (username) or a pk (id). After the user hits the sign up button and everything is valid, I want to redirect them to their profile page: /profiles/{their username} profiles.urls app_name = 'profiles' urlpatterns = [ url(r'^(?P<pk>\d+)/$', views.Index.as_view(), name='Index'), url(r'^(?P<slug>[\w_]+)/$', views.Index.as_view(), name='Index'), ] oauth.views class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' def form_valid(self, form): return redirect('profiles:Index', slug=form.username) oauth.views is where I make my custom SignupView. Now when I try to sign up, I don't get redirected to the user's profile. Instead I get this error: File "C:\python3.6.3\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\python3.6.3\lib\site-packages\allauth\account\views.py", line 102, in post response = self.form_valid(form) File "C:\Users\xx\PycharmProjects\examplesite\oauth\views.py", line 17, in form_valid return redirect('profiles:Index', slug=form.username) AttributeError: 'RegisterForm' object has no attribute 'username' How do I make it so that the user is redirected to their profile based on the username they selected? -
how can i make django sign up form? (django 1.11.8)
I'm gonna to make sign up form. I made login form. I am using auth_user. (django default table) and I had to add more columns, so I made a new table and referenced auth_user table by foreign key. and I'm going to make sign up form. How can I make it? In django default sign up page, it only requires id, pw. (In sign form, user must input email, questions for when he(she) find password, address, birthday, etc..) -
Schedule in different time zone
I'm developing a Django project. I want to sync classes automatically. My code: from datetime import timedelta from celery.schedules import crontab CELERYBEAT_SCHEDULE = { 'sync-classes': { 'task': 'scheduler.tasks.sync_classes', 'schedule': crontab(hour='0', minute=0), } CELERY_ENABLE_UTC = False CELERY_TIMEZONE = 'Europe/London' It works in the London time zone. Each class has a different time zone. I want the schedule to run automatically based on the relevant time zone of classes. In sync_classes() method I get all classes and sync it in London Time zone. Question: How can I sync every class based on its time zone? -
Subquery returns more than 1 row in Django while connecting models
I want to get authorName whenever someone search for a book and yeah I have tried many to many but it is very confusing and after researching some things I got to a view which I thought should work fine but it is returning an error "1242, 'Subquery returns more than 1 row'" here are some of the relevant code: Models from __future__ import unicode_literals from django.db import models class Books(models.Model): bid = models.BigIntegerField(primary_key=True) bname = models.CharField(max_length=200, blank=True, null=True) bdescription = models.TextField(blank=True, null=True) def __str__(self): return self.bname class Authors(models.Model): aid = models.AutoField(primary_key=True) aname = models.CharField(max_length=200, blank=True, null=True) adescription = models.TextField( blank=True, null=True) def __str__(self): return self.aname+"\n" class Bookauth(models.Model): bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True) aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True) Views for what I thought was right def authbook(request): s = Authors.objects.all() r = Books.objects.filter(bookauth__aid = s).values() return HttpResponse(r) Guide me please Django gods!! -
How to pass a Model to a Generic Serializer from a ViewSet in Django Rest Framework
I'm trying to create a Generic TemporalModelSerializer. The TemporalModelSerializer creates a new record and terminates the old record. It is successful in doing so, however now i would like to use the Serializer for other models. Is it possible to pass the model into the Serializer and then use it in this line? Thanks OptionMaster.objects.filter(pk=instance.pk, vflag=1).update(**new_record) Views class OptionMasterViewSet(viewsets.ModelViewSet): serializer_class = TemporalModelSerializer queryset = OptionMaster.objects.filter(vflag=1) lookup_field = 'contractcode' The Generic TemporalModelSerializer class TemporalModelSerializer(serializers.ModelSerializer): vf = serializers.HiddenField(default=datetime.now()) vt = serializers.HiddenField(default=datetime(3000, 12, 31, 23, 00, 00, 000000)) vflag = serializers.HiddenField(default=1) vu = serializers.HiddenField(default='Theodore') class Meta: model = OptionMaster exclude = ('vt', 'vf', 'vu', 'vflag') def update(self, instance, validated_data): time_now = datetime.now() old_record = {} new_record = {} for field in instance._meta.get_fields(): old_record[field.name] = getattr(instance, field.name) new_record[field.name] = validated_data[field.name] old_record['vt'] = time_now old_record['vflag'] = 0 new_record['vf'] = time_now self.delete_me(old_record) OptionMaster.objects.filter( pk=instance.pk, vflag=1).update(**new_record) return instance def delete_me(self, old_record): obj = OptionMaster.objects.create(**old_record) -
Django Rest Framework foreign key multiple data
I have a model call Schedule, it is like reminder function. I also have another model called Family which user can add family member in it. So in schedule, i create a foreign key to link family inside so that it will include the family member id in it. Here is the how my API for schedule looks like: https://imgur.com/a/bwYDn And here are my questions. As you can see based on the image in above link, the userId is a drop down. is it possible to make it userId = self.request.user.userId ? In the schedule api, the familyId is a drop down that consist of all family member(basically, even other people who added their family), is there a way to filter it so that it will only shows a dropdown of only the current user familyId appear ? When creating a schedule, user can only insert 1 familyId. Is there a way to choose more than 1 familyId ? For eg, user can insert familyId 1 and 2 Here is my code models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=40, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) class Family(models.Model): userId = … -
Future-proofing my application code for readability (Django, Beginner)
The aim of my website is to have a page, let's call it "Random Question!" Each time the user enters the page, a set of numbers are randomly generated, and they have to correctly answer the question: numbera + number b . IF they are correct, they go to a page that says "Correct" and then they are redirected back to the same page, again, with a different set of numbers. Now, the issue is, on the first page "Random Question!", I want to add another question to it. Views.py: def form_handle(request): if request.method == 'POST': form = MyForm(request.POST) # if post method then form will be validated if form.is_valid(): cd = form.cleaned_data num1 = cd.get('num1') a = request.session.get('a', 0) b = request.session.get('b', 0) if float(num1) == float(a + b): # give HttpResponse only or render page you need to load on success return render(request, 'sectipn1part1success', {}) else: # if sum not equal... then redirect to custom url/page return HttpResponseRedirect('rr/') # mention redirect url in argument else: a = random.randrange(5,10); b = random.randrange(10,20); request.session['a'] = a request.session['b'] = b question1 = ('What is ' + str(a) + ' + ' + str(b) + ' ?') form = MyForm() # blank … -
Saving Django Inline Formsets
I've been working on a report form and I've ran into a bit of a road block. The report is basic, with exception to the fact that the report can have many punches (clock in, clock out). To make that usable on the form I have to generate a custom form with attributes. When I do that, I am unable to save the inline form data. Where am I going wrong here? ''' views.py ''' def reportupdateview(request, pk): form = ServiceReportUpdateForm report = get_object_or_404(ServiceReportModel, pk=pk) formset = PunchesFormSet(instance=report) print(report) if request.method == 'POST': reportform = form(request.POST, instance=report) punchesform = form(request.POST, instance=report) if reportform.is_valid(): if punchesform.is_valid(): reportform.save() punchesform.save() return redirect('service:report-update', pk=report.pk) if request.method == 'GET': report.updated_by = request.user reportform = form(instance=report) context = { 'report': reportform, 'punches': formset } return render(request, 'service/report-update.html', context) ''' forms.py ''' class ServiceReportUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ServiceReportUpdateForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['request_number'].required = False self.fields['reported_by'].widget.attrs['readonly'] = True self.fields['updated_by'].widget.attrs['readonly'] = True self.fields['equipment'].widget.attrs['readonly'] = True self.fields['report_reason'].widget.attrs['readonly'] = True def clean_reported_by(self): instance = getattr(self, 'instance', None) if instance and instance.pk: return instance.reported_by else: return self.cleaned_data['reported_by'] class Meta: model = ServiceReportModel fields = [ 'site', 'invoiced', 'paid', 'request_number', 'reported_by', 'updated_by', 'equipment', 'report_reason', … -
Intellij complains of incorrect configuration for django project
Whenever I run my python django application in Intellij, it shows me a dialog box saying configuration is incorrect and gives me an option to edit or run anyway. Following is the screenshot of my configuration. Not sure what is it that I am missing. Update: It does show intermittently in the same configuration dialog box that Django project root is not configured and I am not sure how I can do that. Also, when I run the project anyway, it says, No manage.py file specified in Settings->Django Support -
Speed for querying the whole database using objects.filter()
I am using django to make a website in which a user can log in and upload files. I was wondering whether using files = upload.objects.filter(user=User) to filter all the files uploaded by a specific user an efficient way. What if my database has thousands of files in it. Will this method work in an efficient way? Here's models.py: class upload(models.Model): files = models.FileField() title = models.CharField(max_length = 30) user = models.ForeignKey(User,on_delete=models.CASCADE)