Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Ubuntu - Copy directory to new directory (incorrect directory path?)
I'm trying to write my first Python script, and it is not going well. I am trying to copy an entire local directory on my Ubuntu machine and place it and its contents in a different on my OS. I did some research and found distutils.dir_util.copy_tree(src,dst) should do just that. This is the contents of my backup_images.py file: import os import sys src = '/nodeGit/code/assets/images' dst = '/usr/images_backup' distutils.dir_util.copy_tree(src,dst) When I run it, I get error(s) on every line. When I run ./backup_images.py in terminal, this is the output: ./backup_images.py: line 1: src: command not found ./backup_images.py: line 2: dst: command not found ./backup_images.py: line 4: syntax error near unexpected token `src,dst' ./backup_images.py: line 4: `distutils.dir_util.copy_tree(src,dst)' If I run the same command with sudo (sudo ./backup_images.py), I get completely different errors: ./backup_images.py: 1: ./backup_images.py: src: not found ./backup_images.py: 2: ./backup_images.py: dst: not found ./backup_images.py: 4: ./backup_images.py: Syntax error: word unexpected (expecting ")") Based on the first couple errors of this, (src: not found,dst: not found), it seems Python isn't able to find the directories I assigned the src and dst files to. Is this correct? Because of the vague (and changing!) errors, I'm unsure of how to fix my code. -
Django url slugs with modeltranslation NoReverseMatch Error
I am using modeltranslation in my project, and my goal is to also translate the slugs of my urls. The slugs are successfully translated and I overwrote the save method of my Model to automatically populate the slug fields for all the languages in my project. class FrontendCategory(models.Model): name = models.CharField(_('Name'), max_length=255, db_index=True) slug = AutoSlugField(_('Slug'), populate_from='name', max_length=255, db_index=True) def save(self, *args, **kwargs): for lang_code, lang_verbose in settings.LANGUAGES: if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'name_%s' % lang_code): setattr(self, 'slug_%s' % lang_code, slugify(getattr(self, 'name_%s' % lang_code, u""))) def get_absolute_url(self): url = reverse( 'catalogue:frontend-category', kwargs={'frontend_category_slug': self.slug, 'pk': self.pk}) return url I checked and all the slugs are translated and saved correctly in the database. this is my url: url(r'^section/(P<frontend_category_slug>[\w-]+(/[\w-]+)*)_(?P<pk>\d+)/$', self.frontend_category_view.as_view(), name='frontend-category'), if I call the get_absolute_url method in a template the following error gets raised: Reverse for 'frontend-category' with arguments '()' and keyword arguments '{'pk': 5, 'frontend_category_slug':'test-slug'}' not found. 1 pattern(s) tried: ['de/catalogue/section/(P<frontend_category_slug>[\\w-]+(/[\\w-]+)*)_(?P<pk>\\d+)/$'] which seams weird because it is exactly what I seem to have defined in my url definition. All of this was working before I translated the slug with modeltranslation. Is there some kind of slug lookup performed by the url definition? Am I missing something else? -
ModelManager used in ForeignKey relations
I need an effective way of completely ignore the inactive users of my site, so I don't send them any notifications, emails, etc. I've tried using a custom Model Manager that only returns the active ones, like this: class ActiveAccountsManager(models.Manager): use_for_related_fields = True def get_queryset(self): return super(ActiveAccountsManager, self).get_queryset().filter(user__is_active=True) class Account(models.Model): class Meta: verbose_name = _('Account') verbose_name_plural = _('Accounts') objects = ActiveAccountsManager() all_accounts = models.Manager() # Enabling the obtention of all the users, instead of only the active ones user = models.OneToOneField(User) type = models.IntegerField(choices=ACCOUNT_TYPES, default=-1) And, while it works exactly as I want when I directly try to query Account objects, it doesn't when they are referenced through an object that has a ForeignKey relation with it. For example, if I had a Comment model like the following one: class Comment(models.Model): author = models.ForeignKey(Account) I'd like that, when I query for Comment objects, the ones whose author is a inactive user (i.e. an user that the default Manager of the Account model won't return) aren't returned either, instead of the current behavior that returns the comment but says that the account related to it does not exist Is there any way of achieving this without specifically defining a custom ModelManager … -
Is it better to use Django template tags or pass variables from python
I'm displaying a date on a Django template, and I have a python function that formats the date today for me and passes it to my template. # function [format example: Wednesday 01 February 10:00:00] def today(): date_now = datetime.now() day_number = date_now.strftime("%d") month_name = date_now.strftime("%B") day_name = date_now.strftime("%A") time = date_now.strftime("%X") date = "{} {} {} {}".format(day_name, day_number, month_name, time) return date # view def myview(request): the_date_today = today() context = { "the_date_today": the_date_today, } return render(request, "template.html", context) # template <h1>{{ the_date_today }}</h1> I've just found a way of doing this just with Django template tags. # view def myview(request): the_date_today = datetime.now() context = { "the_date_today": the_date_today, } return render(request, "template.html", context) # template <h1>{{ the_date_today|date:"l m F H:i" }}</h1> What's the better approach for this? It's a lot less code to just use template filters, but does this make anything slower? -
Creating dynamic tables in postgres using django
I need a small help. I am new to postgres and django. I am creating a project in django where there will n number of clients and their data is saved into the database on monthly basis. So my doubts is should i go with only a single table and save all the data inside it or do I have an option to create individual tables dynamically as the user approaches and then save the values into those table? -
How to svae choices value in django ?
I am donig with a poll system for my class. I use model-form and create-view to serve the poll form. I use choices in in the field but I just find out that create-view only save the last value of the checkboxes and I want to save all the selected choices as a list maybe. I've tried to change the form_valid() method, but I just find out that I need to iterate all the fields to check wheather there are multipule choices. It's not flexible. And I can't figure out other solutions... How can I meet this requirement? I am truly a newbie.. Thanks in advance. -
Delete an user from auth_user table in django
I have to delete an user from auth_user table. And I am trying to do using from django. I am getting ProgrammingError: (1146, u"Table 'oculus.auth_user_groups' doesn't exist") The code I am using is: from django.contrib.auth.models import User user = User.objects.filter(id=3306) user[0].delete() -
Initial data with formsets django
The following javascript code generates a draft url: function encodeQueryParameters(data) { return Object.keys(data).map(function(key) { return [key, data[key]].map(encodeURIComponent).join("="); }).join("&") } function extractFields(form, exclude) { var fields = {}; for (input of $$("input", form)) { if (input.name && exclude.indexOf(input.name) === -1) { if (input.value && input.type != 'checkbox') fields[input.name] = input.value; else if (input.checked) fields[input.name] = "on"; } } return fields } generateDraftButton = $("#generate-draft") generateDraftButton.onclick = (function() { var poll = extractFields($("#create"), ["csrfmiddlewaretoken"]); var draftParameters = encodeQueryParameters(poll); var draft; if(window.location.search) draft = window.location.href + "&" + draftParameters; else draft = window.location.href + "?" + draftParameters; window.location.replace(draft); }) It generates a URL like this: http://127.0.0.1:8000/create/?choice_set-TOTAL_FORMS=5&choice_set-INITIAL_FORMS=0&choice_set-MIN_NUM_FORMS=1&choice_set-MAX_NUM_FORMS=20&choice_set-0-choice_text=Yes.&choice_set-1-choice_text=No. In the view the parameters should be used for the initial data of the forms: draft = request.GET.dict() question_form = QuestionForm(initial=draft) Everything works fine with the normal form, but with the formset a error is raised: choice_form_set = ChoiceFormSet(initial=draft) I know that the initial keyword has a different meaning for formsets, but how to achieve the same thing like with normal forms? -
How to request.user.is_authenticated() in views.py? Django
I am trying to check if user is logged in from my views.py file. As depending if user is logged in it should return me different forms. But request.user.is_authenticated() or request.user.is_authenticated is not working, i always get True value. My view: def ContactsView(request): form_class = ContactForm_logged(request=request) form_class_nonlogged = ContactForm_nonlogged(request=request) # new logic! if request.method == 'POST': if request.user.is_authenticated(): form = ContactForm_logged(data=request.POST, request = request) else: form = ContactForm_nonlogged(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') subjects = form.cleaned_data['subjects'] subjects = dict(form.fields['subjects'].choices)[subjects] # Email the profile with the # contact information template = get_template('threeD/email/contact_template.txt') context = Context({ 'contact_name': contact_name, 'subjects': subjects, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) email = EmailMessage( "New message from " + contact_name, content, "Message - " + subjects + ' ', ['smart.3d.printing.facility@gmail.com'], headers={'Reply-To': contact_email} ) email.send() messages.success(request, "Thank you for your message.") return redirect('/index/contacts/') else: if request.user.is_authenticated(): form = ContactForm_logged(request=request) else: form = ContactForm_nonlogged() if request.user.is_authenticated(): return render(request, 'threeD/contacts.html', { 'form': form_class, }) else: return render(request, 'threeD/contacts.html', { 'form': form_class_nonlogged, }) And two of my forms: class ContactForm_logged(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) subjects = forms.ChoiceField(choices=emailsubjects) content = forms.CharField( required=True, widget=forms.Textarea ) def … -
Django Dynamic Model , cant able to access in admin
I'm using django 1.11 and I tried to create django dynamic models by referring this link https://code.djangoproject.com/wiki/DynamicModels , by executing each and every step it runs without any issue, but when I see the registered model in the django admin panel, The Model is visible under it corresponding app, but it not accessible, I don't know what I missed out there, def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None): """ Create specified model """ class Meta: # Using type('Meta', ...) gives a dictproxy error during model creation pass if app_label: # app_label must be set using the Meta inner class setattr(Meta, 'app_label', app_label) # Update Meta with any options that were provided if options is not None: for key, value in options.iteritems(): setattr(Meta, key, value) # Set up a dictionary to simulate declarations within a class attrs = {'__module__': module, 'Meta': Meta} # Add in any fields that were provided if fields: attrs.update(fields) # Create the class, which automatically triggers ModelBase processing model = type(name, (models.Model,), attrs) # Create an Admin class if admin options were provided if admin_opts is not None: class Admin(admin.ModelAdmin): pass for key, value in admin_opts: setattr(Admin, key, value) admin.site.register(model, Admin) return model Please refer this image … -
Int Object Not Iterable Error After Implementing Custom Template Proccessor
I wrote a custom template processor so that I can get the result on any page I want with a variable. In the processor file, I want to get the price of Bitcoin from an api. See below. context_processors import requests def BitLive(request): d_price=requests.get('http://api.coindesk.com/v1/bpi/currentprice.json') v_data=d_price.json() sp= v_data["bpi"]["USD"]["rate_float"] finalprice=int(round(sp)) return {'finalprice':finalprice} I added it to my base_settings.py 'manapp.context_processors.BitLive', Template {{finalprice}} I got this error when I load any page: TypeError: Int Object Not Iterable When I comment out the context processor in my settings file, the site will load fine. What am I missing? because I'm not iterating over any object. -
Add db_index = True to a Django model which already has a lot of data
I want to add indexing to an already existing Django model field by adding db_index = True. The corresponding table already has a lot of data in the database. Will adding db_index = True to the field automatically index the values after migrating with the new changes? -
How to update an ImageField in Django model with a new Image
In my project a user can upload an image and once it is saved I can run a post_save signal to modify the image using Pillow. And after modifying the image I need to replace the existing image with the new image.Now the issue is if I run the save method in the post_save signal it will lead to maximum recursion error.So instead of this I am thinking of using update method but it throws an error regarding the characters in the file. Below is the code: def menuImageLocation(instance,filename): return "%s/%s"%(instance,filename) class restaurantMenuImage(models.Model): restaurant = models.ForeignKey(restaurantCreateUpdate) title = models.CharField(max_length=100,null=True,blank=True) menuImage = models.ImageField(upload_to=menuImageLocation,null=True,blank=True,verbose_name="Menu Image") def __unicode__(self): return str(self.restaurant) @receiver(post_save,sender=restaurantMenuImage) def modifyMenuImage(sender,instance,**kwargs): getRestaurant = restaurantCreateUpdate.objects.get(restaurantName=instance.restaurant) image_path = instance.menuImage.path filename = os.path.basename(image_path) image_hold = Image.open(image_path) image = image_hold.resize((300,300),Image.ANTIALIAS) temp_loc = "%s/%s/%s/tmp"%(settings.MEDIA_ROOT,"menu",getRestaurant.uniqueID) if not os.path.exists(temp_loc): os.makedirs(temp_loc) temp_file_path = os.path.join(temp_loc,filename) if os.path.exists(temp_file_path): temp_path = os.path.join(temp_loc,"%s" %(random.random())) os.makedirs(temp_path) temp_file_path = os.path.join(temp_path,filename) temp_image = open(temp_file_path,"w") image.save(temp_image,quality=80) temp_data = open(temp_file_path,"r") image_file = File(temp_data) instance.menuImage = image_file instance.menuImage.save(filename, image_file) So if I run the last line of the code, this will result into maximum recursion error, and instead of using save method I am trying to use update method the file path but for that I am getting the … -
LDAP auth in private network with HTTP calls
I have a frontend-backend setup that runs in a private network but can be accessed from outside. The user authentication will be done by an LDAP server that runs in the same private network, using the username-password provided by the user in the frontend.Can I pass these parameters with HTTP calls to the server? It this a safe policy for the application? Frontend is Angular 1.6 and backend is Django 1.8 with Django rest framework 3.3 Thank you -
Create a Django patch which update several instances
I'm asking a question about my Django application updates. I'm working on my Django Development server and I would like to know How I could create a patch which will update my different Django Project installed on different servers. For example : In my Dev' server, I add a new Query in my script. Then I would like to add this new Query to my all virtual instances by updating my script and not just copy/past modifications. It could work for one query, but if I have 200 rows, copy/paste will be too long. I launch a patch which will make all updates without manually copy/paste rows. How it's possible to do that ? Thank you so much -
Django simple pagination in detail view between items
I want to add simple back/next pagination in my item detail view. How can I do that ? I have something like that in my template: {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="#back">Back</a> {% endif %} {% if page_obj.has_next %} <a href="#next">Next: {{ item.title }}</a> {% endif %} </span> </div> {% endif %} The main thing is that I want to do this in ItemDetailView, not in ItemListView, because in list view I have all items, and I just want to go between items in detail view. Thanks a lot for help. -
How to do a JOIN over multiple Django models
The following models are given: class Copy(CommonLibraryBaseModel): lecture = models.ForeignKey('Lecture', ...) signature = models.CharField(max_length=100, ...) class Lecture(CommonLibraryBaseModel): category = models.ForeignKey('LectureCategory', ...) class LectureCategory(CommonLibraryBaseModel): parent = models.ForeignKey('self', ...) display_name = models.CharField(max_length=100, ...) I basically want to do the following query: SELECT signature, display_name FROM lecturecategory as lc, lecture as l, copy as c WHERE lc.id = l.category_id AND c.lecture_id = l.id AND lc.parent_id=2; How would I do that in Django? I could not figure out how to combine the different models. Thanks for the help! -
Django with Python notebooks
I am using Ibm Notebooks with Phyton 2.7. I want to implement a Django webserver in the data science experience platform. How can i do this? Where do i get the URL of the Webserver? -
Tricky NOT NULL error django utils Integrity error
Tricky NULL Constraint error. Previously working when i just delete py and pyc files from migrations folder. now when i make migrations it is no longer working. File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: Htweets2_htweets2.tweet_location Here is my models.py class Htweets2(models.Model): tweet_id = models.BigIntegerField(default=None, null=True, blank=True) tweet_timestamp = models.CharField(max_length=200) tweet_screenname = models.CharField(max_length=200) tweet_favour_count = models.CharField(default=None, max_length=200) tweet_recount = models.BigIntegerField(default=None) tweet_location = models.CharField(default=None, blank=True, null=True, max_length=200) tweet_text = models.TextField(default=None) tweet_media_entities = models.URLField(default=None) I am certain that simply deleting pyc and py files from migrations folder was working, but after i have done it several times, it does not longer make me do makemigrations. -
Filtering latest entry and prefetch related in Django
I have been trying to optimize my queries in Django to reduce my postgres database hits, so here are the, simplified for this question, concerned models Model : class SentEmail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) sent_date = models.DateTimeField(default=timezone.now) sender = models.EmailField() class AppUser(models.Model): user= models.OneToOneField(User, primary_key=True) is_active= models.BooleanField(default= False) expiration_date = models.DateTimeField(default=make_default_expiration_date) #note : 90 days after the creation And User is the standard Django auth user with the username, password and other stuff. What I want to do, is retrieving the AppUser's various data for active users and the last SentEmail that concerns them. For now, I have this. View : active_users = Language_new.objects.filter(expiration_date__gt=timezone.now(), is_active=True) And if I want to include the last sent email, I'd do something like this active_users = Language_new.objects.filter(expiration_date__gt=timezone.now(), is_active=True).prefetch_related( Prefetch( "sentemail", queryset=SentEmail.objects.filter().latest('sent_date'), to_attr="last_sentemail" )) Questions : Is Django smart enough to make the relation here : queryset=SentEmail.objects.filter().latest('sent_date')? If not, how do I reference each user in the filter()? Also, as there might not be a "latest" sentemail for every AppUser, how do I handle the DoesNotExist in this kind of query? Code execution : Executing this code gets me an AttributeError AttributeError: 'SentEmail' object has no attribute '_iterable_class' Pointing on this line : to_attr="last_sentemail". I … -
How to pass the values entered by the user in template to the function as argument in django?
I want to take the input value given by the user i.e ratings in this case and want to call the specified function but that function doesnot return anything .So i want to stay in the same page after I click submit .Image to display the page where input is taken. This is code to the details page . <h4>Hai this is the details page for the movies {{ plot }}</h4> <form action="#" method="get"> {% csrf_token %} Ratings: <input type="number" name="quantity" step="0.5" min="1" max="5"><br> <input type="submit" value="Click"> </form> This is the function which i need to call by passing the value given by user and this function does not return anything instead it stores the value to the csv file. def rate_movie(user_id , movie_id , rating_value): pc = ratings.movie_id[ratings.user_id == user_id] # gets all the movies rated by this user ad = pc.tolist() #converts to list s = 0 # This loop finds the exact location in the table to store the rating. for p in ad: if movie_id < p: s = ad.index(p) break #Splits the table at this point. seperate = list(pc[pc == s].index)[0] #The row which will be added to the table. bla = [user_id,movie_id,rating_value,665345] #Splitting the … -
Wordpress User Password Data as Plaintext
I have around 900 users in my wordpress, i am exporting these user data to my new platform that will be using Django. My question is, how can i export these user's password as plaintext? if i cannot do it, i wanted to store it in "old_password" field in my new database, but i want to know how to "match" text with the old_password? because my plan is that when the user login, i will try to find the user with the same email and the hashed password, but i don't know what type of hashing function Wordpress used and the equivalent of that function in Python Django. -
Celery does not work in AWS ECS
I deployed my django project to the AWS ECS service using the docker. And to use celery I set rabbitmq as a separate ec2 server (two ec2 with brocker and result backend). The problem is that the celery worker works locally but not on AWS. When I typing docker run -rm -it -p 8080: 80 proj command, the celery worker to run and get the response(Email sent). So if you want to make a worker, I need to create a worker with celery -A mysite worker -l INFO in my local django project. Despite setting the supervisor to run worker. Below is my code. Dockerfile FROM ubuntu:16.04 # A layer is created for each command ex)RUN, ENV, COPY, etc... RUN apt-get -y update RUN apt-get -y install python3 python3-pip RUN apt-get -y install nginx RUN apt-get -y install python-dev libpq-dev RUN apt-get -y install supervisor WORKDIR /srv RUN mkdir app COPY . /srv/app WORKDIR /srv/app RUN pip3 install -r requirements.txt RUN pip3 install uwsgi ENV DEBUG="False" \ STATIC="s3" \ REGION="Tokyo" COPY .conf/uwsgi-app.ini /etc/uwsgi/sites/app.ini COPY .conf/nginx.conf /etc/nginx/nginx.conf COPY .conf/nginx-app.conf /etc/nginx/sites-available/app.conf COPY .conf/supervisor-app.conf /etc/supervisor/conf.d/ COPY .conf/docker-entrypoint.sh / RUN ln -s /etc/nginx/sites-available/app.conf /etc/nginx/sites-enabled/app.conf EXPOSE 80 CMD supervisord -n ENTRYPOINT ["/docker-entrypoint.sh"] supervior-app.conf [program:uwsgi] command … -
How to pass a custom authentication form from within a view in django?
I'm trying to pass a custom authentication form I created to the auth.views.login. All the tutorials I found do it through url() in urls.py, and with a url for the login view (e.g. url(r'^login/$', auth.views.login,{'authentication_form':MyAuthenticationForm}) ). But I want the url to be the same as the index url, if the user is authenticated then show the index otherwise show the login form with my custom authentication form. Here's my views.py : from django.shortcuts import render from django.contrib.auth import views as auth_views def cp(request): if request.user.is_authenticated(): return render(request, 'index.html') # How to pass my custom authentication form ? return auth_views.login(request) This is working, but how to tell django of my custom authentication form ? -
Django - Is overriding TemplateView.get with different signature a bad practice?
I wrote a Django application with a JobView inherited from TemplateView. The get method needs an additional argument (job_id) which is in the URL. Basically, my urls.py looks like this: # urls.py from django.conf import url from .views import JobView urlpatterns = [ url(r'^job/(?P<job_id>[0-9]+)$', JobView.as_view()) The views.py contains the definition of JobView: # views.py from django.views.generic import TemplateView from django.http import HttpResponse class JobView(TemplateView): def get(self, request, job_id): # Some stuff return HttpResponse("something") When checking this code with pylint, I get this error: [arguments-differ] Arguments number differs from overriden 'get' method. To fit the TemplateView.get method, the definition of JobView.get should be: class JobView(TemplateView): def get(self, request): # Some stuff Is overriding with an other signature a bad practice? If yes, how am I supposed to implement such a thing?