Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django oscar product description
I am exploring django oscar ecommerce and I wanted to find out if there was a way to insert images into product description. Under dashboard, it doesn't allow me to insert images or edit it in html mode. Many Thanks! enter image description here -
How to integrate Django authentication with Jinja2 templates properly?
I am trying to use authentication and authorisation system provided by Django and as I can see the default built-in views for login/logout expect Django templates, hence I cannot use my Jinja2 base.html file to extend them as I have already integrated Jinja2 engine. I was able to solve this problem by replicating 'base.html' and changing syntax to Django template, but this approach forces me to rely on two same files in different templating languages. However, now I have other issue, I cannot access the user object in Jinja2 template context, even though I can do that in Django template. By saying 'I cannot access': File "/home/dir/workspace/project/venv/local/lib/python2.7/site-packages/jinja2/environment.py", line 430, in getattr return getattr(obj, attribute) UndefinedError: 'user' is undefined My Jinja2 template: {% if user.is_authenticated %} <li>User: {{ user.get_username }}</li> <li><a href="{% url 'logout'%}?next={{request.path}}">Logout</a></li> {% else %} <li><a href="{% url 'login'%}?next={{request.path}}">Login</a></li> {% endif %} My question is, how can I go around this problem? Should I just switch back Django templates, because this becomes more and more messy. -
Django ORM get jobs with top 3 scores for each model_used
Models.py: class ScoringModel(models.Model): title = models.CharField(max_length=64) class PredictedScore(models.Model): job = models.ForeignKey('Job') candidate = models.ForeignKey('Candidate') model_used = models.ForeignKey('ScoringModel') score = models.FloatField() created_at = models.DateField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) serializers.py: class MatchingJobsSerializer(serializers.ModelSerializer): job_title = serializers.CharField(source='job.title', read_only=True) class Meta: model = PredictedScore fields = ('job', 'job_title', 'score', 'model_used', 'candidate') I want to fetch the jobs with top 3 scores for a given candidate for each model used. So, it should return the top 3 matching jobs with each ML model for the given candidate. I read about annotations in django ORM but couldn't get much. I want to use DRF serializers for this operations. This is a read only operation. I am using Postgres as database. What should be the Django ORM query to perform this operation? -
Django static files : use only /static/ directory
I have a Django live version in production and I develop in local with Django manager.py. I'm not able to find the correct configuration settings for my static files. All my static files are on a /static/ on the root of the project, because all the sub-apps use the same stylesheets and so on. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' On my live version : it works because I've got an NGINX rule that allow access to /static/ directly. But when I want to work on local, the static files are 404, with Debug True and False. I don't see the interest for my needings of the staticfiles directory (but I can have a wrong mind here). Is it possible to have all the static files in subdirectories in /static/ (css, img, js, etc.) and to set a workable settings on both local and live production without switching something in settings.py for deployment ? Thanks for your help :) -
Save data in database for a particular column for a particlur value in another coulumn in django
html <form method="post"> {% csrf_token%} <label for="alert_selected">Your name: </label> <input id="alert_selected" type="text" name="alert_selected" value="{{form.as_p }}"> <input type="submit" value="OK"> </form> View.py def do_post(request): try: person=PersonForm(request.POST) print "Inside post" print person,"gghhgghgh" if person.is_valid(): print "Hello",person person.save() #print useralertname #alertnamedictpost = dict.fromkeys(useralertname) return render(request, 'promeditor.html', {'alertnamefile':get_displayalerts()}) except Exception as e: error_string = str(e) print error_string return render_to_response('error.html') modals.py class Person(models.Model): first_name = models.CharField(max_length=30) alert_selected=models.CharField(max_length=3000,null=True) forms.py class PersonForm(ModelForm): class Meta: model=Person fields=['first_name','alert_selected'] //My requirment is that I need to save data for a particular username the details.Like how in views I will point out for this particluar username i have the following details. Now it is throwing an error<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" required id="id_first_name" maxlength="30" /></td></tr> -
django allauth signup callback?
I am working on a Django app where after a user registers/signs up, I create a an instance of 'x' on their homepage - like a new file or something. How can I achieve this? For example, I have a function create_instance() which I need to be executed like this: def after_signup_callback(): create_instance(); Should I inherit from the SignupView defined in allauth and add a method of my own? or Should I wait for the user to login and when the user arrives at the homepage (where the created instance is shown), check if its the user's first login, and then call the create_instance() method? -
Saving to related_name name django field?
I have two model classes for shop items so far. class Item(models.Model): title = models.CharField(max_length=250) price = models.DecimalField(max_digits=8, decimal_places=2) url = models.URLField(max_length=250) image = models.CharField(max_length=1000) retailer = models.CharField(max_length=250) category = models.CharField(max_length=100) featured = models.CharField(max_length=10, default='NO') class Stock(models.Model): item = models.ForeignKey(Item, related_name='sizes') size = models.TextField() I have a script that reads a CSV datafeed file and use pandas to parse then input the appropriate results into the database. Via a command like this: try: Item( title=title, price=price, aw_product_id=aw_product_id, url=url, image=image, retailer=retailer, category=category, ).save() except IntegrityError as e: print(e)try: I'm using inlines as there are multiple sizes that I wish to add such as 'XS, S, M, L, XL, XXL'. This is my admin.py class StockInline(admin.StackedInline): model = Stock class ItemAdmin(admin.ModelAdmin): inlines = [ StockInline, ] admin.site.register(Item, ItemAdmin ) admin.site.register(Stock) How can I add to the 'sizes' field on 'Stock'? I've though about something like this: size=Stock.objects.create(size=size) ? -
Cant create new user in Django by form?
In my Django project I have modal with form where superuser can create new user. When superuser submit the form if raise error in browser console. Also here below you can see detailed log. Can someone say where are my mistakes? I am not sure but it seems to me that form is not valid because of password1 and password2 fields. Do you have any ideas? forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'password1', 'password2') def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs = { 'class': 'form-control', 'id': 'username', } self.fields['first_name'].widget.attrs = { 'class': 'form-control', 'id': 'first_name', } self.fields['last_name'].widget.attrs = { 'class': 'form-control', 'id': 'last_name', } self.fields['email'].widget.attrs = { 'class': 'form-control', 'id': 'email', } self.fields['password1'].widget.attrs = { 'class': 'form-control', 'id': 'password1', } self.fields['password2'].widget.attrs = { 'class': 'form-control', 'id': 'password2', } self.fields['is_active'].widget.attrs = { 'class': 'form-control', 'id': 'is_active', } self.fields['is_superuser'].widget.attrs = { 'class': 'form-control', 'id': 'is_superuser', } self.fields['last_login'].widget.attrs = { 'class': 'form-control', 'id': 'last_login', 'readonly': 'readonly', } self.fields['date_joined'].widget.attrs = { 'class': 'form-control', 'id': 'date_joined', 'readonly': 'readonly', } views.py: class UserCreateView(CreateView): template_name = 'users/create_user.html' form_class = UserCreateForm def get(self, … -
Django Python application not getting Taggable_friend Permission
I have applied many times to Facebook and asked for taggable_friend permission as I want to display the friend image and then tag them. I tried the sharable dialog, so that I can get the taggable-friend permission but failed. <script> document.getElementById('shareBtn').onclick = function() { FB.ui({ method: 'share_open_graph', action_type: 'og.shares', action_properties: JSON.stringify({ object: { 'og:url': document.location.origin, 'og:title': "{{fb.first_name}}'s Test result", 'og:description': 'Let\'s check yours.', 'og:image': '{{fb.picture.data.url}}', } }) }, function(response){}); } document.getElementById('invite').onclick = function() { FB.ui({ method: 'send', link:"http://website:port/", }, function(response){}); } window.fbAsyncInit = function() { FB.init({ appId : 'xxxxxxxxxxxxx', xfbml : true, version : 'v2.10' }); FB.AppEvents.logPageView(); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> I want to know how I can have access to taggable_friend permission from facebook. What I can do so that I get access to Taggable friend permission. Kindly, let me know your insights. -
Deploy a Django App Using AWS, but always get 504 Gateway Time-out
I just followed this tutorial (https://www.packtpub.com/books/content/how-deploy-simple-django-app-using-aws) to put my django project to AWS server, using nginx and gunicorn Here's my nginx.conf: server { listen 80; server_name 52.63.229.89; access_log /var/log/nginx-access.log; error_log /var/log/nginx-error.log; root /home/ubuntu/code-query/ELEC3609/ELEC3609; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; #uwsgi_read_timeout 120; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 10; proxy_send_timeout 15; proxy_read_timeout 20; } } And my gunicorn is running, but I just get 504 Gateway Time-out on my website. What's happening? -
Can't get POST data from Django (sending it from React)
I'm spending hours to solve this problem. The problem is I can't send POST's body data. I'm getting 500 error from the server. Here is my HTTP request on React Native (I don't think I have a problem here). There might be problem on http body? export const createCloth = (token, hType, clothObject) => async dispatch => { let headers = { 'Authorization': `JWT ${token}`}; if(hType==1) { headers = { 'Authorization': `JWT ${token}`}; } else if (hType==2) { headers = { 'Authorization': `Bearer ${token}`}; } let {image, text, clothType, ... , onlyMe} = clothObject; console.log(text); <- printing ok console.log(bigType); <- printing ok let response = await axios.post(`${ROOT_URL}/clothes/create/`, { text, clothType, ..., onlyMe }, {headers}); console.log(response.data); Here is my part of Backend API. class ClothCreateAPIView(APIView): def post(self, request, format=None): # Create Cloth # self.request.POST.get('user_id') print('--------REQUEST-------') print(request) logged_in_user = self.request.user content = self.request.POST.get('text') cloth_type = self.request.POST.get('clothType') only_me = self.request.POST.get('onlyMe') ... print('----------PRINTING CLOTH CONTENT') print(logged_in_user) <- printing my username (GOOD) print(cloth_type) <- printing None always print(content) <- printing None always At the last two line, why are they always printing None? I'm checking these syntax back and forth more than twenty times. This is so frustrating I tried with self.request.POST.get(~) request.POST.get(~) ?? -
OperationalErrors - no such column django - ForeignKey
I have this field in my model: customer = models.ManyToManyField(Customer) Due to some changes, I realized that I have to change the relationship to this: customer = models.ForeignKey(Customer) I have tried to do the makemigrations app_name and migrate again and again but it still produces the error. I also have tried deleting the existing data of the model in the admin site. -
Why are my tasks not found although they are in the database?
I'm using the library django-background-tasks: https://github.com/arteria/django-background-tasks I'm doing the example in the documentation here: http://django-background-tasks.readthedocs.io/en/latest/ I ran the the task in the shell: from forker.tasks import notify_user notify_user(user.id) And I made sure that it was saved in the database successfully in the table background_task I ran the command: python manage.py process_tasks The process keeps running without finding any task. With some troubleshooting, I found the part of the code that can't find any tasks in background_task/management/commands/process_tasks.py: while (duration <= 0) or (time.time() - start_time) <= duration: if sig_manager.kill_now: # shutting down gracefully break if not self._tasks.run_next_task(queue): # there were no tasks in the queue, let's recover. close_connection() logger.debug('waiting for tasks') time.sleep(sleep) else: # there were some tasks to process, let's check if there is more work to do after a little break. time.sleep(random.uniform(sig_manager.time_to_wait[0], sig_manager.time_to_wait[1])) It always doesn't find tasks in the queue (the second if statement). Any idea why it can't find a next task? I am pretty sure I'm going through the documentation step by step but now I am looking the library code and feeling getting out of track. -
Django + docker + periodic commands
What's the best practices for running periodic/scheduled tasks ( like manage.py custom_command ) when running Django with docker (docker-compose) ? f.e. the most common case - ./manage.py clearsessions Django recommends to run it with cronjobs... But Docker does not recommend adding more then one running service to single container... I guess I can create a docker-compose service from the same image for each command that i need to run - and the command should run infinite loop with a needed sleeps, but that seems overkill doing that for every command that need to be scheduled What's your advice ? -
Django mail sending error when DEBUG is False
I have a Django website with contact form. I need to send email to user and admin. When the DEBUG is False in settings.py the mail was not send. It generates 500 error in console. Can you help me to solve this. -
Error "Section 'Boto' already exists"
I need make new S3 File System (different than existing one). When I'm trying to do it i get Section 'Boto' already exists I understand, that firstly I need to delete previous S3 File System. One question - how can I delete the existing one? -
Should I have a seperate table for each media type
See initially I thought this would be simple but this is killing me right now I have a post model which contains a field (foreign key to media) Media has 3 colums Image, Video, Audio (each related to their own tables) And each of those three tables above has 1 file field (except for image because that holds x and y coordinated too for the tagging purpose) I don't wanna disturb the order of the upload(the size if the field is gonna change in future because I have to store a thumbnail for each file) let's say a user uploaded a picture first and then audio and then a video I wanna display them in the order as they were uploaded but I really don't know how to achieve this Can anyone please help me figure out, what should I do to implement this -
Django internet explorer download page content instead render it
I create a website using django and python tecnologies. When i view it with browser like chrome,safari,firefox ecc ecc all done, but if i open in explorer this appen: in my views.py i have this code: def index(request): context = RequestContext(request) c_form = False try: c_form = request.COOKIES['cform'] except Exception: if request.POST: c_form = foo_email(request) context_list = {'form': c_form} response = render(request, 'base_home.html', context_list, context) if c_form: response.set_cookie('cform', value='1', max_age=None) return response the response variable contain the html strucutre of the page, other browser render it but ie doesn't, why? Thanks in advance -
Mongo query in Django (python) if I use variable as Collection Name?
My MongoDB query in Django App like this, how can i use dynamic variable name for Collection Name mycoll = 'my_collection_name' client = MongoClient() db = client['database_name'] collection = db.mycoll.find({'Return._id': q},{'Return.ReturnData':1,'_id':0}) -
Is there somewhere different between `pk` and `id`?
When I read the source code, I find the function use pk to as keyword to select data: def detail(request, album_id): try: album = Album.objects.filter(pk=album_id) except Album.DoesNotExist: raise Http404("Album does not exist") context = { "album":album, } return render(request, "music/detail.html", context) I am used to use id: album = Album.objects.filter(id=album_id) So, is there somewhere different between them? -
How do I add different users data on my Django backend?
I have a bunch of users on my django backend. Let's say each user has a field 'age'. I would like to add every users age and divide by the number of users to get an average. Would this best be done in a ModelView as a function that makes a call using a While loop (while User.age for example)? -
Iterating through json request with multiple objects - django
I have a django project that I am working on. I have a api request that is returning a json response. With the json reponse that I am getting, there is a list of funding sources and within each funding source is an item that has the name with the object. I want to go though each json item and grab the names from the list of objewcts. how can I do this with the following response. I will also attach the request code that I sent... response: { 'funding-sources':[ { '_links':{ 'self':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..546a9720a01', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'funding-source' }, 'customer':{ 'href':'https://api-sandbox.dwolla.com/customers/..524dde5a', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'customer' }, 'initiate-micro-deposits':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..6a9720a01/micro-deposits', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'micro-deposits' } }, 'id':'56b3ab2c-da7b-4edc-83a8-5546a9720a01', 'status':'unverified', 'type':'bank', 'bankAccountType':'checking', 'name':'Cheese', 'created':'2017-11-02T05:37:39.000Z', 'removed':False, 'channels':[ 'ach' ], 'bankName':'SANDBOX TEST BANK', 'fingerprint':'..ff1d7dcd22' }, { '_links':{ 'self':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..a51126e4', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'funding-source' }, 'customer':{ 'href':'https://api-sandbox.dwolla.com/customers/..6b56524dde5a', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'customer' }, 'with-available-balance':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..d3a51126e4', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'funding-source' }, 'balance':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..6e4/balance', 'type':'application/vnd.dwolla.v1.hal+json', 'resource-type':'balance' } }, 'id':'522d3f3c-5ea2-4751-a485-4ad3a51126e4', 'status':'verified', 'type':'balance', 'name':'Balance', 'created':'2017-11-02T01:51:27.000Z', 'removed':False, 'channels':[ ] } ] } here is the code that I have right now for the request... the funding sources is in the -embedded objects as you will see in the code below: sources = app_token.get('%s/funding-sources' % account_url) accounts = sources.body['_embedded'] -
port is listening in server but unable to telnet ( Django with Apache )
I have developed a Django application which I wish to deploy on apache2.4 server. I have configured mod_wsgi and stuff on a system, which is going to be my server and localhost:8081 (apache's port) is working properly on the server system. I am in a corporate environment. When I wish to access the application from another system, I am unable to access the page.(The server and client are in the same network, both using LAN) Observations: 8081 port is listening on my server system (Proto: TCP, Local Address: 0.0.0.0:8081, Foreign Address: Computername:0, State: LISTENING) I am unable to telnet to server ip on port 8081 (Connecting To 10.176.241.35...Could not open connection to the host, on port 8081: Connect failed) I have JDeveloper installed in my server system and I am able to access the homepage of WebLogic server from another system though. Site can't be reached, took too long to respond error while trying to access the page from client system What all I have done so far: Followed the exact steps mentioned in here for configuring apache with django Turned off firewall in both client and server systems Add inbound and outbound exception rules in Advcanced firewall settings in … -
How to sum and group data for template
For simplicity, assume a database with the following columns: Table: Tickets Columns: Gender, Quantity, Date where Gender can be M or F. A row is inserted for every purchase. Ultimately I want a stacked bar chart that shows the quantity purchased by males and females each month. I can't seem to find a way to do this that doesn't require 2 queries, one that sums for M per month and one for F per month. The problem is that the query sets may not have the same number of objects and may not be in the same order by date. I've tried: set = Model.objects.filter(date__month = month).values('gender').aggregate(Sum('quantity')) This sorts by date but doesn't separate M from F. Adding M or F as a filter yields the correct quantity for one of the groups. Using two queries(one for each of M, F) yields the correct quantities and date ranges but doesn't necessarily yield an identical number of sets. (eg. if in some months there are no purchases by M). Thanks in advance for guidance. -
TypeError: 'RegexValidator' object is not iterable
I was building integer array field for color. I tried to use CommaSeparatedIntegerField but it was depreated CommaSeparatedIntegerField has been deprecated. Support for it (except in historical migrations) will be removed in Django 2.0. HINT: Use CharField(validators=[validate_comma_separated_integer_list]) instead So I used set the color field as CharField instead of CommaSeparatedIntegerFieldas recommended from django.core.validators import validate_comma_separated_integer_list class Cloth(models.Model): color = models.CharField(validators=validate_comma_separated_integer_list) But I'm getting this error when I makemigrations TypeError: 'RegexValidator' object is not iterable Why am I getting this error? I followed the exact guideline :(