Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
apache failed to start with no error logs
this day i got an issue my apache has failed to restart my django app, i dont know why. and the worst is , it doesnt out with any error log , just blank! this problem make me confuse ,need help. alif@alif-VirtualBox:/var/www/mywebsite/website$ service apache2 restart * Restarting web server apache2 [fail] /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin admin@musicplayer.vhost ServerName www.musicplayer.vhost ServerAlias musicplayer.vhost DocumentRoot /var/www/mywebsite Alias /static /var/www/mywebsite/website/static <Directory /var/www/mywebsite/website/static> Require all granted </Directory> <Directory /var/www/mywebsite/website/website> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mywebsite python-path=/var/www/mywebsite:/var/www/mywebsite/env/lib/python2.7/site-packages WSGIProcessGroup mywebsite WSGIScriptAlias / /var/www/mywebsite/website/website/wsgi.py # Available loglevels: trace8, ..., trace1, debug, info,notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel … -
How can I find all friends whom are NOT a friend of user.first_name = "Daniel" in the following Django Model?
In my Django application, I've got two models, one Users and one Friendships. There is a Many to Many relationship between the two, as Users can have many Friends, and Friends can have many Users. How can I return all friends (first and last name) whom are NOT friends with the user with the first_name='Daniel'? Models.py: class Friendships(models.Model): user = models.ForeignKey('Users', models.DO_NOTHING, related_name="usersfriend") friend = models.ForeignKey('Users', models.DO_NOTHING, related_name ="friendsfriend") created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'friendships' class Users(models.Model): first_name = models.CharField(max_length=45, blank=True, null=True) last_name = models.CharField(max_length=45, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'users' So far, here's what I've tried in my controller (views.py) -- please note, I understand controllers should be skinny but still learning so apologies. What I tried in the snippet below (after many failed attempts at a cleaner method) was to try and first grab friends of daniels (populating them into a list), and then filter them out by their id. # show first and last name of all friends who daniel is not friends with: def index(req): friends_of_daniel = Friendships.objects.filter(user__first_name='Daniel') daniels_friends = [] for friend_of_daniel in … -
how can I update multiple record list from a form in Django 1.9
I have a shipment_details form where have some information about shipment and all item in that order of the shipments. There is two model information one Shipment another is Items model. I want to update all Marco Item Shipped value using the checkbox( see the form view pics). here is my form view http://imgur.com/a/dcNZE Here is my forms.py where I linked up checkbox to Items is_shipped field and this value show in the view using {{form_status.as_p}}. forms.py class ShipmentStatus(forms.CheckboxInput): input_type = 'checkbox' class ShipmentStatusForm((forms.ModelForm)): class Meta: model = Items fields = ['is_shipped'] widgets = { 'is_shipped': ShipmentStatus(), } Here is my view model shipment_detail.html {% extends "_dashboardlayout.html" %} {% block content %} <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h2 class="page-header">Shipment Details</h2> </div> <div class="col-md-12"> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <table class="table table-striped"> <tr> <th>Item No</th> <th>SKU</th> <th>Quantity</th> <th>Price</th> <th>Marco Item</th> <th>Marco Item Shipped</th> </tr> {% for item in items_queryset %} <tr> <td>{{ item.item_no }}</td> <td>{{ item.sku }}</td> <td>{{ item.requested_quantity }}</td> <td>{{ item.price }}</td> <td>{{ item.is_send }}</td> <td>{{ form_status.as_p }}</td> </tr> {% endfor %} </table> <input type="submit" value="Save"> </form> </div> </div> <!-- /.row --> </div> {% endblock %} Here is my control py file def shipment_detail(request, order_id=None): … -
Django user selects multiple images from gallery and saves it as strings in database backend
Im trying to create a form where the user selects from a gallery of images and it saves it to the database. The code below currently renders some radio buttons in the html output. Is there anyway I can change these to images i have saved in a static directory so the user can click on images instead? Would be great if I could change what it saves in the database to what I needed instead of image urls as well. Theres lots of documentation on uploading images but not much I could find on selecting images. Im using django 1.9.7 and python 3.5 models.py client_choices = (('client1', 'Client 1'), ('client2', 'Client 2'), ('client3', 'Client 3'), ('client4', 'Client 4'), ('client5', 'Client 5')) class ClientSelect(models.Model): client = MultiSelectField(choices=client_choices) forms.py from app.models import ClientSelect class ClientSelectForm(forms.ModelForm): class Meta: model = ClientSelect fields = '__all__' views.py class FormWizard(SessionWizardView): template_name = "app/clientchoices.html" #define what the wizard does when its finished collecting information def done(self, form_list, **kwargs): form_data = process_form_data(form_list) return render_to_response('app/about.html', {'form_data': form_data}) urls.py url(r'^clientchoices$', FormWizard.as_view([ClientSelectForm]) , name='clientchoices'), clientchoices.html {% load staticfiles %} {% block content %} <section class="content"> <div class="container"> <div class="fit-form-wrapper"> <h2>Client Choices</h2> <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> {% … -
How to Block a IP address in my network using Django
how to find a other network IP address and i need to block that ip address using django, in my project want to find the other network IP and block that IP to access my system(like server) -
Error when importing files from other apps
I have a project named "analytics".It has two apps->"resources" and "geofences". I have a few .py files in "resources" that I want to import in the "geofences" app's model or views. I am using Django version 1.9.4 and PyCharm version 5.0.5 The name of files I want to import are utilis.py and validations.py When I mention in models of geofence: from resource.validations import * from resource.utilis import * Red lines are shown below these two lines and no methods from these files are accessible in models of geofence. I also tried: from analytics.resources.validations import * but still the result was same. How can I import files from other apps? -
How to add a form as field attribute in a django ModelForm
I have a ModelForm for a Product object set up like this: class ProductForm(forms.ModelForm): compositon_choices = ((2L, u'Calcium (100mg)'), (3L, u'Iron (500mg)')) composition_selection = forms.\ MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=compositon_choices ) class Meta: model = Product fields = [ 'title', 'title_de', 'title_es', 'upc', 'description', 'description_en_gb', 'description_de', 'description_es', 'is_discountable', 'structure', 'unit_type', 'product_concentration',] widgets = { 'structure': forms.HiddenInput() } In the example above I extended the ModelForm with a MultipleChoiceField by adding the composition_selection field (this works): I would like the composoition_selection to be a form itself and not just a MultipleChoiceField: class ProductComponentForm(forms.Form): component_amount = forms.IntegerField() component_name = forms.CharField() and then extend the ModelForm with this new form like this: class ProductForm(forms.ModelForm): composition_selection = ProductComponentForm() class Meta: model = Product fields = [ 'title', 'title_de', 'title_es', 'upc', 'description', 'description_en_gb', 'description_de', 'description_es', 'is_discountable', 'structure', 'unit_type', 'product_concentration',] widgets = { 'structure': forms.HiddenInput() } But I cannot get this to work. This ProductForm that I want to create never gets rendered,and nothing appears. Am I doing something wrong or missing something? What would be the best way to extend a ModelForm with a SubForm? -
django doesn't show ValidationError
I have a problem: when i try to login with information that doesn't get validated, the page is just refreshes, and nothing happens. My goal is to pop up any validation error, but they literally refuse to appear. Could you please check my code, and help me to find out what to do. template <form method="post" action=""> {% csrf_token %} {% bootstrap_form_errors form %} {% bootstrap_form form %} <input type="hidden" name="next" value="{{ request.path }}"> <input type="submit" value="Войти"> </form> form class LoginForm(forms.ModelForm): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class Meta: model = CustomUser fields = ('username', 'password') def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: user = authenticate(username=self.cleaned_data.get('username'), password=self.cleaned_data.get('password')) if user is None: raise ValidationError('Неверное имя пользователя или пароль') if username is None or password is None: raise ValidationError('Неверные данные') return self.cleaned_data view class LoginView(FormView): form_class = LoginForm template_name = 'user/login.html' def get_success_url(self): return self.request.META.get('HTTP_REFERER') def get_context_data(self, **kwargs): ctx = super().get_context_data() ctx['form'] = self.form_class return ctx def form_valid(self, form): user = authenticate(username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password')) login(self.request, user) return super().form_valid(form) def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated(): return redirect('post-list') return super().dispatch(request, *args, **kwargs) -
Django+Nginx+Gunicorn how to run cgi scipts
I have a Django app deployed on digitalocean, it only provides RESTful API, nothing more. I need to add some payment gateway integration into my webservice, the payment gateway send a callback and I want to execute a .cgi script as a result. From the research I did, I haven't found any reference to achieve that with gunicorn, I have experimented with uWSGI for quite a few hours but was not able to get anywhere. So my question is what are my options here ? Shall I move away from gunicorn OR shall I ditch nginx all together for Apache as it seems to handle CGI requests by default. This is a production server so I am trying to be very careful about my options. -
How to average and compress data using django?
This class has volts & frequency that are calculated every minute. I want to take the average of each (volts, frequency ... etc) every 15 minutesof the recorded data and time ]. Should I do it in SQL or it can be done by django? class LogsN (models.Model): syv = models.ForeignKey (smodel.Syved, related_name='%(class)s') data = models.ForeignKey (smodel.Data, related_name='%(class)s') val = models.FloatField (null=True, blank = True) timestamp = models.DateTimeField () objects = AccessManager() -
Error decoding signature in Django Rest Framework
I use JWT in my API. But I can't authenticate with JWT. What is the problem I couldn't find. Thanks for your helps. @api_view(['POST']) @permission_classes((AllowAny,)) def UserLogin(request): try: username = request.POST.get('username', None) password = request.POST.get('password', None) account = authenticate(username=username, password=password) except (User.DoesNotExist, User.PasswordDoesNotMatch): return Response({'message': 'Wrong credentials'}, status=400) if account is not None: if account.is_active: login(request, account) if request.user.is_superuser: user_type = '0' elif request.user.is_instructor(): user_type = '1' elif request.user.is_student(): user_type = '2' else: user_type = '3' payload = { 'user_type': user_type, 'username': username, 'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS) } jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) return Response({'token': jwt_token.decode('utf-8')}) Payload data returns { "user_type": "0", "username": "bus", "exp": 1475480008 } It is enough for me. But when I request Other API url, It returns { "detail": "Error decoding signature." } -
Model in Django 1.9. TypeError: __init__() got multiple values for argument 'verbose_name'
I have Python 3.5 and Django 1.9 try to do the next class Question(models.Model): def __init__(self, *args, question_text=None, pub_date=None, **kwargs): self.question_text = question_text self.pub_date = pub_date question_text = models.CharField(max_length=200, verbose_name="Question") pub_date = models.DateTimeField('date_published', verbose_name="Date") def __str__(self): return self.question_text def __unicode__(self): return self.question_text class Meta: verbose_name = "Question" But got an error File "/home/donotyou/PycharmProjects/djangobook/polls/models.py", line 15, in Question pub_date = models.DateTimeField('date_published', verbose_name="Date") TypeError: init() got multiple values for argument 'verbose_name' Please help -
Django: Testing if the template is inheriting the correct template
In django you can test weather your view is rendering correct template like this def test_view_renders_correct_template(self): response = self.client.get("/some/url/") self.assertTemplateUsed(response, 'template.html') but what if you want to test if the used template is extending/inheriting from the correct template. -
How to implement a basic login, Registration and logout in Django?
Basic Authentication Process coding using Django. Like Login, Registration and Logout. The following are my steps for creating a site where you can: Log in using your email address Register with email verification. View and edit your user profile. -
What is verbose in django and why we use it?
i am using verbose in my project but i am not familiar with verbose and don't know why we use it . I just copy a code from net to my view file.. Please tell me what is the exact usage of verbose. -
Celry tasks not calling post_save revceiver function. Django
I have one table 'notification', in which storing notification messages.I have written a post_save handler function which will be called when signal raises. I am storing data in this table by celery task, but this task is not calling this receiver function. @receiver(post_save, sender=Notification) def send_push_notifications(sender, **kwargs): """ """ message = kwargs["instance"] push_notifications = MobilePushNotifications(message_object=message) Please help me to solve this problem. Thanks in Advance -
AWS Route53 - Site not working. Works when opened using public IP
I have a basic Django website running on an AWS EC2 instance. Command I use to run server: python3 manage.py runserver 0.0.0.0:8000 Website is accessible when I used the public IP of the EC2 instance in the browser. Next step I tried was to set up DNS using AWS Route53. Created a hosted domain as shown here - Hosted Domain I have added record sets for www.mysite.com. and mysite.com. My domain is registered with namecheap.com and I have added the 4 name servers shown in my hosted domain to it in the custom DNS section under name servers. The state of my domain on https://www.whatsmydns.net/#A/mysite.com looks good. I have created a health check under route53 and it shows red. The website is not accessible when I type in www.mysite.com in the browser. What am I missing here? Please advise. -
How to implement django search help popup for a form?
Sometimes I have hundreds of values in my form dropdown I usually try to have a list of values with filter and paging and from this list I select value I use in my form. But Sometimes it is more than one value with huge dropdowns to select in the same form so my way is not working. I am currently looking into django-popup-formsto solve my problem I am implementing my search list functionality in popup and will try to bring it back to the form. However I am not sure that I am reinventing the wheel.(but cant find anything with google) Is there any solutions batteries included I can reuse in django? -
Using AJAX GET to generate CSRF protected forms in a cached page
I have pages that use excessive time in database access and slow template processing so I had to use caching using django-cacheops that uses Redis. Now since I have POST forms that use csrf tokens, these values will be cached too. I've been thinking to implement the following solution but I am not still sure if it is a wise one. GET the cached page without any forms. Initiate a small script embedded in the cached page with AJAX GET request to load the form if the user is logged in. Is this approach secure and wise? If so How can I know using Javascript/jQuery and cookies that I'm a logged user (i.e. How can I differentiate between the users and visitors in client side like request.user.is_authenticated() in server side)? -
Django filter when current time falls between two TimeField values
I am storing an object in my DB with a timefield like so: class MyClass(models.Model): start_time = models.TimeField(null=True, blank=True) stop_time = models.TimeField(null=True, blank=True) The idea here is that when querying an endpoint, the server will return only objects where the current time is between the start_time and stop_time. NB: start_time and stop_time are arbitrary times of the day, and can span across midnight, but will never be more than 24hr apart. I have tried currentTime = datetime.now().time() MyClass.objects.filter(stop_time__gte=currentTime, start_time__lte=currentTime) but this does not account for when the times span midnight. I'm sure there must be a simple solution to this, but web search has left me fruitless. Does anyone know a good way to do this? -
How to get username from Django Rest Framework JWT token
I am using Django Rest Framework and i've included a 3rd party package called REST framework JWT Auth. It returns a token when you send a username/password to a certain route. Then the token is needed for permission to certain routes. However, how do I get the username from the token? I've looked all through the package documentation and went through StackOverflow. It is a JSON Web Token and I am assuming there is a method like username = decode_token(token) but I haven't found such a method. -
Does Django refresh session_key out of the box?
When using Django sessions out of the box, Does Django offer automatic/timed session_key renewal? (e.g. calling session.cycle_key) In order to mitigate the possibility of session fixation attacks? Or am I gonna have to do this myself? If so, any recommended links/guides to this matter of renewing session keys? -
Import error: No module named Include in Python Django
I am a beginner in Python. The Python version is 2.7. When I run the below command (test) C:\virtualenvs\test> python manage.py runserver under a virtual environment I get an error saying File "C:\virtualenvs\test\lib\site-packages\django\apps\config.py", line 90, in create Module = import_module(entry) File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module__import__(name) ImportError: no module named Include Any help is highly appreciated. -
Limiting dropdown in the form for subset of data even after validation
I have my payment view in this view I perform payment for certain lease term assigned to the lease. My form has following fields class LeasePaymentForm(forms.ModelForm): class Meta: model = LeasePayment fields = [ 'leaseterm', 'amount', 'payment_date', 'description'] in my view I populate allow to select LeaseTerm only from lease terms assigned to the lease def payment_new(request,pk,uri): lease = get_object_or_404(Lease, pk=pk) title = 'payment' uri = _get_redirect_url(request, uri) if request.method == "POST": form = LeasePaymentForm(request.POST) if form.is_valid(): payment = form.save(commit=False) payment.lease = lease payment.save() messages.add_message(request, messages.SUCCESS, str(payment.id) + "-SUCCESS Object created sucssefully") return redirect(uri) else: form = LeasePaymentForm() form.fields['leaseterm'].queryset = LeaseTerm.objects.filter(lease=lease) return render(request, 'object_edit.html', {'form': form, 'title': title, 'extend': EXTEND}) however if user will not select the leaseterm after validation all the leaseterms will be displayed in dropdown. Is there a way to make the form behave in same way as before the validation? -
Django: request.user.is_authenticated() returning true in Template, but false in View
I am writing a simple login/logout form using Django form, and other packages. In my logout, view this is what I have, but it appears that request.user.is_authenticated() is always returning false, because it always goes to the else statement. def logout_view(request): try: if request.user.is_authenticated(): logout(request) return HttpResponseRedirect("registration:login") else: return HttpResponse("User was never signed in") except: return HttpResponse("User was never logged in") However, in my template.py, request.user.is_authenticated works fine. It returns "I am logged in", so why is it that my view one returns false? Thanks For the help :D <h1>Home Page</h1> {{ user.username }} <form action="{% url 'registration:logout'%}" method="POST"> {% csrf_token %} {% if request.user.is_authenticated %} <p>I'm logged in</p> {% else %} <p>I am anonymous</p> {% endif %} <input type="submit" value="Log out"/> </form> Also, here is my urls.py from . import views app_name = 'registration' urlpatterns = [ url(r'^test', views.login, name='test'), url(r'^login/', views.login_view, name='login'), url(r'^signup/(?P<user_id>[0-9]+)/$',views.signup,name='signup'), url(r'^logout/',views.logout_view,name='logout'), url(r'^update/(?P<userNet_id>[0-9]+)?',views.updateProfile,name='update'), url(r'^home/(?P<userNet_id>[0-9]+)?',views.homePage,name='home'), ]