Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django_filters have initial value only when ?page=1 is present
I have the a view, AccoutList, which is trying to render a django_table2 table. The view's source code: class AccountList(SingleTableMixin, FilterView): model = Account table_class = AccountTable template_name = 'accounts/account_list.html' context_table_name = 'object_list' ordering = ['vps'] filterset_class = AccountFilter This view is currently using this filterset (from django_filters): import django_filters from accounts.models import Account class AccountFilter(django_filters.FilterSet): class Meta: model = Account fields = ['is_suspended', 'is_abandoned'] is_suspended = django_filters.BooleanFilter(name='is_suspended', initial='False') is_abandoned = django_filters.BooleanFilter(name='is_abandoned', initial='False') def __init__(self, data=None, *args, **kwargs): # if filterset is bound, use initial values as defaults if data is not None: # get a mutable copy of the QueryDict data = data.copy() for name, f in self.base_filters.items(): initial = f.extra.get('initial') # filter param is either missing or empty, use initial as default if not data.get(name) and initial: data[name] = initial super().__init__(data, *args, **kwargs) Using this template: {% if filter %} <form action="" method="get" class="form form-inline"> {{ filter.form.as_p }} <input type="submit" /> </form> {% endif %} {% render_table object_list %} {% endblock %} This is my from my urls.py path('', login_required(AccountList.as_view())), When I visit my page, 127.0.0.1:8000, I see that the filters are not set: But then if i do 127.0.0.1:8000?page=1, I see the filters are initialized properly: What … -
Django-Orgnaizations equivalent for nodejs?
I want to know if there's an equivalent of django-organizations for nodejs frameworks like hapi or restify or express. -
How to pass 2 variables using json dumps to an ajax function?
I want to pass two variable: scenario_name and scenario_id from my view to my ajax function in the html code. So basically in the database, each Organization can have multiple scenarios. The organization and scenario models have 2 fields each: an id field and a name field. And my other doubt is, once I pass it to ajax, how do I access the variables passed? my views.py org_id = request.GET.get('org_id') organization = Organization.objects.get(pk=int(org_id)) scenarios_ids = organization.scenario_set.values_list('scenario_id', flat=True) scenarios_names = organization.scenario_set.values_list('scenario_name', flat=True) scenarioIDS = json.dumps(list(scenarios_ids)) scenarioNames = json.dumps(list(scenarios_names)) return scenarioIDS, scenarioNames my ajax function var orgID = $(this).val(); var scenario_id = '{{ scenarioIDS }}' var scenario_name = '{{ scenarioNames }}' $.ajax({ type: "GET", url: "{% url 'Get_Scenario' %}", data: { org_id: orgID}, success: function () { var udata = ""; for (var i = 0; i < scenario_id.length; i++) { udata = udata + "<option value='"+ scenario_id[i] + "'>" + scenario_name[i] + "</option>" $("#txtScenario").append(udata); } }, }); The url Get_Scenario links me to my view having the function get_scenario. Any help will be greatly appreciated. -
Error in configuring celery with django
Full Traceback. Please help Traceback (most recent call last): File "/Users/ashokk/venv/bin/celery", line 11, in <module> sys.exit(main()) File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/__main__.py", line 16, in main _main() File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/bin/base.py", line 273, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/bin/base.py", line 479, in setup_app_from_commandline self.app = self.find_app(app) File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/bin/base.py", line 501, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/app/utils.py", line 359, in find_app sym = symbol_by_name(app, imp=imp) File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/bin/base.py", line 504, in symbol_by_name return imports.symbol_by_name(name, imp=imp) File "/Users/ashokk/venv/lib/python3.6/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/Users/ashokk/venv/lib/python3.6/site-packages/celery/utils/imports.py", line 104, in import_from_cwd return imp(module, package=package) File "/Users/ashokk/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/ashokk/venv/social_automation/automation/__init__.py", line 5, in <module> from .celery import app as celery_app File "/Users/ashokk/venv/social_automation/automation/celery.py", line 5, in <module> from .views import calling_actions File "/Users/ashokk/venv/social_automation/automation/views.py", line 4, in <module> from .forms import WelcomePage, LoginForm File "/Users/ashokk/venv/social_automation/automation/forms.py", line 2, in <module> from .models import Followers File … -
Smilies in form are saved as ???? in database
In my Django app, when users send form containing smilies like 😎 the smily is saved ass ???? def send_letter(request): args = {} if request.method == 'POST': form = SendDastanForm(request.POST) if form.is_valid(): d = form.save(commit = False) try: author = get_user(request) except: author = 'Guest' d.title = form.cleaned_data['title'] d.body = form.cleaned_data['body'] d.published = False d.save() The model which is used to generates form is: class SendLetter(models.Model): author = models.ForeignKey(User, blank=True, null=True) title = models.CharField(max_length=100, blank=False) body = models.TextField(blank=False) created = models.DateTimeField(default=datetime.datetime.now) published = models.BooleanField(default= False, blank=True) The site reviews the receive letters so they are not published automatically. I'm wondering how can I preserve the smiles while still keep the form safe from SQL injection and so on? -
How to know which field is changed in Update form - django
Before uploading images I need to compress them and for that I am using PIL in forms but the problem is I don't know which image field is changed (I have two image fields), have a look at form class class UpdateProfileForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UserProfileModel fields = ('profile_image','cover_image','about_self') widgets = { 'file': forms.FileInput(attrs={ 'accept': 'image/*' # this is not an actual validation! don't rely on that! }) } def save(self): update_form = super(UpdateProfileForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') print(help(self.cleaned_data)) image = Image.open(update_form.cover_image) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((985, 370), Image.ANTIALIAS) resized_image.save(update_form.cover_image.path) return update_form at this time I am compressing cover_image only but if only profile image is uploaded then cover_image also get change (changes applied in current cover_image), What I need is a method that returns if a field is changed in form class. -
CMD path not fully shown after adminname@187.35.123.345 command line
I want to see full path in CMD window, but after I enter my server admin account and CD couple times, command prompt only shown as adminname@djangoProjectname: $ it supposes to be adminname@DjangoProjectname:~/portfolio-project$ why wont the ~/portfolio-project part shown??? it just got replaced with all spaces...its difficult to see which sub-dir I am at. -
Django: Stripe & POST request
I am currently trying to implement Stripe Connect in my Django project. Stripe documentations states for Standard accounts: Assuming no error occurred, the last step is to use the provided code to make a POST request to our access_token_url endpoint to fetch the user’s Stripe credentials: curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_Dur3X2cOCwyjlf9Nr7OCf3qO \ -d code="{AUTHORIZATION_CODE}" \ -d grant_type=authorization_code I now wonder how to send a POST request with Django without form & user action (clicking the submit button)? -
Can't create new entry by admin
I have model called Company. The model pretty simple as you can see. In project I use postgres database. I have strange problem when try to create new entry by Django admin. First I add 5 entry in database by sql request from terminal. They have id from 1 to 5. In database client I see them. Now when I try to add new company by admin it raise next error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "url_pkey" DETAIL: Key (id)=(5) already exists. Can someone say how to fix this problem? models.py: class Company(models.Model): name = models.CharField() admin.py: class CompanyAdmin(admin.ModelAdmin): search_fields = ('name',) admin.site.register(Company, CompanyAdmin) -
"Relation Already Exists" in Empty Database
My Django migrations on an existing Postgres database are giving me a lot of trouble; I am trying to get to the bottom of why Postgres keeps telling me: psycopg2.ProgrammingError: relation "tablename" already exists So I decided to spin up an empty database and try a fresh migration. On a completely clean Postgres instance, I am still getting that a table already exists, when I can clearly see that there are no tables in the database. What can be causing this issue? -
Django : "'utf-8' codec can't decode byte 0xe9 in position 19983: invalid continuation byte" when loading a template
I'm trying create a web app using django with python and the jupyter notebook environment. I am following the tutorial on djangoproject website : https://docs.djangoproject.com/en/2.0/intro/tutorial03/ When I try to load a template in the views file of my project, I get the following error : 'utf-8' codec can't decode byte 0xe9 in position 19983: invalid continuation byte. Here is the part of the code where I call the file : def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) After some research, I found out that a file : mysite/polls/templates/polls/index_fichiers/themedata.thmx gives me the following message when I try to open it in jupyter : Error ! mysite/polls/templates/polls/index_fichiers/themedata.thmx is not UTF-8 encoded. Saving disabled. See Console for more details. In my console : 400 GET /api/contents/polls/templates/polls/index_fichiers/themedata.thmx?type=file&format=text&_=1530244665665 (::1) 4.00ms referer=http://localhost:8888/edit/polls/templates/polls/index_fichiers/themedata.thmx I tried to convert this file in UTF-8 by opening it in a text document and saving it with a UTF-8 encoding, but it still have the same message. I tried to add an argument : encoding='UTF-8' to the get_template fonction, but "encoding" is not a keyword argument for it. Does someone know what I should try ? Maybe change the encoding parameters of … -
DJango content iteration from file
What i want to do is have different stories stored in my directory/server. Have python/django read the files and store the text in the appropriate variables. Iterate over these files in the django template. I tried using setInterval and Timeout but it jumps straight to the last iteration without iterating through the content and pausing after each iteration. Views.py def Story(request): titles =[] path = 'StoryBox/static/StoryBox/files' for i in os.listdir(path): if i.startswith('story'): storystring = "" file = '/'.join([path, i]) f = open(file) for lines in f: if lines.startswith('<title>'): x = lines.split('>') x = x[1] x= x.replace('\n', '') titles.append(x) return (render (request,'StoryBox/homepage.html '{'titles':titles'})) homepage.html function StopTimer(z){ document.getElementById("title") .innerHTML = z; } function iterate(){ {% for z in titles %} setInterval(StopTimer({{z}}") ,2000); {% endfor%} } P.S code format tool bar didnt work on phone , thats why the code isnt formatted properly in my question. sorry -
Django. count number of li elements
So, I am getting values from our CMS which is throwing me an ordered list output. e.g. <ol> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ol> Is there a way to manipulate or add an element in the li before being displayed using Django. Like below. <ol> <li><div>inserted element</div>item 1</li> <li><div>inserted element</div>item 2</li> <li><div>inserted element</div>item 3</li> </ol> Thanks in advance -
Applying a Django FilterSet to an Annotated QuerySet?
I'm trying to apply a filter to an annotated queryset, like is done here: https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#filtering-on-annotations Similar to the snippet below, I'd like to make that highly_rated piece a FilterSet that picks up the request parameters highly_rated = Count('books', filter=Q(books__rating__gte=7)) Author.objects.annotate(num_books=Count('books'), highly_rated_books=highly_rated) I'd like to make that highly_rated piece a FilterSet that picks up the request queries. Something like: class MainFilter(FilterSet): class Meta: model = Author fields = { author: ['in', 'exact'], genre: ['in', 'exact'] } class AnnotatedFilter(FilterSet): class Meta: fields = { 'books__rating': ['gt', 'lt' ], } class MyView(ListApiView): filter_class = AuthorFilter def get_queryset(self): annotated_filter = AnnotatedFilter(request) # how do I set up another filter based on the request? Author.objects.annotate(num_books=Count('books'), FilterSet=annotated_filter) # how do I apply it to an annotated queryset? All so I can query something like: api/authors/?genre=Fantasy&books__rating__gt=5 Where one of the parameters executes against all the records and other params execute against the annotated part. Any help is greatly appreciated. Thanks! -
Make view disable after some boolean value in django rest
models.py class One(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) one = models.CharField(max_length=20) ses = models.IntegerField() occupied = models.BooleanField(default=False) I have occupied boolean field which is False by default. I want to make all the views disable and only read only after occupied is made True serializers.py class OneSerializer(serializers.ModelSerializer): class Meta: model = One field = '__all__' read_only_fields = ('user',) views.py class OneView(APIView): @staticmethod def get(request): user = request.user apt = One.objects.filter(user=user) if type(apt)==Response: return apt return Response(OneSerializer(apt).data) @staticmethod def post(request): serializer = OneSerializer(data=request.data, context = {'request':request}) if serializer.is_valid(): user = request.user serializer.save(user=user) return Response(OneSerializer(serializer.instance).data, status=201) return Response(serializer.errors, statusl=400) How do I make such feature making occupied True, make the respective view only readonly to owner user? -
Postgres Django Migration Persistently Throws "Relation Already Exists"
This is the third time I have received this exception after running a database migration: psycopg2.ProgrammingError: relation "TABLENAME" already exists I have gotten around this by removing the table and re-creating it (and all of the columns the schema expects), but Id like to find the core issue here. When I add new tables to my schema, I run the fake migration first: python manage.py migrate --fake-initial But this one table keeps on giving me issues. What could the problem be? -
trying to see if a variable is included in a list in django
I am trying to find if a selected country is in a list of tuples by using the following command in my view: if second_tier.profile.country in COUNTRIES: if I print second_tier.profile.country I have CA and when I print COUNTRIES I get: (('GB', 'United Kingdom'), ('AU', 'Australia'), ('AT', 'Austria'), ('BE', 'Belgium'), ('CA', 'Canada'), ('DK', 'Denmark'), ('FI', 'Finland'), ('FR', 'France'), ('DE', 'Germany'), ('HK', 'Hong Kong'), ('IE', 'Ireland'), ('IT', 'Italy'), ('LU', 'Luxembourg'), ('NL', 'Netherlands'), ('NZ', 'New Zealand'), ('NO', 'Norway'), ('PT', 'Portugal'), ('SG', 'Singapore'), ('ES', 'Spain'), ('SE', 'Sweden'), ('CH', 'Switzerland'), ('US', 'United States')) So the if statement is supposed to return True, however it comes back as False. -
Adding comment system to django app with class-based views
I am trying to add a comment system with the threadedcomments package. The code to which I am trying to add the package is below, where it says "My Code". I have read the threadedcomments documentation and Django comment documentation, but I'm having difficulty figuring out exactly how to implement it. The package asks to add this into the template to fetch the form (after adding the app and etc., which I have done). There are others like this on the documentation to add to the template. What should each part be for my code, which isn't very usual? Fetching the comment form: {% get_comment_form for [object] as [varname] %} {% get_comment_form for [object] as [varname] with [parent_id] %} {% get_comment_form for [app].[model] [id] as [varname] %} {% get_comment_form for [app].[model] [id] as [varname] with [parent_id] %} Also implementing the comment url, as instructed by the package, might not work for my code; what should I do? The product is like this: There's a book list. On each book item is a form. This form saves a post and makes it related to this particular book. When you click a book item, you see a list of posts, all related … -
In Django, how to create a reusable receiver function?
I have a model SessionType with a field title of which I'd like to create a slugified version, smattering_slug. Currently, this is implemented with the following receiver function: from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify @receiver(pre_save, sender=SessionType) def create_smattering_slug(sender, instance, **kwargs): if not instance.smattering_slug: instance.smattering_slug = slugify(instance.title) I also have other models, however, for which I'd like to do the same thing, but the name of the field to be slugified and the slug field is different. To generalize this, I considered doing something like this: def create_slug_field(sender, instance, **kwargs): field = kwargs.pop('field') slug_field = kwargs.pop('slug_field') if not getattr(instance, slug_field): setattr(instance, slug_field, slugify(field)) from functools import partial pre_save.connect(partial(create_slug_field, field='title', slug_field='smattering_slug')) However, in this way, I'm not passing in sender=SessionType as in the original example. (It is not clear to me from https://docs.djangoproject.com/en/2.0/topics/signals/#connecting-to-signals-sent-by-specific-senders how to do this while using .connect()). Also, I would like to make field and slug_field required arguments, but I don't quite see how this would work because the handlers seem to expect a fixed set of arguments described in https://docs.djangoproject.com/en/2.0/ref/signals/#pre-save. How might I implement this receiver in an 'extensible' way? -
invalid literal for int() with base 10: '91136891f1bf47c1bfba5094b810554b'
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Preferences(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) ebay_token = models.TextField(max_length=1024) app_id = models.CharField(max_length=128, default='asdf', editable=False) dev_id = models.CharField(max_length=128, default='asdf', editable=False) cert_id = models.CharField(max_length=128, default='asdf', editable=False) markup = models.FloatField(max_length=3) seller_location = models.CharField(max_length=256) #the ebay site number might need editing ebay_site_number = models.IntegerField() quantity = models.IntegerField() #this will def need fixing here fullfillment_policy = models.CharField(max_length=64) payment_policy = models.CharField(max_length=64) return_policy = models.CharField(max_length=64) def __str__(self): return "{}'s Preferences".format(self.customer.username) class listed_products(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) product_url = models.CharField(max_length=512) price = models.FloatField(max_length=3) mpn = models.CharField(max_length=30) upc = models.CharField(max_length=13) product_title = models.CharField(max_length=128) brand = models.CharField(max_length=64) ebay_link = models.CharField(max_length=256) ebay_id = models.CharField(max_length=64) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return "{}'s {}".format(self.customer.username, self.product_title) class Meta: ordering = ['date_added'] I keep getting the error message 'invalid literal for int() with base 10: '91136891f1bf47c1bfba5094b810554b' when I try to go the admin page and click on the models I registered. Do you have any idea what could be causing this? When I originally read it, I believed that the integer fields needed a length, but django told me that it would be removed automatically so I removed it. Are the float fields causing this? If you have any … -
Bootstrap: convert date format- mm/dd/yyyy
I am writing a Django web application and using Material Kit(Bootstrap) for front end. I want to display the date on the html in the format of mm/dd/yyyy. e.g. 06/27/2018 The date passed from python is already in the format of mm/dd/yyyy. I have no idea why it's display in the .html in the format of June,28 2018 I think it's because of Material Kit, but I don't have idea any how to convert or override the function. Please help! -
Custom register form not working as expected
I created a register form which has worked great, allowing me to create users and sign in with them. Recently, I have been trying to implement email verification before signing up a user to the system. I've been using SendGrid to send the emails, and a token to activate the user. The form hasn't been saving, redirecting the user to the activation page, or even sending the email. I get the error "can't set attribute" because "user.is_active = False" for my parent_sign_up view. I can't figure out what's wrong. Any help would be appreciated! views.py def parent_sign_up(request): if request.method == 'POST': form = ParentSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string('acc_active_email.html', { 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() else: form = ParentSignUpForm() form = ParentSignUpForm() context = {'form' : form} return render(request, 'accounts/parent_sign_up.html', context) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('home') return HttpResponse('Thank you for your email confirmation. Now you … -
How to merge multiple tables into a single table mysql
What I'm trying to do is a tool inventory table, I currently have a table for each tool type (Drill_bits, plyers, end_mills, ..etc ), and a person's table. I want to make a middle table that records all transactions i.e(when a tool is borrowed to a person). I assume that would look like this: +--------------------+ |transaction | +--------------------+ |person_id FK | |tools_id Fk | +--------------------+ I don't know how to accomplish unifying all different tool's tables into one single tools table. Is this even a good idea? Any suggestions would be tremendously appreciated. -
Como usar oracle no Django 2.0?
Estou com dificuldade de usar no oracle no Django 2.0, sempre usei o oracle 11g ex, porem o Django 2.0 so aceitar versao >= 12.1 do oracle, instalei o oracle 12c com muita dificuldade mas consegui porem não acho muitos tutoriais explicando como configurar o oracle com o Django 2.0, ja que o mesmo é novo, alem de eu não saber configurar o settings.py. se alguem tiver um tutorial de como configurar um vituralenv com o oracle e o django 2.0 ficarei muito agradecido. -
heroku does not reflect code changes after successful build python angular
I have been having a problem with heroku not reflecting changes in my code after a successful build. I am using angular on the front end so when I run my ng build take the files in the dist folder put them in my front end static folder (yes my collect static is working correctly) do git add . git commit -m "nifty commit message" git push origin master && git push heroku master I have tried using heroku reset running heroku run python manage.py makemigrations and heroku run python manage.py migrate to see if it was a database issue. Nothing of the sort. I have tried fixes from the following with nothing no result. Heroku doesn't see my changes after git push https://github.com/mars/create-react-app-buildpack/issues/66 and successfully build my app and push i do not see my changes when I got to my heroku website. I did two tests. one I created a test.html file and added it to my front end static files just to see if it would show up in heroku in the bash and I changed the index.html <title> tag from "Suits + Tables" to "Suits and Tables and Tables" I saw the test.html file but the …