Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'Column 'user_id' cannot be null'
Please help me resolve this issue. I'm starting to learn Django. Please tell me where the error. I was looking for similar problems, but I did not find a solution. Thanks views def register(request): args = {} args['forms'] = SignUpForm() args['form1'] = ImagefieldForm() if request.POST: newuser_form = SignUpForm(request.POST) image_field_form = ImagefieldForm(request.POST, request.FILES) if newuser_form.is_valid() and image_field_form.is_valid(): user = newuser_form.save(commit=False) user.is_active = False user.save() print ('User saved') image_field_form.save() current_site = get_current_site(request) mail_subject = 'Welcome to site' message = render_to_string('login_app/please_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = newuser_form.cleaned_data.get('username') email = EmailMessage( mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please check your email') else: args['forms'] = newuser_form return render(request, 'login_app/registration.html', args) forms class ImagefieldForm(forms.ModelForm): avatar = forms.ImageField(required=True) class Meta: model = Profile fields = ('avatar', ) models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='images/users', blank=False) -
How to Upgrade Pinax for Django 2.0
I am trying to upgrade my django project to Django 2.0, and I have read the release notes and read several blog posts about what to change, but nothing addresses my problem so far, which relates to the package pinax: File "/Users/marlo/miniconda3/envs/project/lib/python3.6/site- packages/pinax/eventlog/models.py", line 13, in class Log(models.Model): File "/Users/marlo/miniconda3/envs/project/lib/python3.6/site-packages/pinax/eventlog/models.py", line 22, in Log content_type = models.ForeignKey(ContentType, null=True) TypeError: __init__() missing 1 required positional argument: 'on_delete' Are there any fixes for this yet? -
Clicking 'Make public' on my S3 Bucket doesn't do anything
Here is the image of me clicking 'Make Public' on one of my images in my bucket: and then subsequently clicking 'Make public' on the pop-up window: It says it completed successfully - however when I refresh the page it still gives me the option to 'Make public' so it appears it didn't work. When I go to my website the image still doesn't show up, further showing the image is still not public. This is the src the img uses on my website: https://postr-bucket.s3.amazonaws.com/static/images/settingsIcon.png?Expires=1519249290&Signature=9eixuWMxLknf%2BAnDB1XIS30ntO8%3D&AWSAccessKeyId=AKIAIDO3PF5Y7SMSOHHA I don't think the access key should be in that src, but I'm not sure how to change it. My settings for AWS are normal: from decouple import config import datetime AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY") AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = 'draft1.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'draft1.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'postr-bucket' S3DIRECT_REGION = 'us-west-2' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ), } I've also tried the same 'Make public' … -
Time passed to celery beat schedule from model object
I wonder how can I pass the time from the model object to the celery beat schedule in settings.py? Do I need to import the model in settings.py and iterate over all objects? model.py class Note(models.Model): user = models.ForeignKey(User, related_name='notes') status = models.TextField(max_length=500) publish_time = models.DateTimeField() is_publish = models.BooleanField(default=False) Task in my app: @task() def task_number_one(): // do something return something celery part in settings.py CELERY_BROKER_URL = 'amqp://localhost' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'noteapp.tasks.task_number_one', 'schedule': crontab(minute=put here min from model, hour=put here hour from model), }, } -
Django url parameters in html code
I am trying to pass the id of a todolist item to my html code so that everything works when I am editing the todolist item and I click submit. #views.py def edit(request, id): todo = Todo.objects.get(id=id) context = { 'todo': todo } if(request.method == 'POST'): title = request.POST['title'] text = request.POST['text'] todo.title = title todo.text = text todo.save() return redirect('/todos') else: return render(request, 'edit.html', context) #urls.py url(r'^details/(?P<id>\w{0,50})/edit/$', views.edit, name='edit') #my html code <h2>Edit Todo- {{ todo.title }}</h2> <form action="{% url 'edit' request.todo.id %}" method="post"> {% csrf_token %} <label for="title">Title</label> <br/> <input type="text" name="title" id="title"/> <br> <label for="text">Text</label> <br/> <textarea type="text" name="text" id="text"></textarea> <br><br> <input type="submit" value="Submit"/> </form> I think the problem is in my url in the html code. I can't figure out how to pass my todolist item's id parameter. The error I keep getting is invalid literal for int() with base 10: '' Please help -
django 2.0 Having Issue about MySql and Login check & redirect
I dedicated to learn django & python , I have decided to develop a social media platform using Django 2.0.So far I have made some progress.I have connected phpMyAdmin to settings.py.I can make user registration and keep them in my database.So far so good.When it comes to log and redirect them to my home.html , problem starts. I have followed range of tutorials to solve it but couldnt manage to do it with my lack of knowledge.Iam going to share my code below.I believe it is most basic thing sorry about it im just new lerner. Please i would preciate any little tiny info about my questions.Iam so confused , i need to understand these basics to go further. Views.py Problem: This code has some problems. It does not redirects after submit button.I also figured that I ommitted MySQLdb , query.execute basically all but log(request,email,password) and return HttpResponseRedirect section code still working ? Do i not need to connect db ? since i already set connect settings in settings.py.If so i check if user and password matchs in my db with if(query.execute("SELECT * FROM landingapp_user WHERE email = '" + email + "' AND password = '" + password + … -
Add new form prepopulated with data in Django's admin
How can you go about adding an "add new" button that prepopulates with data from an existing object within Django's admin for a given model? -
Django Model Instance as Hashable List
We have sales data for a number of brands retrieved from a remote server in JSON. Each brand has a unique API key and password. These are stored and decoupled in settings.py. Each brand is matched to its API key and password according to the below dictionary. How do we create a hashable list of brands based on the 'brand' model instance? brand = models.CharField(max_length=140, default='') brands = WHAT DO WE PUT HERE? api_key = { "BRAND1": settings.BRAND1_API_KEY, "BRAND2": settings.BRAND2_API_KEY, } password = { "BRAND1": settings.BRAND1_PASSWORD, "BRAND2": settings.BRAND2_PASSWORD, } orders_url = 'https://{}:{}@site.com/admin/orders/count.json'.format(api_key[brands],password[brands]) -
Cloudinary multiple image upload in django?
I have an image upload defined as follows in my Django app with Cloudinary package, class Photo(models.Model): photo = CloudinaryField('image') I Would like to make this field upload mutliple images. How do I do this? -
Use Django with SSL in order to integrate PayPal
I want to use PayPal in a Django Project and in order to do this I need Django to work with TSL 1.2. Since I haven't worked with such encryption yet, I need advice on how to setup Django in a way that works with an https version that works with PayPal. I already have a working ssl certificate and was able to use django-sslserver to make Django work with https, but PayPal still does not work with it. Could someone give a hint were I should be looking into for this kind of thing? -
How can I add additional top level JSON fields using the ModelSerializer
I am using the ModelSerializer from the Django Rest Framework to create an API. The ModelSerializer works great for returning JSON lists of whatever I query the database for. But I need to have some additional fields at the root level of the JSON response. How can I bump the query result to another level and add custom fields at the root of the JSON object? This is what the API query returns: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "user": { "username": "myuser" }, "content": "Another tweet", "timesince": "2 weeks, 3 days", "url": "/tweet/3/", "id": 3 }, { "user": { "username": "myuser" }, "content": "a tweet", "timesince": "2 weeks, 3 days", "url": "/tweet/2/", "id": 2 } ] This is what I want: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "custom_field": "custom value", "result": [ { "user": { "username": "myuser" }, "content": "Another tweet", "timesince": "2 weeks, 3 days", "url": "/tweet/3/", "id": 3 }, { "user": { "username": "myuser" }, "content": "a tweet", "timesince": "2 weeks, 3 days", "url": "/tweet/2/", "id": 2 } ] } serializer.py: from django.utils.timesince import timesince from rest_framework import serializers from tweets.models import Tweet from … -
How do I paginate for every slug?
I was wondering what is the right way to paginate items from a slug page. I tried something, but I can't seem to figure out how to properly pass Courses that belong to that Faculty and to paginate them by 1 course per page. Here is what I tried: def faculty_filter(request, faculty_slug): qr = get_object_or_404(Faculty, faculty_slug=faculty_slug) query_list = Course.objects.get(qr) query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.filter(faculty_slug=faculty_slug), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), } return render(request, 'courses/filters/faculty_filter.html', context) Note: Courses do not directly belong to a Faculty. I have four models bound by foreign keys in this order: Faculty > Department > StudyProgramme > Courses. -
html form and successfully message
hello i have a simple html form with select option choose. I want after form submit the user get successfully message like this <p>your request is complete</p> in the position of html form. and if user press refresh then html form come back in page. here the code : <form action="" method="POST"> <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <br> <br> <input class="btn btn-primary btn-lg btn-block" type="submit"> </form> any idea ?I am stack now I know this method action="other.html" but I want to work in the some html page without create other html page. -
invalid literal for int() with base 10: 'edycja' Django
I have a little problem. I've create a app where I can added the new records and edit. And now in edit this problem appear. When I select from list the record to edit -> form loading me properly the filled fields with datas. But when I click on Edit button to update the datas, the Django return me a error: **invalid literal for int() with base 10: 'edycja'** I don't know exacly where is a problem. Maybe somebody could help me? Here is the part of my views.py @login_required def szczegoly_pracownik(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) return render(request, 'cudzoziemiec/szczegoly_pracownik.html', {'link_pracownik': link_pracownik}) @login_required def edycja_pracownika(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) if request.method == 'POST': edycja_pracownika = CudzoziemiecForm(request.POST, instance=link_pracownik) if edycja_pracownika.is_valid(): link_pracownik = edycja_pracownika.save(commit=False) link_pracownik.save() return render('szczegoly_pracownik', id=link_pracownik.id) else: edycja_pracownika = CudzoziemiecForm(request.user, instance=link_pracownik) return render(request, 'cudzoziemiec/edycja_pracownika.html', {'edycja_pracownika': edycja_pracownika}) And when I read the log the error is somewhere in def szczegoly_pracownik -
Constructing Django templates from strings within Python code
I'd like to test a custom filter I wrote in Django, label_with_classes. My basic approach is to instantiate a 'snippet' of my actual template using by instantiating a django.template.Template with a string, rendering it with some context, and asserting that the generated output is what I would expect. I would also like to be able to write tags, etc. on new lines like I do in the actual template. The problem is that when I do this, lots of whitespaces appear in the rendered output. Here is a test case so far: from ..templatetags.label_with_classes import label_with_classes from django.test import SimpleTestCase from django.template import Context, Template from ..forms.sessions import SessionForm class CustomFilterTest(SimpleTestCase): def test_1(self): form = SessionForm(data={}) template = Template("\ {% load label_with_classes %}\ {{ form.session_number|label_with_classes }}") context = Context({'form': form}) output = template.render(context) upon which I drop into the debugger using import ipdb; ipdb.set_trace(). Here I see that output has lots of leading whitespaces: ipdb> output ' <label class="invalid" for="id_session_number">Session number:</label>' It seems like this whitespace comes from me writing on new lines in the string in the Template() constructor. However, in the actual HTML whitespaces between HTML tags are ignored. Is there a way to 'write HTML within' Python … -
Suggesting compatability level based on min and max value
I am stuck with a somehow reasonable request from a client but harder to implement (and downvotes for sure :p). The application includes State, City, County etc. Each one has weather related information for a range of month. A typical model is now: class County(models.Model): min_temp=models.DecimalField() max_temp=models.DecimalField() class Person(models.Model): prefer_min_temp=models.DecimalField() prefer_max_temp=models.DecimalField() So basically, when a person choses a county, we want to tell him his comptabiity based on the min and max temperature he has declared he prefers on a scale of 0-30 (Weak),31-50 (Good), 51-70 (Fair), >71 (Excellent) E.g. prefere_min_temp=50, max=90 County: min_temp=30, max_temp=100 How do I go about handling this for temperatures that can vary significantly with low percentage of error, since it is an a recommendation? -
django views.py search query un sorts my dataframe
I'm having a unique problem with my Django program. I have a problem where I need to get user input, query the database and return the results to the screen. I have written a custom function: get_cust_info(first_name, last_name, middle_name, address, state, zip) that takes in those respective inputs, queries the database and returns a list of suggested names in the event the user has typed his name wrong. The function works, returning the 10 largest values (names are sorted by their score, higher the score, better the match). I tested this function in a conda python 3 environment and it works as it should. But, when I try this in django, for some reason, it unsorts the values. Not sure what is going on. In my views.py, i have: #views.py from django.shortcuts import render from .name_matching import get_cust_info # Create your views here. def search_form(request): return render(request,'search_form.html') def search(request): first_name = request.GET['fname'] middle_name = request.GET['mname'] last_name = request.GET['lname'] address = request.GET['address'] zip_code = request.GET['zip'] state = request.GET['state'] df = get_cust_info(firstName=first_name, middleName=middle_name, lastName=last_name, address=address, zip_code=zip_code, state=state) path = 'H:\\work\\projects\\scoville_name_match\\scovilleapp\\templates\\search_results.html' df = df.nlargest(10, ['score_first', 'score_second', 'score_third']) df.to_html(path) return render(request,'search_results.html') #urls.py from django.conf.urls import url from django.contrib import admin from scovilleapp import views … -
django The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
I'm deploying a Django application on heroku. In my settings module, I have configured to host static files like STATIC_ROOT = os.path.join(BASE_DIR, 'static_my_project') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_my_project') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'media_root') and urls.py urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But on deployment to heroku, it gives error as SystemCheckError: System check identified some issues: ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. -
How do I get elements from a Django Queryset starting from a specific position?
I have a queryset in a Python/Django project: articles = ArticlePage.objects.live().order_by('-date') If I wanted to get only the first 50 elements I'd do: articles[:50] But also I need to get elements from position 5, this is to ignore the first 4 elements. I was expecting it to have something like articles[5:][:50] but I can't seem to find anything like that in the docs. Is there any way to achieve this? -
django-channels webSocketBridge read data sent by consumers
I am having a simple setup with testing channels 2.0. I have a routed consumer with three methods: consumers.py from channels.generic.websocket import JsonWebsocketConsumer from datetime import datetime # class Feedback_001_Consumer(JsonWebsocketConsumer): def connect(self,text_data=None, bytes_data=None): self.accept() self.send_json("Connection for Feedback 1 ready.") # def receive(self,text_data=None): #self.accept() self.send_json("{}".format(datetime.now())) print(datetime.now()) # def disconnect(self,close_code): pass and my js looks like this: const webSocketBridge = new channels.WebSocketBridge(); #... webSocketBridge.connect('my_route/etc...'); #... console.log(webSocketBridge.send('')); While the datetime is printing in the console, I cannot get the one sent by self.send_json in the receive method of the consumer. What would be the proper way to do this? -
Django: form.is_valid() is always false
I'm just a beginner in Django and I am currently developing user login functionalities. I've come across a bug and I cannot find out what is wrong. I've read other questions and solutions from that topic, but those solutions do not apply to my problem. I tried them but they do not work. My problem: form.is_valid() is always false views.py def login_view(request): form = UserLoginForm(request.POST or None) print(request.user.is_authenticated) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) print("Works") print(request.user.is_authenticated) return render(request, "music/login.html", {'form': form}) forms.py User = get_user_model() class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user does not exists") if user.check_password(password): raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("Tjis user is not longer active") return super(UserLoginForm, self).clean(*args, **kwargs) login.html <h3>Login</h3> <form class="form-horizontal" action="" method="POST" enctype="multipart/form-data"> {% include 'music/form-template.html' %} {% csrf_token %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> Thanks for help! -
django post method to get all value with same name
Hi i am trying to build a application using Django. I have a form under which i let the use to enter n number of input as they wish. but i am not able to retrieve the data as expected when the submit. Here is my view def sample(request): if request.method == 'POST' form_value = request.POST.copy() print form_value #This print statement print me <QueryDict: {u'csrfmiddlewaretoken': [u'gAxkEq1bVk5hQicPGmFo4DTIOxomOUdtaOiimW5Bel1kvFaYyECp5JzPqk4yzJe8'], u'userinput': [u'asddsaf', u'asfsadf', u'asfsdf', u'asfdsaf', u'asfasdf']}> print form_value['userinput'] # but this print statment print me only the last value asdfsaf my HTML <form action='.' method='post'> {% csrf_token %} <input type='text' name='userinput'> <input type='text' name='userinput'> <input type='text' name='userinput'> <input type='text' name='userinput'> <button type='submit'>Submit</button> </form> How can i get the list/array of input with the name 'userinput' -
In Django, how to filter a model using a list of values but each value can be used only once?
I'm new to Django. I have a Postgres database of details about movies. I want to display 10 movies on a page. I have 2 issues: Each movie must be from a different country. So far, I can only get a list of 10 random countries from a larger list. I don't know how to use .objects.filter() in a way that makes sure there are no repeated countries. Some movies are produced by more than one country, and they are contained as strings in the database, for instance 'Tajikistan,Papua New Guinea,Korea'. But the .objects.filter() function only returns movies with a single country in it. My current code in views.py: from .countries import countries # this is a Python list of countries class MoviesListView(generic.ListView): model = Movies def get_queryset(self): random_countries = [] i = 0 while i < 10: country_choice = random.choice(countries) if country_choice in random_countries: pass else: random_countries.append(country_choice) i += 1 for i in random_countries: print(i) print(len(random_countries)) return Movies.objects.filter(production_countries__in=random_countries)[:10] I've googled around and looked into the Django documentation but haven't been able to find solutions. What's the best way to do this? Must I connect to the database with psycopg2, use sql to get 10 movies that fit my criteria … -
How to edit form in Django
I'am trying to create a edit form in my project but my code do not working well. I can't find the error. Maybe somebody help me? My views.py is: @login_required def szczegoly_pracownik(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) return render(request, 'cudzoziemiec/szczegoly_pracownik.html', {'link_pracownik': link_pracownik}) @login_required def edycja_pracownika(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) if request.method == 'POST': edycja_pracownika = CudzoziemiecForm(request.user, request.POST) if edycja_pracownika.is_valid(): link_pracownik = edycja_pracownika.save(commit=False) link_pracownik.save() return render('szczegoly_pracownik', id=link_pracownik.id) else: edycja_pracownika = Cudzoziemiec(request.user) return render(request, 'cudzoziemiec/edycja_pracownika.html', {'edycja_pracownika': edycja_pracownika}) the def szczegoly_pracownik is responible for getting the details from record When I click in html file on the button "Edit" the url works ok, because is redirecting me in to the edycja_pracownika.html , but in edycja_pracownika.html i see only the button, without forms. -
Form not showing up Django 1.8
I am making a project using python 3.5 and Django 1.8 ,there is a feature for login and signup, so login and signup are two different apps THIS image shows my directory structure of apps Now in login app's form , I import from signup.models allusers1 (a class in signup.models) Using view I pass the form but nothing is showing up ,but the submit button shows nothing else This is login/forms.py from django import forms from signup.models import allusers1 from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) User=get_user_model() class UserLoginForm(forms.Form): class Meta: model = allusers1 fields=['username','password'] widgets = { 'password': forms.PasswordInput(), } def clean(self ,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user_qs = User.objects.filter(username=username) if user_qs.count() == 0: raise forms.ValidationError("The user does not exist") else: if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is no longer active") return super(UserLoginForm,self).clean(*args,**kwargs) This is signup/models.py from django.db import models from django import forms # Create your models here. class allusers1(models.Model): username=models.CharField(max_length=40) password=models.CharField(max_length=40) phoneno=models.CharField(max_length=10,primary_key=True) otp=models.IntegerField(blank=True,null=True,default=0000) def __str__(self): return self.username login/views.py def login(request): form1=UserLoginForm(request.POST or None) if form1.is_valid(): username=form1.cleaned_data.get("username") password=form1.cleaned_data.get("password") user=authenticate(username=username,password=password) auth_loginwa(request,user) print(request.user.is_authenticated()) return redirect("home2") context= { "form1": form1, } return render(request, "login.html",context) login.html <form action="" …