Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serve private image in html page with django?
I have a django website that serves media image with nginx. I implemented permissions adding 'internal' option in nginx configuration so I can download image with 'X-Accel-Redirect'. Now I can't see images in html pages. Is there any solution to view these images in my html pages? -
Django contact form isn't sending message content
My contact form sends emails to my gmail account but they never have any subject or message content. I'm not quite sure what to do next. If any more code is needed, please let me know. views.py from django.views.generic.edit import FormView from .forms import ContactForm try: from django.urls import reverse except ImportError: # pragma: no cover from django.core.urlresolvers import reverse # pragma: no cover class ContactFormView(FormView): form_class = ContactForm recipient_list = None template_name = 'contact_form/contact_form.html' def form_valid(self, form): form.save() return super(ContactFormView, self).form_valid(form) def get_form_kwargs(self): # ContactForm instances require instantiation with an # HttpRequest. kwargs = super(ContactFormView, self).get_form_kwargs() kwargs.update({'request': self.request}) # We may also have been given a recipient list when # instantiated. if self.recipient_list is not None: kwargs.update({'recipient_list': self.recipient_list}) return kwargs def get_success_url(self): return reverse('contact_form_sent') forms.py from django import forms from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.utils.translation import ugettext_lazy as _ from django.core.mail import send_mail from django.template import loader class ContactForm(forms.Form): name = forms.CharField(max_length=100, label=_(u'Your name')) email = forms.EmailField(max_length=200, label=_(u'Your email address')) body = forms.CharField(widget=forms.Textarea, label=_(u'Your message')) from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [mail_tuple[1] for mail_tuple in settings.MANAGERS] subject_template_name = "contact_form/contact_form_subject.txt" template_name = 'contact_form/contact_form.txt' def __init__(self, data=None, files=None, request=None, recipient_list=None, *args, **kwargs): if request is None: raise TypeError("Keyword … -
django admin: apply filter_horizontal to an inline model?
If according to django documentation, filter_horizontal is one of the shared features for the InlineModelAdmin class... Then I just need to understand syntactically how to apply it to an inline model. So I have an inline for a model called Keyword. I would like it to display using the filter_horizontal feature on the admin page for changing the Statement model. I was hoping it would be as simple as class KeywordInline(admin.TabularInline): model = Keyword.statement.through class KeywordAdmin(admin.ModelAdmin): inlines = [KeywordInline,] filter_horizontal = ('keyword',) class StatementAdmin(admin.ModelAdmin): list_display = ('statement_id', 'title', 'author', 'released_by', 'issue_date', 'access', 'full_text',) list_filter = (StatementListFilter, 'released_by', 'issue_date', 'access',) search_fields = ('statement_id', 'title', 'author', 'issue_date',) inlines = [ KeywordInline,] But this has... literally no effect on the display of the inline. What am I missing (syntactically)? -
Form.is_valid is always false
I am writing a simple survey with modelForm. I have searched online for this issue too and it says that's because it's because the form is unbound... but I for simplicity I only offered one choice in models.py models.py Those are hardcoded as radio inputs in html class Office(models.Model): Office_Space = ( ('R1B1', 'R1B1'), ('R2B1', 'R2B1'), ('R3B1', 'R3B1'), ('R1B2', 'R1B2'), ('R2B2', 'R2B2'), ('R3B2', 'R3B2'), ('R1B3', 'R1B3'), ('R2B3', 'R2B3'), ('R3B3', 'R3B3') ) space = models.CharField(max_length=4, choices=Office_Space) form.py class officeForm(forms.ModelForm): class Meta: model = Office fields = ['space',] Thanks in advance. -
How can I send real-time data using Django WebSockets?
I would like to send real-time data from external API using Django WebSockets. My view with HTTP looks in this way: @permission_classes([GetPermission]) class DataList(GenericAPIView): serializer_class = ObjectSerializer def get(self, request): parameter = self.request.query_params.get('parameter', None) queryset = ExternalAPI().get(parameter, "RSQA") id = Object.objects.get(parameter=parameter).id queryset["id"] = id return Response(queryset) I would like use WebSockets instead of HTTP to send my data constantly. Is it a good solution and acceptable to send it without request? I wonder how it should be done? I will be grateful if example would be shown on my GenericAPIView. -
How do I add users to database so I can login using credentials?
Okay, so here's the issue; I will try to make this as short-winded as possible: I have gone through a tutorial at https://www.youtube.com/watch?v=CFypO_LNmcc and https://www.youtube.com/watch?v=Tam4IGrPESg to create a register, login, and logout system for my website/webapp. I have successfully been able to create the pages necessary to register a user successfully. To prove that registered users have been created successfully I have monitored users through the /admin portal to confirm that the users were indeed created. The way that I have things set up, after registration you must click on a link that takes you to the login page and login; however, every time I attempt to login using the newly created user I get redirected to my invalid_credentials.html although I have the password field set to expose my password so I can verify that the correct password is being typed. Now, in this tutorial that I have followed, the person in the video is doing "python manage.py syncdb". I assume that this is to sync the newly created users to be able to login. For me, since I am using Django 1.11, I am typing "python manage.py makemigrations" and then "python manage.py migrate". The issue is that when I … -
How to return model object as json after post request in DRF?
In my django rest api I have a view which adds a debt by creating a new Debt model instance and saving it. If this operation is successful, the api should return a response containing the newly created Debt model instance as json. The function in the model responsible for adding a debt and returning it is this: def add_debt(self, from_user, to_user, paying_user, receiving_user, amount, currency, description, date_incurred, deadline, payed, overdue): """ Create a debt request """ if from_user == to_user: raise ValidationError("Users cannot be in debt with themselves") request, created = DebtRequest.objects.get_or_create( from_user=from_user, to_user=to_user, paying_user=paying_user, receiving_user=receiving_user, amount=amount, currency=currency, description=description, date_incurred=date_incurred, deadline=deadline, payed=payed, overdue=overdue) debt_request_created.send(sender=request) return request In my view I have the following: class DebtRequestCreate(generics.GenericAPIView): permission_classes = (IsAuthenticated,) def post(self, request, *args, **kwargs): other_user = User.objects.get(pk=request.data["friend_pk"]) amount = request.data["amount"] currency = request.data["currency"] description = request.data["description"] date_incurred = request.data["date_incurred"] deadline = request.data["deadline"] is_payed = request.data["is_payed"] is_overdue = request.data["is_overdue"] is_in_debt = request.data["is_in_debt"] debt = None if is_in_debt: # is the request.user in debt debt = Debt.objects.add_debt( request.user, # From user other_user, # To user request.user, # Paying user other_user, # Receiving user amount, currency, description, date_incurred, deadline, is_payed, is_overdue) else: debt = Debt.objects.add_debt( request.user, # From user other_user, # To user … -
automatically set field values for models in Django
Is there a way to automatically set field values for models in Django when defining the model? I need t define some values of fields automatically in my model using function. my function get input image path calculate and I need that calculation results to define my database fields in Django. first to I want is something like this : mymodels.py : def myfun(): #processing return value1,value2 class MyModel(models.Model): field1 = models.ForeignKey(User, unique=False) field2 = models.ImageField(upload_to='images') field3= models.TextField(default=value1) field4 = models.TextField(default=value2) myfunction : def myfun(): #processing return value1,value2 my model : class MyModel(models.Model): field1 = models.ForeignKey(User, unique=False) field2 = models.ImageField(upload_to='images') field3= models.TextField() field4 = models.TextField() my view : def myview(request): uploadimages = UploadImagesForm(request.POST or None, request.FILES or None) if uploadimages.is_valid(): # Get the images that have been browsed if request.FILES.get('multipleimages', None) is not None: images = request.FILES.getlist('multipleimages') for image in images: MyModel.objects.create(field1=request.user,field2=image) first test from my views.py create object : def myview(request): uploadimages = UploadImagesForm(request.POST or None, request.FILES or None) if uploadimages.is_valid(): # Get the images that have been browsed if request.FILES.get('multipleimages', None) is not None: images = request.FILES.getlist('multipleimages') for image in images: value1=myfunc(image) value2=myfunc(image) MyModel.objects.create(field1=request.user,field2=image,field3=value1,field4=value2) that doesn't work because to work my function need first to upload image in … -
Django MEDIA_ROOT Development in Windows Environment
In my settings.py ive added the following print(BASE_DIR) print(MEDIA_URL) print(MEDIA_ROOT) It prints the following d:/OneDrive/!code_projects/!django_projects/mgTut /media/ d:/OneDrive/!code_projects/!django_projects/mgTut/media/ But when I start the server, I am seeing this error FileNotFoundError: [Errno 2] No such file or directory: 'd:\\OneDrive\\!code_projects\\!django_projects\\mgTut\\media\\media\\images\\profile_image\\0C0A8604_1_mKlAyCG.JPG' I'm not quite sure where to go from here. My media_root is supposed to replace, but it doesn't seem to be when it's called. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR + '/media/').replace('\\', '/') My models.py class: class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=200, default='') city = models.CharField(max_length=50, default='') state = models.CharField(max_length=2, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) avatar = models.ImageField(upload_to=b'media/images/profile_image', default='media/images/profile_image/Profile_Blank.PNG') avatar_thumbnail = ImageSpecField(source='avatar', processors=[ResizeToFill(100, 100)], format='JPEG', options={'quality': 60}) def __str__(self): return '%s - %s' % (self.user, self.description) profile = UserProfile.objects.all()[0] print(profile.avatar_thumbnail.url) # > /media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg print(profile.avatar_thumbnail.width) # > 100 Full error: d:/OneDrive/!code_projects/!django_projects/mgTut /media/ d:/OneDrive/!code_projects/!django_projects/mgTut/media/ Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002EDDFA09048> Traceback (most recent call last): File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "D:\OneDrive\!code_projects\!django_projects\windows_venv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() … -
Modify kwarg data for view in django
I am trying to implement an MVC like pattern in my views. Basically I have a base View which serves a normal type, and type1 view and type2 view that extends the base view. I also have a controller and a model to get and set data. I need to pass this model over to the view. But I always get a KeyError when I access the kwargs dict from the view. I am new to django and python. So please don't mind if I am missing something obvious. Here is the code class Controller(): NORMAL, TYPE1 , TYPE2 = (0,1,2) @classmethod def controller_init(cls): #entry point to view. Called in urls.py def view(request,slug,*args,**kwargs): self = cls() self.request = request self.slug = slug self.args = args self.kwargs = kwargs return self.start() return view def start(self): modal = Modal() self.kwargs['modal'] = modal modal.init(self.slug) ptype = modal.getPtype() return self.showView(ptype) def showView(self,viewType): if(viewType == self.NORMAL): view_handler = View1.as_view() elif(projectType == self.TYPE1): view_handler = ExtendedView1.as_view() else: view_handler = ExtendedView2.as_view() return view_handler(self.request,self.args,self.kwargs) -
i extended User Model and i dont know how to get value of it from other users through forms
i extended User Model so i made nickname. and nickname appears on admin page but i cant get value of it from other users through forms. the value was not saved whenever i clicked the submit button of my signup page after i filled up nickname charfield #models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User class Profile(models.Model): class Meta: verbose_name = u'profile' verbose_name_plural = u'profile' user = models.OneToOneField(settings.AUTH_USER_MODEL) nick = models.CharField(verbose_name=u'nickname', max_length=50, blank=True,) i think its working good but #forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django import forms from .models import Profile class CreateUserForm(UserCreationForm): email = forms.EmailField(required=True) nick = forms.CharField(required=True) class Meta: model = User fields = ("username", "email", "nick", "password1", "password2") def save(self, commit=True): user = super(CreateUserForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.nick = self.cleaned_data["nick"] if commit: user.save() return user I think something is wrong with forms.py <!--signup.html--> {% extends 'moc/base.html' %} {% block content %} <form method="post" action="{% url 'signup' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> {% endblock %} -
PyMySQL with Django, Multithreaded application
We are trying to use PyMySQL (==0.7.11) in our Django (==1.11.4) environment. But we are encountered with problems when multiple actions are performed at the same time (Multiple requests sent to the same API function). We are trying to delete records from the DB (some time massive requests come from multiple users). Code: def delete(self, delete_query): self.try_reconnect() return self._execute_query(delete_query) def try_reconnect(self): if not self.is_connected: self.connection.ping(reconnect=True) @property def is_connected(self) try: self.connection.ping(reconnect=False) return True execpt: return False def _execute_query(self, query): with self.connection.cursor() as cursor: cursor.execute(query) self.connection.commit() last_row_id = cursor.lastrowid return last_row_id I didn't think it necessary to point out that those functions are part of DBHandler class, and self.connection initialized in def connect(self) function. def connect(self): self.connection = pymysql.connect(...) This connect function run once in Django startup, we create a global instance(varaible) of DBHandler for the whole project, and multiple files importing it. We are using the delete function as our gateway to execute delete query. What we are doing wrong ? And how can we fix it ? -
How to get data from a remote host?
Please help get data from remote host. On http://localhost:8000/messages/index Django framework return follow JSON: [ {'key': val}, {'key': val}, {'key': val}, {'key': val} ] On http://localhost:4200/ anguler2 recieve JSON via service: @Injectable() export class MessagesService { private messagesArr: any[]; constructor(private http: Http){ this.messagesArr = localStorage.messages ? localStorage.messages : []; }; private messages: any[] = []; getMessages(): Observable<any> { let result = this.http.get('http://localhost:8000/messages/index'); console.log(result); return result; } } Component: ..... ngOnInit() { this.messagesService .getMessages() .map((response: Response) => JSON.parse(response.json())) .subscribe(data => { console.log(data); this.messages = data; }, err => { console.log('err') }); } ..... In Django i allowed follow hosts: ALLOWED_HOSTS = ['http://localhost:4200', 'localhost'] And allow CORS: CORS_ORIGIN_ALLOW_ALL = True In result Chrome-browser on 'network' tab display successful request and successful response JSON-data But Chrome-browser console display follow error message: XMLHttpRequest cannot load messages/index. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:4200' is therefore not allowed access. err -
django test : accessing database from a form returns empty list
I'm using a Django form, containing a ChoiceField list. This list content is retrieved from the form, using orm. It works in the application, but in the test, the utility method returns an empty content. Before I create the form, I'm querying the same table as the utility method, and it returns 3 records. Any idea why the utility method considers the table empty ? 1) the form : class JournalForm(forms.Form): journal_id = forms.CharField(widget=forms.HiddenInput(), required=False) journal_name = forms.CharField(label=ugettext('Journal name'), max_length=100, required=False) list_field = list() list_field.append(('0',ugettext('select'))) list_field = list_field + getFieldOfInterestList() journal_fieldOfInterest = forms.ChoiceField(initial='0', choices = list_field, label=ugettext('Field of interest'), widget=forms.Select(), required=False) 2) the utility method : def getFieldOfInterestList(): try: interest_list = list() for field in FieldOfInterest.objects.all().order_by('name'): interest_list.append((str(field.id_field),field.name)) return interest_list except Exception as ex: print("an error in getFieldOfInterestList() : " + str(ex)) return list() 3) the test : @pytest.mark.django_db def testJournals(self): # this query returns 3 fields, previously added in this test (so test database is not empty) print("nb fields = " + str(FieldOfInterest.objects.all().count())) journalForm = JournalForm( initial={ 'journal_name': 'Aquatic Botany', 'journal_fieldOfInterest': 3, }) print("form = " + str(journalForm)) # returns False print("is valid = " + str(journalForm.is_valid())) Printed form should have more options in the select, but only contains the … -
Add `help_text` to Django Admin field
I'm attempting to display an image when editing a user on the admin panel, but I can't figure out how to add help text. I'm using this Django Admin Show Image from Imagefield code, which works fine. However the short_description attribute only names the image, and help_text doesn't seem to add an text below it. How can I add help_text to this field like normal model fields? -
Django Redirect Unauthenticated Users
I've found a lot of older content, but I'm looking for something for v1.11. I'd like all users that are NOT logged in to get redirected to the login page. I've used some middleware in the past. The problem is it's v1.8 and doesn't work well after v1.10. According to the django docs in v2.0 it won't even work anymore. So my proposed question is how do we redirect users that arent authenticated to the login page? -
In python, how to print each list item, unless the item matches one of four criteria?
In Python, I have a list of items. I want to display each item, but I want to exclude items that meet any of four criteria. What is the most efficient way to do this? -
Virtual environment actiavtion
Activating virtual environment in atom text editor it shows error "chcp is not found"enter image description here I have added the screenshot also please help me. -
After POSTing the form and implementing form_valid() method I get "object has no user" error
Good evening. I'm trying to add a blog to the subscription list of a user which is currently logged in. I'm expecting that after I submit a subscription form the values of "user" and "blogs_in_subscription" (it will be taken from a current url from "blog_pk" kwarg) of SubscriptionList model will be automatically populated by the values that I get from form_valid method of my AddBlogToSubList view. But I get this error: File "D:\PyDocs\taskagain\src\blog\models.py" in __str__ 42. return "%s subscription list" % self.user.username File "D:\PyDocs\taskagain\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__ 194. "%s has no %s." % (self.field.model.__name__, self.field.name) Exception Type: RelatedObjectDoesNotExist at /blogs/1/add_to_subscription/ Exception Value: SubscriptionList has no user. The same method works in django official documentation def form_valid(self, form): form.instance.created_by = self.request.user return super(AuthorCreate, self).form_valid(form) I don't understand why it doesn't work in my case. Any help appreciated. models class SubscriptionList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='subscription_list') blogs_in_subscription = models.ManyToManyField(Blog, related_name='in_subscription_lists', blank=True) def __str__(self): return "%s subscription list" % self.user.username`enter code here` views class AddBlogToSubList(CreateView): model = SubscriptionList fields = [] #['user', 'blogs_in_subscription'] template_name = 'blog/add_blog_to_sub_list.html' success_url = reverse_lazy('blog:blog-list') def form_valid(self, form): blog = Blog.objects.get(pk=self.kwargs['blog_pk']) form.instance.blogs_in_subscription.add(blog) form.instance.user = self.request.user return super(AddBlogToSubList, self).form_valid(form) urls urlpatterns = [ url(r'^$', BlogList.as_view(), name='blog-list'), url(r'^(?P<blog_pk>\d+)/$', BlogDetail.as_view(), name='blog-detail'), url(r'^(?P<blog_pk>\d+)/add_to_subscription/$', AddBlogToSubList.as_view(), … -
Pass the id of button from django template to a view
views.py def view_approval(request): utype = request.POST.get('butn') print utype if utype == 'APP': #certain set of funtions if utype == 'SRC': #certain set of funtions else: #certain set of funtions the html page <form name="feedback22" action="{% url 'view_approval' %}" method="post"> {% csrf_token %} <input id="bdyBtn" type="button" name="butn" value="APP" data-toggle="modal" data-target="#appModal" > <input id="bdyBtn" type="button" name="butn" value="SRC" data-toggle="modal" data-target="#srcModal" > </form> I'm having two modals in my html page, used for uploading two excel sheets. The So I created a django view named 'view_approval' and placed the code inside it. The code gets executed depending upon the input button clicked. But the issue is, the value of the input button is not reaching the views. When I printed the value using a print inside the view, it showed a value "None" Thanks in advance!! -
Check if user has certain permissions in Django
I have the following class, named custom_class.py. All i need is a way to check in my views if a certain user is admin, and show some DIVs and if not, hide them. Any help appreciated. class Backend_user: parents = {'Administrator': 'None', 'Supervisor': 'Administrator', 'Operator': 'Supervisor', } childs = {'Administrator': 'Supervisor', 'Supervisor': 'Operator', 'Operator': 'Boss', } def __init__(self, user): self.user = user self.permissions = OrderedDict() self.permissions_plural = OrderedDict() self.permissions_plural['Administrator'] = 'Administrators' self.permissions_plural['Supervisor'] = 'Supervisors' if hasattr(user, "administrator"): self.my_specialty = getattr(user, 'administrator') self.permissions['Administrator'] = True self.permissions['Supervisor'] = True self.permissions['Operator'] = True self.permissions['Boss'] = True elif hasattr(user, "supervisor"): self.my_specialty = getattr(user, 'supervisor') self.permissions['Administrator'] = False self.permissions['Supervisor'] = True self.permissions['Operator'] = True self.permissions['Boss'] = True -
Django test client get returns 404 instead of 200
I'm very new to Django and testing.... I'm testing my app and every time I do threads_page = self.client.get('/threads/1/') it returns a 404 status instead of 200 (that url works, the 1 is the subject id). I found a thread with the same problem and there was a response with the issue (Django test client get returns 404 however works in shell) but I still don't know how to solve it. The problem is that in my views I have a get_object_or_404 with an argument but I don't know how to pass the argument in the test: views.py def threads(request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) return render(request, 'forum/threads.html', {'subject': subject}) This is my test right now def test_check_threads_content_is_correct(self): threads_page = self.client.get('/threads/1/') self.assertEqual(threads_page.status_code, 200) Thank you! -
How do you rename apps in Django1.11 LTS?
How do you rename apps in Django 1.11 LTS? There are suggestions in renaming apps in Django but they are for version <1.11 and are complicated. Anybody knows? -
Extract Products/Prices/Categories/Specs from Amazon Inventory
I am a Django developer and recently I got some project where I need to render Amazon's inventory to Django website. Is there some sort of solution that allows Amazon.com to share their products or do I have to manage it with scrapper? Your help will be much appreciated. -
Django running fine outside Docker but never starts within Docker, how to find issue?
I had a working Django project that had built and deployed many images over the last few weeks. My django project kept working fine when ran as "python manage.py runserver" and the Docker images kept being built fine (all successful builds). However the django app now doesn't deploy. What could be the issue and where should I start to look for it? I've tried the logs but they only say "Starting Django" without actually starting the service I use github and have gone back to previous versions of the code and none of them now work, even though the code is exactly the same. It also fails to deploy the Django server on AWS Elastic Beanstalk infrastructure which is my ultimate goal with this code. start.sh: #!/bin/bash echo Starting Django cd TN_API exec python ../manage.py runserver 0.0.0.0:8000 Dockerfile: FROM python:2.7.13-slim # Set the working directory to /app WORKDIR /TN_API # Copy the current directory contents into the container at /app ADD . /TN_API # COPY startup script into known file location in container COPY start.sh /start.sh # Install requirements RUN pip install -r requirements.txt # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD specifcies the command …