Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get and verify Datefield in Django form before form.save - CreateView
I have model as below, as user can't have new project if his projects' work_times >= 8 hours on a day, the purpose is to warn or remind users when they create new project , and I've got a field in one model like by this: User.objects.annotate(total_times=Sum('projects__work_times', filter=Q(projects__date=some_date))).filter(total_times__gt=8) The partial code of models.py as below, I can get one day's value, but how to get and verify Datefield in Django CreateView form before form.save? I would like to know how to define some_date? how to define the date? if I wrote like this:date=self.request.date, will get a error of 'WSGIRequest' object has no attribute 'date' class Project(models.Model): date = fields.DateField(auto_now=False) user = models.ManyToManyField(User, related_name="projects", blank=True) work_times = models.FloatField(default=1, verbose_name="work times(hours)") class ProjectCreateView(CreateView): model = Project form_class = ProjectForm def form_valid(self, form): # Is it right if I verify date here? # how to define the date? not date=self.request.date project = form.save(commit=False) project.save() form.save_m2m() Thanks so much for your help! -
Currently File in form does not save
I have a formset with a group model and the group members form. I want to give the option of edit the group but when I save the group, the form is not valid because it have to upload the file field even when it says there is a currently file. What I have to do to save the edit form without upload the file when it is no necessary? Here is the view class editGroup(CreateView): model = Group fields = ['group'] labels= {'grupo': 'Group Name' } template_name= "pfapp/editgroup.html" success_url = reverse_lazy('profile-list') def __init__(self): groupname = Group.objects.filter(id=grupo_selec) editGroup.initial={'group': groupname[0]} def get_context_data(self, **kwargs): members = GroupMembers.objects.filter(groupid_id=grupo_selec) GroupMemberEditFormSet = inlineformset_factory(Group, GroupMembers, form=GroupMemberForm, extra=len(members)) data = super(editGroup, self).get_context_data(**kwargs) if self.request.POST: data['groupmembers'] = GroupMemberEditFormSet(self.request.POST or None , self.request.FILES or None) else: try: data['groupmembers'] = GroupMemberEditFormSet(initial=[{'nombreint': members[i].nombreint , 'correoint': members[i].correoint, 'foto1':members[i].foto1, 'foto2':members[i].foto2 } for i in range(0,len(members))]) except (ObjectDoesNotExist, MultipleObjectsReturned): pass return data def form_valid(self, form): context = self.get_context_data() groupmembers = context['groupmembers'] with transaction.atomic(): form.instance.user = self.request.user if groupmembers.is_valid(): groupmembers.instance = self.object idgroup=Group.objects.only('id').get(id=grupo_selec) members = GroupMembers.objects.filter(groupid_id=grupo_selec) i=0 for f in groupmembers: nombreint = f.cleaned_data['nombreint'] correoint= f.cleaned_data['correoint'] foto1= f.cleaned_data['foto1'] foto2= f.cleaned_data['foto2'] if i<len(groupmembers): data=GroupMembers.objects.get(correoint=members[i].correoint) data.nombreint=nombreint data.correoint=correoint data.foto1=foto1 data.foto2=foto2 data.groupid=idgroup data.save() else: member = GroupMembers(groupid=idgroup, nombreint = … -
Django utf8 DatabaseError occurred when a database character set already set to utf8mb4
Each time I edit a model with string attributes then migrate, the error comes. But the character set of the database and its tables already set to utf8mb4. For example, I wanted to add "related_name" to authors field, the error occurred. class Book(models.Model): title = models.CharField(max_length=255) pub_date = models.DateField() publisher = models.CharField(max_length=255) language = models.CharField(max_length=255) print_length = models.DecimalField(max_digits=6, decimal_places=0) price = models.DecimalField(max_digits=10, decimal_places=2) authors = models.ManyToManyField(Author, related_name='by') def __str__(self): return self.title Error: django.db.utils.DatabaseError: (3719, "3719: 'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous.", None) Database status: mysql> show create database eShop; +----------+----------------------------------------------------------------------------------------------+ | Database | Create Database | +----------+----------------------------------------------------------------------------------------------+ | eShop | CREATE DATABASE `eShop` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ | +----------+----------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) How can I fix this issue? -
Heroku uninstalling Pillow?
I was getting the error n heroku when trying to upload a field: ModuleNotFoundError No module named 'PIL' Full traceback: 2018-08-16T01:12:18.364616+00:00 app[web.1]: Internal Server Error: /admin/app/neighborhood/add/ 2018-08-16T01:12:18.364628+00:00 app[web.1]: Traceback (most recent call last): 2018-08-16T01:12:18.364630+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner 2018-08-16T01:12:18.364632+00:00 app[web.1]: response = get_response(request) 2018-08-16T01:12:18.364634+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response 2018-08-16T01:12:18.364635+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2018-08-16T01:12:18.364637+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response 2018-08-16T01:12:18.364639+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2018-08-16T01:12:18.364641+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/options.py", line 607, in wrapper 2018-08-16T01:12:18.364642+00:00 app[web.1]: return self.admin_site.admin_view(view)(*args, **kwargs) 2018-08-16T01:12:18.364644+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view 2018-08-16T01:12:18.364646+00:00 app[web.1]: response = view_func(request, *args, **kwargs) 2018-08-16T01:12:18.364647+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func 2018-08-16T01:12:18.364649+00:00 app[web.1]: response = view_func(request, *args, **kwargs) 2018-08-16T01:12:18.364651+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner 2018-08-16T01:12:18.364653+00:00 app[web.1]: return view(request, *args, **kwargs) 2018-08-16T01:12:18.364654+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1647, in add_view 2018-08-16T01:12:18.364656+00:00 app[web.1]: return self.changeform_view(request, None, form_url, extra_context) 2018-08-16T01:12:18.364657+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper 2018-08-16T01:12:18.364659+00:00 app[web.1]: return bound_method(*args, **kwargs) 2018-08-16T01:12:18.364660+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view 2018-08-16T01:12:18.364662+00:00 app[web.1]: response = view_func(request, *args, **kwargs) 2018-08-16T01:12:18.364664+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1536, in changeform_view 2018-08-16T01:12:18.364665+00:00 app[web.1]: return self._changeform_view(request, object_id, form_url, extra_context) 2018-08-16T01:12:18.364667+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1568, in _changeform_view 2018-08-16T01:12:18.364668+00:00 app[web.1]: … -
django-paypal valid_ipn_received is never called
I am trying to integrate django-paypal to my website and I can't seem to make the valid_ipn_received to work. mainApp/urls.py urlpatterns = [ path('paypal/', include('paypal.standard.ipn.urls')), ] mainApp/settings.py INSTALLED_APPS = [ ... 'paypal.standard.ipn', 'payment.apps.PaymentConfig' ... ] PAYPAL_RECEIVER_EMAIL = "Jeremy.aube-liveserver@live.com" PAYPAL_TEST = True payment/apps.py from django.apps import AppConfig from paypal.standard.ipn.signals import valid_ipn_received class PaymentConfig(AppConfig): name = 'payment' def ready(self): from .hooks import payment_received valid_ipn_received.connect(payment_received) payment/hooks.py @csrf_exempt def payment_received(sender, **kwargs): ipn_obj = sender try: invoice = models.Invoice.objects.get(pk=ipn_obj.invoice) except: return if ipn_obj.payment_status == ST_PP_COMPLETED: # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != utils.get_paypal_buisness_email(): invoice.status = models.Invoice.CANCELED invoice.save() return price = invoice.amount if ipn_obj.mc_gross == price and ipn_obj.mc_currency == 'CAD': invoice.status = models.Invoice.DONE else: invoice.status = models.Invoice.CANCELED invoice.save() else: invoice.status = models.Invoice.CANCELED invoice.save() Code when creating the paypal form paypal_dict = { "business": utils.get_paypal_buisness_email(), "amount": invoice.amount, "item_name": "Registration Fees", "invoice": str(invoice.pk), "currency_code": "CAD", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('payment:done')), "cancel_return": request.build_absolute_uri(reverse('payment:canceled')), } form = PayPalPaymentsForm(initial=paypal_dict) utils.get_paypal_buisness_email() returns the buisness email as a string. When I see that the sever receives a POST from Paypal but nothing happens after … -
Django google app engine No such file or directory
I have django (2) with python 3.6 site in google cloud, the app is in app engine flex. (my first app :) My app has an upload page, where Iam asking the user upload a JSON file (that is never keep in the site), what i do is open it and generate another file from it I know that django depending on the size of the file it goes into memory but I was never able to use this functionality, so what I did in local env, was creating a folder that I called, temp_reports, so I created the files here, uploaded them into a bucket and then delete them, from temp_reports. So I was thinking, as the site is already in gcloud, if I can directly create this files into the bucket? or do i still need to generate them in the site and then upload them? Now if it is from my site I keep getting the following error: Exception Value: [Errno 2] No such file or directory: '/home/vmagent/app/temp_reports/file_516A3E1B80334372ADB440681BB5F030.xlsx I had in my app.yaml handlers: - url: /temp_reports static_dir: temp_reports Is there something I am missing? in order to use temp_reports? Or how can i create a file … -
Django Inlineformset forms primary keys error
So, I have this view on my project, it is for saving a formula of a product, in it I have two forms, the Formula, and the Lines of the formula (Formula_materia). The problem is that when I try to update the inline formset it throws a form validation error. It does not recognize the primary key, and says the field is empty (It is AutoField, and it is not rendered on the form). I searched all web, but couldn't find a answer that helps me. Error : pkid_formula_materia (This field is required) Maybe an error on the view ? view (I know it is big and confusing, sorry): def formula_produto(request, id_produto): produto = Produto.objects.get(pkid_produto=id_produto) # Checks if there is already a formula to that product try: Formula = Formulaproduto.objects.get(fkid_produto=id_produto) except: Formula = None # Makes the formset based on two models formset_materias = inlineformset_factory(Formulaproduto,Formula_materia,extra=0,min_num=1,form=Formula_materiaForm) if request.POST: with transaction.atomic(): form_formula = FormulaprodutoForm(request.POST, instance=Formula) if form_formula.is_valid(): formula = formula.save(commit=False) formula.fkid_produto = produto formula.save() # Use as instance the existing Formula or the newly created if Formula and Formula != None: forms_materia = formset_materias(request.POST, instance=Formula) else: forms_materia = formset_materias(request.POST, instance=formula) for form in forms_materia: if form.is_valid(): # Here it does not validate … -
Django - cannot fill form with leaflet 0.7.7 js source
As long as I use this leaflet js source in my html: <script src="https://unpkg.com/leaflet@0.7.7/dist/leaflet.js" async></script> I am not able to fill my Django forms anymore. What is the reason? I need this version of leaflet (0.7.7). Thanks -
Django Ajax adding data to POST
I'm using ajax to submit a form and some extra data. I can see the all the data coming through in console.log but my view is failing, it's not grabbing the extra data. page.html //AJAX get location function function get_location(form) { var data = form.serializeArray(); data.push({ {% if form.instance.id %}id: {{form.instance.id}},{% endif %} city : itemCity, state : itemState, country :itemCountry, lat : itemLat, lng : itemLng }); console.log(data); $.ajax({ url : "{% url 'posts:ajax_location' %}", type : 'POST', data : data, success : function(json) { console.log('success call') if (json['status'] = 'Update Post') { $(location).attr('href', json['url']); } ... views.py def ajaxSetPostLocation(request): if request.method == 'POST': if request.is_ajax(): city = request.POST.get('city', None) state = request.POST.get('state', None) country = request.POST.get('country', None) lng = request.POST.get('lng', None) lat = request.POST.get('lat', None) pk = request.POST.get('id', None) response_data = {} Is there a different way to grab data from an array? -
Django Rest Framework Serializer add elements to Meta.fields
I have a custom serializer class that I created copying the answer to this question, but in this example the fields parameter replaces original Meta.fields attribute, and what I want is to add new elements to Meta.fields. Is there any way this can be done? This is my serializer: class DynamicModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): fields = kwargs.pop('fields', None) add_fields = kwargs.pop('add_fields', None) exclude = kwargs.pop('exclude', None) nest = kwargs.pop('nest', None) if nest is not None: self.Meta.depth = nest super(DynamicModelSerializer, self).__init__(*args, **kwargs) if fields is not None: allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) if exclude is not None: for field_name in exclude: self.fields.pop(field_name) -
How would changing Django's cookie domain settings cause sporadic CSRF failures?
In my Django project, until recently I had left the settings SESSION_COOKIE_DOMAIN and CSRF_COOKIE_DOMAIN unset. Recently I changed them to .mydomain.com and since then I have been seeing sporadic CSRF failures on AJAX requests for certain users. The failure manifests as a 403 with CSRF token missing or incorrect. appearing in the logs. Asking users to clear cookies seems to resolve the issue, but I'm wondering how the settings change could have caused this and why it only seems to be happening for some users and not others. -
Django: page not found error
I got the following error in my Django starting page: Here is the views.py and urls.py under polls: polls/views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") polls/urls.py from django.urls import path from . import views from django.conf.urls import include, url urlpatterns = [ path('', views.index, name='index'), # path('', views.search, name='search'), ] and error: Any idea what might be wrong? Thanks! -
Java login to Aristotle Metadata Registry
I'm trying to write a Java app to query data in an Aristotle Metadata Registry instance. I eventually plan to query for entry points that provide JSON output for my app to work on. To get started I have to login to Aristotle. When I look at the Aristotle console for a regular web user logging in I see this sequence: [15/Aug/2018 21:16:59] "GET /login?next=/account/home HTTP/1.1" 200 7098 [15/Aug/2018 21:16:59] "GET /static/COMPILED/aristotle_mdr/login.css HTTP/1.1" 200 784 [15/Aug/2018 21:17:08] "POST /login HTTP/1.1" 302 0 [15/Aug/2018 21:17:08] "GET /account/home HTTP/1.1" 200 16379 [15/Aug/2018 21:17:08] "GET /static/aristotle_mdr/bootstrap/css/bootstrap.min.css HTTP/1.1" 200 122241 [15/Aug/2018 21:17:08] "GET /static/aristotle_mdr/bootstrap/js/bootstrap.min.js HTTP/1.1" 200 37340 [15/Aug/2018 21:17:08] "GET /static/COMPILED/aristotle_mdr/aristotle.visuals.css HTTP/1.1" 200 1320 [15/Aug/2018 21:17:08] "GET /static/COMPILED/aristotle_mdr/aristotle.css HTTP/1.1" 200 6957 [15/Aug/2018 21:17:08] "GET /static/aristotle_mdr/bootstrap.wcag.css HTTP/1.1" 200 656 [15/Aug/2018 21:17:08] "GET /static/aristotle_mdr/pink.wcag.css HTTP/1.1" 200 1231 [15/Aug/2018 21:17:08] "GET /static/aristotle_mdr/aristotle.js HTTP/1.1" 200 1647 [15/Aug/2018 21:17:08] "GET /static/bootstrap3_datetime/bootstrap-datetimepicker.min.css HTTP/1.1" 200 7785 [15/Aug/2018 21:17:08] "GET /static/bootstrap3_datetime/moment.min.js HTTP/1.1" 200 61317 [15/Aug/2018 21:17:08] "GET /static/bootstrap3_datetime/bootstrap-datetimepicker.min.js HTTP/1.1" 200 38514 [15/Aug/2018 21:17:08] "GET /static/aristotle_mdr/aristotle.notify.js HTTP/1.1" 200 3848 [15/Aug/2018 21:17:08] "GET /static/COMPILED/aristotle_mdr/aristotle.dashboard.css HTTP/1.1" 200 2506 I'm not trying to reproduce loading .js and .css, but trying to copy the other GETs and POSTs. My test program produces these results: [15/Aug/2018 21:22:53] "GET … -
In Django Factory Boy, is it possible to mute a specific receiver (not all signals)?
In our Django project, we have a receiver function for post_save signals sent by the User model: @receiver(post_save, sender=User) def update_intercom_attributes(sender, instance, **kwargs): # if the user is not yet in the app, do not attempt to setup/update their Intercom profile. if instance.using_app: intercom.update_intercom_attributes(instance) This receiver calls an external API, and we'd like to disable it when generating test fixtures with factory_boy. As far as I can tell from https://factoryboy.readthedocs.io/en/latest/orms.html#disabling-signals, however, all one can do is mute all post_save signals, not a specific receiver. At the moment, the way we are going about this is by defining an IntercomMixin which every test case inherits from (in the first position in the inheritance chain): from unittest.mock import patch class IntercomMixin: @classmethod def setUpClass(cls): cls.patcher = patch('lucy_web.lib.intercom.update_intercom_attributes') cls.intercomMock = cls.patcher.start() super().setUpClass() @classmethod def tearDownClass(cls): super().tearDownClass() cls.patcher.stop() However, it is cumbersome and repetitive to add this mixin to every test case, and ideally, we'd like to build this patching functionality into the test factories themselves. Is there any way to do this in Factory Boy? (I had a look at the source code (https://github.com/FactoryBoy/factory_boy/blob/2d735767b7f3e1f9adfc3f14c28eeef7acbf6e5a/factory/django.py#L256) and it seems like the __enter__ method is setting signal.receivers = []; perhaps this could be modified so that … -
Django + gunicorn + nginx: 502 bad gateway but sometimes only?
I recently decided to just give up on apache2 + mod_wsgi and give a try to gunicorn + nginx to run my Django App. I followed those tutorials with no issue at all, on a clean Ubuntu 16.04 install: https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04 https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#create-a-gunicorn-systemd-service-file I thought that everything would be fine, but when browsing my website, I noticed that from time to time a few pages did not display at all and just show a 502 Bad Gateway error. Looking into the error/var/log/nginx/error.log, I only have errors like the following: upstream prematurely closed connection while reading response header from upstream I have no clue on what it implies: why would it be my Django install, if I have no issues when running on localhost for instance? also: sometimes all pages work and display just fine; sometimes the sames pages will throw a 502 error :( how could I know what's wrong with my gunicorn install, if the issue comes from there? How to debug? For you information: /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myself Group=www-data WorkingDirectory=/home/myself/django/myproject ExecStart=/home/myself/django/myproject/venvprod/bin/gunicorn \ --access-logfile - \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-enabled/myproject server { server_name mysite.fr mysite.com; location … -
how to use sed command to extract DB information?
I am trying to make bash file that runs inside my Dockerfile and also that has my Django DB connection information. My db is already deployed remotely. My questions is... I am not sure I doing it right way to write my bash scripting(start.sh) and how do i use sed to extract the DB info in my settings.py? Thank you! I have DB connection info in my Django settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myDB', 'USER': 'myUser', 'PASSWORD': 'myPW', 'HOST': '0.0.0.0', 'PORT': '1234', } } Dockerfile FROM python:3 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip3 install --upgrade pip RUN pip3 install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 ENTRYPOINT ["python ./manage.py" , "./start.sh"] CMD ["runserver", "0.0.0.0:8000"] start.sh (I am trying to modify this template i got from Stackoverflow) #!/bin/bash # this script is run when the docker container is built PGDATABASE="myDB" PGHOST="0.0.0.0" PGUSER="myUser" PGPASSWORD="myPW" DB_LOCATION="../app/settings.py" echo "*** CREATING DATABASE ***" # create default database gosu postgres postgres --single <<EOSQL CREATE USER '$PGUSER'@'$PGHOST' IDENTIFIED BY '$PGPASSWORD' CREATE DATABASE "$PGDATABASE"; GRANT ALL PRIVILEGES ON DATABASE "$PGDATABASE" TO $PGUSER; EOSQL # clean sql_dump - because I want to have a one-line command # remove indentation sed "s/^[ \t]*//" -i … -
Image not saved to storage when loading with picasso
I have an application that syncs it's database with a Django server using the Django rest framework. I am able to upload images to the server. The problem is if an image is uploaded from another device or through the web app directly. When I try to re-sync using the "since" filter it shows that it is calling to GET the image (not made on the current device), but it is never saved. The only way that I found to fix it is to clear android cache and start an initial sync with the server. I am using Picasso to load images into a new Target: private void saveImage(final String url){ Picasso.get().load(url).into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { try { String root = Environment.getExternalStorageDirectory().toString(); File directory = new File(root + "/instrumentImages"); if (!directory.exists()) { directory.mkdirs(); } String fileName = url.substring( url.lastIndexOf('/')+1, url.length() ); //String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.')); directory = new File(directory, fileName); FileOutputStream out = new FileOutputStream(directory); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch(Exception e){ Log.v("ActionSync", "Failed to save or load image."); } } I do not understand why it wouldn't be able to save the image if I am getting the URL. If I … -
Django queryset where a field values are in a list
I need to make a query that returns all rows where the field subject values exist in a list. I don't matter with sensitive case, but the values should be exact with the ones in the list. I'm using: my_list = ["Others", "Entertainment"] results = MyObject.objects.filter(subject__iregex=r"(" + "|".join(my_list) + ")") This is the solution from the topic Django query case-insensitive list match but as result I have rows where: subject = "others tv series" and I just want rows like: subject = "others" I need something like iexact and in mixed. Thanks! -
Implement a Scrum Board App in Django
I've been asked to implement as a group project a Django web app for a Scrum Board and I'm not familiar to Django nor Python. How can I do it? Do you have exhaustive guides? Which views/models I have to implement? Thanks in advance. -
Django using has_change_permission to determine owner
I want to restrict other user to change object instance other then owner user. For that I am using has_change_permission admin model function but It is not working. My model: class Book(models.Model): author = models.ForeignKey(User, related_name = 'book_author') ... In my admin.py class BookAdmin(admin.ModelAdmin): def has_change_permission(self, request, obj): if request.user.is_super_user(): return True elif request.user == obj.author: return True else: return False if obj is None: return False In my views.py class BookUpdate(generic.UpdateView): model = Book form_class = BookUpdateForm template_name = 'accounts/book_update.html' def get_object(self, *args, **kwargs): return Book.objects.get(id=self.kwargs.get('id')) In my urls: url(r'^update_book/(?P<id>[\w-]+)/$', views.BookUpdate.as_view(),name='update_book') Now when any one goes to this url pattern can edit book, but I need that only author can edit this book. Is has_change_permission right way to do so, or any other better way ? -
Python Requests Deployment
In on of my Django view´s I am making a request to another webserver via requests, this code works perfect when I run the code with the development server. It looks like that: import requests r = requests.post('http://www.example.org') return r.text But when I Deploy this an apaches www-data user is running it it throws this error: ConnectionError HTTPConnectionPool(host='www.example.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f23e917ba58>:Failed to establish a new connection:[Errno -2] Name or Service not known')) But I can run the code as root user from a seperate script on the Deployment server without a problem this is why i think it is a permission problem. But i have no Idea how to solve this. Thanks in advance! -
How to set up OrientDB PyOrient OGM with Django?
I am having difficulties in connecting Django with Orientdb PyOrient OGM. I have set the following connection strings and initialisation methods in my settings.py file in Django. # PYORIENT DB SETTINGS DJANGORIENT_SETTINGS = { 'host': 'localhost', 'port': '2480', 'username': 'xxxx', 'password': 'xxxxxxxxxx', 'name': 'authdb' } from pyorient.ogm import declarative Node = declarative.declarative_node() Relationship = declarative.declarative_relationship() but I am unable to connect to the database via my models.py file from pyorient.ogm.property import * from .settings import Node class Car(Node): registration = String(unique=True) colour = String() Any advice on how to connect the two technologies? -
have django setup to use /django/ path from http://localhost/django/
I have this WSGIScriptAlias /django/ /path/to/app in my Apache2 virtualhost config. I used django-admin startproject myapp to create the project. But when I go to http://localhost/django/ I get a 404 error via Django If I change the virtualhost config to just / and restart apache2. It works but I use that for other things hence the reason for virtualhost and /django/ sub-path. But it seems that Django is working just not from the correct path. Page not found (404) Request Method: GET Request URL: http://localhost/django/ Using the URLconf defined in djangoexamplecom.urls, Django tried these URL patterns, in this order: ^admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I am guessing when running django-admin startproject it expects the app to run at default URL i.e. http://localhost/ no sub-path? Do I need to edit url.py or settings.py to use /django/? -
PyCharm: Options of non-pure python project (e.g. Django) not available
I am trying to create Django project. According to the tutorial, the possible selections like below should show up when I try to create a new project: However, when I did File -> New Project, the window I got was: Any idea what was missing? Thanks! -
How to know the value of pk in django models
i am learning Django right now and i want to get a table with my "database" and the id/pk of each row of info. right now i have this: Model: class Car(HistoryBase): plate = models.CharField(max_length=6, default='', verbose_name="Placa") year = models.CharField(max_length=4, null=True, blank=True, default='', verbose_name="Año del auto") model = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name="Modelo del auto") brand = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name="Marca del auto") color = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name="Color del auto") Form: from ..core.forms import BootstrapModelForm from .models import Car class CarModelForm(BootstrapModelForm): class Meta: model = Car fields = '__all__' View: from django.views.generic.edit import CreateView from .models import Car from .forms import CarModelForm class CarDetailView(CreateView): template_name = "cars_detail.html" http_method_names = [u'get', u'post', ] form_class = CarModelForm model = Car success_url = '/autos/{}' def _get_car(self, *args, **kwargs): try: pk = int(self.kwargs.get('pk')) return Car.objects.get(pk=pk) except Exception: return None Template: <div class="col-sm-12"> <div class="card"> <div class="card-body"> <div class="card-title"><h2>Listado de Autos</h2></div> <hr> <table id="tabla" class="table table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> <th>Numero</th> <th>Placa</th> <th>Marca</th> <th>Modelo</th> <th>Color</th> </tr> </thead> <tbody> {% for object in object_list %} <tr> **<td>{{ object.object_instance.pk }}</td>** <td>{{ object.plate }}</a></td> <td>{{ object.brand }}</td> <td>{{ object.model }}</td> <td>{{ object.color }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> when i …