Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django static url with mezzanine and templates
Ive been stuck for awhile and I cant seem to get it. Before you say python manage.py collectstatic yes, I've done that. Here's the issue: I am using one of mezzanine's solid layout. It doesn't seem like the mezzanine's files merge with the solid template layout. On my front page, the CSS works, but if i head over to /admin page, then the css loads like this admin/static/mezzanine/some_css.css. Anything but the root main page loads the css file. So I'm guessing it's that path, but I've double checked my root path, it seems correct? settings.py PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH) # PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) also tried this STATIC_URL ='static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') # STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "solid/static"), ) also tried this STATICFILES_DIRS = ( os.path.join(os.path.realpath(PROJECT_ROOT), "solid/static"), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', ) urls.py urlpatterns +=[]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) simplfied file structure app ---app ---solid static admin css mezzanine templates ---static admin css mezzanine manage.py -
change key val in django to list
how to change this format to simple list [{'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 100}, {'qte': 350}, {'qte': 11}] it's result of this requête inst = Produit.objects.values('qte') print inst i need to be like this format [100,100,100,100,100,100.....] -
Working with external code "Allauth" Django
Im new to Django, and I'm trying to integrate Django Allauth. I'm really not sure if I did choose the right approach to work with external code (e. g. Allauth). So far I created an App for Allauth and in that App I recreated a lot of the URLs so that I could overwrite the templates, see code: urlpatterns = [ url(r'^login/$', all_views.LoginView.as_view(template_name='user/login.html'), name='account_login'), url(r'^logout/$', all_views.LogoutView.as_view(template_name='user/logout.html'), name='account_logout'), url(r'^signup/$', SignupView.as_view(template_name='user/signup.html'), name='account_signup'), url(r'^profile/$', ProfileView.as_view(), name='profile'), url(r'^profile/public/(?P<slug>[\w\-]+)/', ProfilePublic.as_view(), name='public_profile'), url(r'^profile/update/', UpdateProfileAbout.as_view(), name='profile_update'), # E-mail url(r"^email/$", all_views.email, name="account_email"), url(r"^confirm-email/$", all_views.email_verification_sent, {'template_name': 'user/verification_sent.html'}, name="account_email_verification_sent"), url(r"^confirm-email/(?P<key>[-:\w]+)/$", all_views.ConfirmEmailView.as_view(template_name='user/confirm_email.html'), name="account_confirm_email"), ] Now I'm trying to integrate email verification but I do recieve a ConnectionRefusedError. Same behaviour happens when I import and include the allauth urls from "allauth/account". If feels like i did choose the wrong approach to integrate Allauth? Can anyone help to solve the Error? Also I'm a little confused where to put .txt files to render the email send to the user. -
Django: disconnect a post_save signal to avoid recursion
This is my model: class Paper(models.Model): ... collection = models.ForeignKey(Collection, on_delete=models.CASCADE) rang = models.IntegerField(default=0) class Meta: ordering = ['collection','rang'] When saving the model, I want it to update all the 'rang' fields in each instance of the model so that they increase by 10. I use the post_save signal below to avoid a problem of recursion: @receiver(post_save, sender=Papier) def redifine_rang(sender, *args, **kwargs): for idx, paper in enumerate(Paper.objects.filter(collection = kwargs['instance'].collection)): paper.rang = idx*10 Signal.disconnect(post_save, sender=Papier) paper.save() Signal.connect(post_save, sender=Papier) However, I can't get the signal to disconnect and connect. Does anyone have any recommendations? -
how to reverse query for django_filters fields
models.py class Product(models.Model): . . pass class Color(models.Model): color_name = models.CharField(blank=True, max_length=50) color = ColorField(default='#FF0000') class ProductColor(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) color = models.ForeignKey('Color', on_delete=models.CASCADE) filters.py class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = ['color',] i want to filter product by color using django_filters how should i do?? -
Display tomorrow's date in Django template
I want to display tomorrow's date. I am using a generic ListView. Today's date is easy via: {% now "jS F Y H:i" %} -
SyntaxError: from __future__ imports must occur at the beginning of the file
Whenever i'm trying to do python manage.py runserver , this following massage shows . How do i solve this Performing system checks... Unhandled exception in thread started by <function wrapper at 0x038DB8F0> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\Deep\Dev\trydjango1-11\src\mupicky\urls.py", line 19, in <module> from restaurants.views import home File "C:\Users\Deep\Dev\trydjango1-11\src\restaurants\views.py", line 3 from __future__ import unicode_literals SyntaxError: from __future__ imports must occur at the beginning of the file -
Opening Ajax Response(pdf) in new window browser. Ok with Firefox bur error in chrome (Django+Javascript)
def print_users(request,*args,kwargs): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf; charset=utf-8') response['Content-Disposition'] = 'attachment; filename="MyUsers.pdf";charset=utf-8' buffer = BytesIO() report = MyPrint(buffer, 'Letter') pdf = report.print_users() response.write(pdf) return response JS--> $.ajax({ url: "/order/print/users/", type: "post", //data: { "category": myObject } }).done(function (result) { window.open("data:application/pdf," + encodeURIComponent(result)); }).fail(function (jqXHR, textStatus, errorThrown) { // needs to implement if it fails }); console.log(result)--> """ %PDF-1.4 %���� ReportLab Generated PDF document http://www.reportlab.com 1 0 obj << /F1 2 0 R >> endobj 2 0 obj << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj 3 0 obj << /Contents 7 0 R /MediaBox [ 0 0 612 792 ] /Parent 6 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj 4 0 obj << /Outlines 8 0 R /PageMode /UseNone /Pages 6 0 R /Type /Catalog >> endobj 5 0 obj << /Author (\(anonymous\)) /CreationDate (D:20170826165648-06'00') /Creator (\(unspecified\)) /Keywords () /ModDate (D:20170826165648-06'00') /Producer (ReportLab PDF Library - www.reportlab.com) /Subject (\(unspecified\)) /Title (\(anonymous\)) /Trapped /False >> endobj 6 0 obj << /Count 1 /Kids [ 3 0 R ] /Type … -
celery .env variables not used in settings.py
I am stuck on using config vars from my .env file inside the settings.py for my celery.py. when i hardcode CELERY_BROKER_URL = 'redis://localhost', everything works, however, when i use CELERY_BROKER_URL= os.environ.get('REDIS_URL'), the REDIS_URL is not taken over and I get an error. celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ['DJANGO_SETTINGS_MODULE'] = 'xlink.settings' app = Celery('xlink') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) .env: REDIS_URL = 'redis://localhost' REDIS_PASSWORD = 'yow' REDIS_HOST = 'localhost' NOT WORKING settings.py: CELERY_BROKER_URL= os.environ.get('REDIS_URL') CELERY_RESULT_BACKEND= os.environ.get('REDIS_URL') WORKING settings.py: CELERY_BROKER_URL= 'redis://localhost' CELERY_RESULT_BACKEND= 'redis://localhost' tasks.py: import celery from celery import shared_task @shared_task def add(x, y): return x + y -
Django/Testing: How do I populate the initial DB data when functional testing against staging server
I'm trying to run functional test for a Django webapp. The test is for a step in the middle of a process, so it requires the user to already have some data in the DB. When I'm testing on my local PC, I use LiveServerTestCase to spin up the server and interact with it through Selenium, generating the data in the setUp function using model code from the concerned app. When I'm testing against the staging server however, and I interact with it through Selenium on my local PC, the setUp code does nothing since it's running on my local PC. My questions: 1) is it best practice to use model code to initialize a functional test (since it's supposed to be blackbox)? 2) how would I populate the DB when running against the staging server? -
Page not found(404) error if reset password email link is wrong in django
I am using django default password reset feature.I get the set new password email link via email. If the url is correct then it's fine. Now if I put a wrong or invalid link then I get, The current URL, account/reset/NTQ/4ox-7f135b9b74e7a4aa909fdd/, didn't match any of these. accounts/urls.py -- url(r'^password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), #url(r'^reset/',auth_views.password_reset_confirm, name='empty_password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), Template password_reset_confirm.html -- {% extends 'base.html' %} {% block content %} {% if validlink %} <h3>Change password</h3> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Change password</button> </form> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} {% endblock %} I tried with -- url(r'^reset/',auth_views.password_reset_confirm, name='empty_password_reset_confirm') But in that case I am getting AssertionError at /account/reset/NTQ/4ox-7f135b9b74e7a4aa909fdd/ Any help is highly appreciated. Thanks in advance. -
Django form not rendering after POST
In the below example, I am trying to get all the error messages to display in template. I have tried almost everything mentioned in all the forum. Below is my code. Please tell me what I am missing Form class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user View def register (request): print(request.method) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() print("Saved") return render(request, 'main/product.html',{}) else: print("Some Error", form.errors) args = {'form':form,'carousel':'display:none'} print(args['form']) return render(request, 'accounts/register.html',args) # if a GET (or any other method) we'll create a blank form else: form = RegistrationForm() args = {'form':form,'carousel':'display:none'} return render(request, 'accounts/register.html',args) HTML Template <form id="register" method="post" action="{% url 'register' %}"> {% csrf_token %} <div class="form-register-with-email"> <div class="form-white-background"> <div class="form-title-row"> <h1>Create an account</h1> </div> {{ form.errors }} {% for field in form %} <div class="form-row"> <label> <span>{{field.label}}</span> {{ field }} </label> </div> {% endfor %} <div class="form-row"> <button type="submit">Register</button> </div> </div> </div> </form> The view is triggered after I press submit and the form shows all the error message … -
Django rest framework update related FileField of a model
Say I have these models: class House(models.model): address = models.CharField(max_length=100) class HouseImage(models.Model): image = models.ImageField(...) house = models.ForeignKey(House, related_name='images') And this serializers: class HouseImageSerializer(serializers.ModelSerializer): class Meta: model = HouseImage fields = ('image', ) class HouseSerializer(serializers.ModelSerializer): images = HouseImageSerializer(many=True, required=False) class Meta: model = House fields = ('address', 'images', ) And this view: class HouseDetails(generics.RetrieveUpdateDestroyAPIView): serializer_class = HouseSerializer queryset = House.objects.all() I am making to calls from my frontend. One creates the House (and it works) and the second one is supposed to send the images. Therefore, in the second call I am making a PATCH request (with axios) and my request.data is {'images': [InMemoryUploadedFile1, InMemoryUploadedFile2,...]} Questions: Am I doing correct so far by defining the images field on HouseSerializer? If it's correct, what else should I do? Because I know I need to somehow map each of the image in images list in my request.data to the image field in HouseImage. Is there a better approach in implementing this? -
AssertionError: The field 'channel_count' was declared on serializer UserSerializer, but has not been included in the 'fields' option
I add some function in UserSerializer class: #!/usr/bin/env python # -*- coding: utf-8 -*- # author: Kun Jia # date: 05/08/2017 # email: me@jarrekk.com from django.contrib.auth import get_user_model from channel.models import Subscribe from video.models import CollectFavor, WatchStatus from rest_framework import serializers UserModel = get_user_model() class UserSerializer(serializers.ModelSerializer): channel_count = serializers.SerializerMethodField() collect_count = serializers.SerializerMethodField() watch_count = serializers.SerializerMethodField() class Meta: model = UserModel fields = ( 'id', 'username', 'first_name', 'last_name', 'email', 'password', 'channel_count', 'collect_count', 'watch_count', ) read_only_fields = ('id',) extra_kwargs = { 'password': {'write_only': True, 'min_length': 6, 'max_length': 16} } def get_channel_count(self, obj): return obj.subscribe_set.filter(subscribe=True).count() # return Subscribe.objects.filter(user=obj, subscribe=True).count() def get_collect_count(self, obj): return obj.collectfavor_set.filter(collect=True).count() # return CollectFavor.objects.filter(user=obj, collect=True).count() def get_watch_count(self, obj): return obj.watchstatus_set.filter(watch=True).count() # return WatchStatus.objects.filter(user=obj, watch=True).count() when I get json data, it's OK, but when I patch data like: {'first_name': 'test_name'} it occurs: AssertionError: The field 'channel_count' was declared on serializer UserSerializer, but has not been included in the 'fields' option. -
Django crontab not working in elastic beanstalk
My cron jobs work fine on localhost but when i deploy they are not getting added. The following settings.py: CRONJOBS = [ ('*/1 * * * *', 'push.cron.my_scheduled_job') ] In development, cron works perfectly by doing this: python manage.py crontab add python manage.py crontab run 2e847f370afca8feeddaa55d5094d128 But when i deploy it to server using.. the cron jobs don't get added automatically. How do i add the crob jobs to the server ? -
Use django authentication system from multiple apps
I am developing django base web service now and I am confused. I have three projects as a django projects. app1 - use from the end user app2 - use from the service providor app3 - use from the operator(administrator) I made one database from app3(migration) and I created symbolic links (models.py, migrations dir) to app1 and app2. And then I try to use user authentication system of django from my app1, I got a following error. The above exception (relation "myapp1_user" does not exist LINE 1: ...myapp1_user"."modify_date" FROM ^ ) was the direct cause of the following exception: I know what is wrong. It's because I don't have myapp1_user table on my database. I only have app3_user table. But I have no idea how can I configure to work well. Does somebody have any idea? Please let me know. -
unable to fetch GET form data in url in django view
i am trying to make a search view, and the results are shown. so for without pagination the search view works fine but when i added pagination it stopped working. Below is my code views.py def search_query(request): if request.method == 'GET': #try: if 'q' in request.GET: query_string= request.GET.get('q') if len(query_string) == 0: return HttpResponseBadRequest('Invalid Search') else: query_list = query_string.split(' ') posts = _search(query_list) paginator = Paginator(posts, 1) page = request.GET.get('page') if page is None: page = 1 else: pass try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) return HttpResponseBadRequest() except EmptyPage: posts = paginator.page(paginator.num_pages) return HttpResponseBadRequest() context = { 'posts': posts, } return render(request, 'search/search.html', {'posts': posts,}) #except: # return HttpResponseBadRequest('Outside Try') Function below does the actual searching def _search(query_list): result = [] for query in query_list: query = query.lower() try: posts = Post.objects.order_by('-date_created').filter(tag__tag__icontains=query) for post in posts: if post in result: pass else: result.append(post) except: result = None return result below is the snippet of search.html pagination part <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> {% if posts.has_previous %} {% comment %} <a href="?page={{ posts.previous_page_number }}">previous</a> {% endcomment %} <li class="page-item"> <a class="page-link" href="?q={{ request.GET.q }}&?page={{ posts.previous_page_number }}" tabindex="-1">Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" … -
Django, change directory inside template
I have slider_image folder inside media folder which saves resized images, and I want to access it (src="/media/{{ x.image }}" this is my code inside template, now I want to access slider_image) . any help? -
How to validate the dimension(width and lenght in pixel) of django image on upload?
I have the following image model, and I would like to validate the image dimension why uploading only a jpeg image. Kindly advise. from django import forms from .models import ImageUploadModel class ImageUploadForm(forms.ModelForm): class Meta: model = ImageUploadModel fields = ('image',) -
Sorting related items in descending order in django template
I want to sorting items from database in descending order in template page {% for n in article.comment_set.all %} {{ n.text }} {% endfor %} Model Example: class comment(models.Model): text = models.TextField(verbose_name="Add Comment") art = models.ForeignKey(article, on_delete = models.CASCADE) -
Iterate through groups, then loop item by item
Django 1.11.4 PostgreSQL 9.6.3 Below is a bookmark model. class Bookmark(CommonUrlMethodsMixin, models.Model): memo = models.CharField(max_length=200, null=False, blank=True, default="") # Intentionally blank. # For displaying in ModelForm. content_type = models.ForeignKey(ContentType) content_type_for_filter = models.CharField(max_length=6, null=False, blank=True, default="") object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "{}: {} {}".format(self.content_object._meta.verbose_name.title(), self.content_object, self.memo) class Meta: verbose_name = _("bookmark") In my project bookmarked can be a Frame, an Item, a Sheet. So, I organized a special field in the Bookmark model content_type_for_filter. It may contain either "frame", or "item" or "sheet". Bookmarks must be shown in groups: first bookmarks for Frames, then for Items and lastly for Sheets: Frames bookmark 1 bookmark 2 bookmark 3 Sheets bookmark 4 bookmark 5 Items bookmark 6 bookmark 7 bookmark 8 Then in the personal area I'd like to show the bookmarks. In views now I have: def get_context_data(self, **kwargs): bookmarks = user.bookmark_set.all() # context['bookmarks'] = bookmarks It seems that my code is not acceptable. Look: I will have to handle bookmarks somehow in Python. Use a named tuple or something. Or at least three lists of lists. I suppose, that my select from the data base is not optimal. Is suppose, it may … -
Django - How include() used to create plug and play URLs?
As mentioned here, the include() function allows referencing other URLconfs. Note that the regular expressions for the include() function doesn’t have a $ (end-of-string match character) but rather a trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing. The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under /polls/, or under /fun_polls/, or under /content/polls/, or any other path root, and the app will still work. Need clarification on second point(above) about, include() is to make it easy to plug-and-play URLs, For a webapp: webapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py where, root URLconf is pointing to webapp.urls as shown below, from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^webapp/', include('webapp.urls')), ] For webapp app, How include() can be used in creating plug and play URLS? -
How to Append to Array Field in Python Django
I am making an E commerce site, I want to store Cart elements in an integer Array Field. I am using PostGreSql as my database. I have created model for cart by extending Django User model. Here is my model from django.db import models from django.contrib.auth.models import User from django.contrib.postgres.fields import ArrayField # Create your models here. class UserCart(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) user_product=models.IntegerField(blank=True, null=True) cart_products = ArrayField( models.IntegerField(blank=True), default = list ) User.profile = property(lambda u:UserCart.objects.get_or_create(user=u)[0]) Below is my Form.py. I have created only basic form from django import forms from .models import UserCart from django.db import models from django.contrib.postgres.fields import ArrayField class UserCartForm (forms.ModelForm): class Meta: model= UserCart fields = ('user_product',) I have searched alot on internet but was unable to find the relevant answer.I want that whenever user clicks on Add to Cart button, that product_id gets stored in cart_products array.I read somewhere that ArrayFields behave as list in Django, so here is my views.py @login_required def user_cart(request): if request.method=='POST': form=UserCartForm(request.POST , instance=request.user.profile) if form.is_valid(): post = form.save(commit=False) post.cart_products.append(99) post.save() return HttpResponseRedirect('/user_login/loggedin') else: HttpResponse("Error") else: user=request.user profile=user.profile form= UserCartForm(instance=profile) args={} args.update(csrf(request)) args['form']=form return render_to_response('cartapi.html' ,args) Its giving me Error that AttributeError at /cart/ac/ 'NoneType' object has no attribute 'append' Request … -
How to execute ksh script present on my linux box from a button present on web browser page
I have a small task which i want to give a GUI look and feel. There are many shell scripts (.sh & .ksh) present in my Linux machine, I want to execute them from Webpage. Eg: "/user/###/##/diff.ksh" present on my linux box. i want to execute it from Browser. Webpage is made using Django framework. Please let me with the connection setting between Linux and Browser. -
Handling file field values in session
Would it be possible to upload a file and store it in a session and send that file using requests in python ? Can someone get back with a detailed answer