Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add filename to formset for display purpose only
I have a model which contains a number of user uploaded files that other than the file itself also contain a description and some other meta information. class ArchiveFile(models.Model): archive_file = models.FileField(upload_to=grab_archive_folder, default=None, blank=False) description = models.CharField(max_length=255) What I want is for a user to (1) upload new files. And (2) be able to edit the descriptions of all files associated with the user, including the recently uploaded. The uploading of new files is done via AJAX / JQuery and new forms (as part of a formset) are generated dynamically. In order to do be able to edit the descriptions in an efficient matter, it would help for a user to know of what file it is changing the description, and so I would like the filename to be displayed. My initial solution was the following: forms.py class ArchiveDataForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['archive_file'].widget.attrs['disabled'] = True class Meta: model = ArchiveFile fields = ['archive_file','description'] template {% for archive_form in archive_formset %} {{ archive_form.archive_file.value }} {{ archive_form.description }} {% endfor %} My issue is that I am getting validation errors on the dynamically created forms, saying that no file is present. Which I suppose is correct since all I … -
Create post without model in django
Sorry for my english. I new in django, and i want create custom post. I have not model for this and i dont need create it. I cant understand how create normal post reqest in django. Bellow my try create it view: class CreateCustopPost(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = CustomSerializer serializer: class CustomSerializer(serializers.ModelSerializer): type_report = serializers.CharField(max_length=23) client_token = serializers.CharField(max_length=128) year_p_start = serializers.DecimalField(max_digits=10, decimal_places=2) month_p_start = serializers.DecimalField(max_digits=10, decimal_places=2) day_p_start = serializers.DecimalField(max_digits=10, decimal_places=2) year_p_end = serializers.DecimalField(max_digits=10, decimal_places=2) month_p_end = serializers.DecimalField(max_digits=10, decimal_places=2) day_p_end = serializers.DecimalField(max_digits=10, decimal_places=2) class Meta: model = # i dont have model for this. fields = ('type_report', 'client_token', 'year_p_start', 'month_p_start', 'day_p_start', 'year_p_end', 'month_p_end', 'day_p_end') my qestion: what need typing in serializer class in model = ? -
Storing JSON variable in django database
In my app that uses Gridster I am changing the widget positions and then saving it as a json variable.I want to store this json variable in django database. For that I am not understanding how should I define a function in views.py and a class in models.py which can store the json variable My HTML/JS template is var URL = "{% url 'my_view_url' %}"; $('.js-seralize-update').on('click', function () { var s = gridster.serialize(); updated_grid=JSON.stringify(s); $('#log').val(updated_grid); function updategridster(){ var data = updated_grid; $.post(URL, data, function(response){ if(response === 'success'){ alert('Yay!'); } else{ alert('Error! :('); } }); } }); My views.py def save_grid(request): if request.method == 'POST': # Some code to get json variable and store it to model return HttpResponse('success') # if everything is OK I want to write some kind of class in models.py corresponding to view.py so that JSON variable can be saved -
Django : Waterfall method with spline display (no column)
I spent a lot of time on this problem: I notice that I am working on Django and Highcharts (chartit). I have a database that contains simulations results. I would like to cumulate these results on a chart in order to get : Simulation 1 -> Result Simulation 1 Simulation 2 -> Sum results simulation 1 + 2 Simulation 3 -> Sum results simulations 1 + 2 + 3 and so on... with the simulation number on the x axis. I have seen that the waterfall function exactly do that but is ploting column or brick. I would like to get a line or spline representation. Do you know an option or an other method to get this result ? Thank you very much !!! -
Django query latest()
I wan't to get the latest id of a table, and use this value as a filter Lastrun=Runid.objects.latest('id') query_hostinfo_results = HostinfoHist.objects.filter( runid = Lastrun ) if I enter the id manually, eg. runid = '1041' everything works fine, but I can't query for Lastrun I guess it's because I don't get a string or integer value back, but Runid object (1041) how I can get the value 1041 from this object cheers Funksen -
Two django project on the same ip address (server)
Is it possible to set two different django projects on the same IP address/server (Linode in this case)? For exmaple, django1_project running on www.example.com and django2_project on django2.example.com. This is preferable, but if this is not possible then how to make two djangos, i.e. one running on www.example.com/django1 and the second on www.example.com/django2? Do I need to adapt the settings.py, wsgi.py files or apache files (at /etc/apache2/sites-available) or something else? Thank you in advance for your help! -
Could not resolve URL for hyperlinked relationship using view name "profile-detail"
I am trying to customize django's User model and send one additional field while creating a new user through djsoer's create user end point. Here is my model.py from django.db import models from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager class CustomAccountManager(BaseUserManager): def create_user(self, email, name, account_address, password): user = self.model(email=email, name=name, account_address=account_address, password=password) user.set_password(password) user.is_staff = False user.is_superuser = False user.save(using=self._db) return user def create_user(self, email,name, account_address, password): user = self.model(email=email, name=name, account_address=account_address, password=password) user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user def get_by_natural_key(self, email_): print(email_) return self.get(email=email_) class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) account_address = models.CharField(max_length=30, blank=True) name = models.CharField(blank=True, null=True, max_length=150) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['account_address', 'password'] objects = CustomAccountManager() def get_short_name(self): return self.email def natural_key(self): return self.email def __str__(self): return self.email and my serializer.py is following from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer class UserRegistrationSerializer(BaseUserRegistrationSerializer): class Meta(BaseUserRegistrationSerializer.Meta): fields = ('url', 'id', 'email', 'name', 'account_address', 'password') and here is my urls.py from django.conf.urls import url, include from rest_framework.routers import DefaultRouter router = DefaultRouter() urlpatterns = [ url(r'^account/', include('djoser.urls')), ] But when I am trying to create a new user i am getting following error. any help is appreciated :) -
Which are some ways to grow strong Python programming skills and logic? [on hold]
I am not that good in programming, i want to upgrade my skills in python, Which are some ways to grow strong Python programming skills and logic? -
Django redirecting http -> https
I am running: python manage.py runserver localhost:44100 And this is redirecting me to https: » http http://localhost:44100/ HTTP/1.0 301 Moved Permanently Content-Type: text/html; charset=utf-8 Date: Mon, 05 Mar 2018 14:09:09 GMT Location: https://localhost:44100/ Server: WSGIServer/0.1 Python/2.7.14 X-Frame-Options: SAMEORIGIN Why / how is this happening? What setting does control whether Django accepts http / https? -
Accessing Middleware value for testing a Django DetailView
I am writing a test for a DetailView that queries get_object() by accessing a value set in a Middleware. This is for a Companies application and Company Model. Each user is in a Company. To access the company throughout the project, I set the current user's Company.uuid on the request via a custom middleware. Middleware from django.utils.deprecation import MiddlewareMixin class DynamicCompanyUUIDMiddleware(MiddlewareMixin): """ Adds the current organization's UUID from the current user.""" def process_request(self, request): try: company_uuid = request.user.company_uuid except: company_uuid = None request.company_uuid = company_uuid That is used in the CompanyDetailView's get_object() method via a Mixin that I use for the other Company Views. Mixin class CompanyMixin(LoginRequiredMixin, SetHeadlineMixin): model = Company def get_object(self): return get_object_or_404( self.model, uuid=self.request.user.company_uuid) Test The test that I'm trying to write is: class TestCompanyDetailView(BaseCompanyTestCase): def setUp(self): super(TestCompanyDetailView, self).setUp() self.client.login(username="testuser", password="password") self.view = CompanyDetailView() self.view.object = self.object request = self.factory.get(reverse('companies:detail')) request.user = self.user request.view = CompanyDetailView response = self.client.get(reverse('companies:detail')) self.assertEqual(response.status_code, 200) def test_get_headline(self): self.assertEqual( self.view.get_headline(), '%s Members' % self.object.name Result This results in a 404 with the testuser's company not being found. response = self.client.get(reverse('companies:detail')) Walking through it: I create the user Create the company for this new testuser Set the user.company_uuid This should allow the mixin … -
Django how to file field with array for uploading
I have html template: <input name="image[1]" class="file input-image " type="file"> <input name="image[2]" class="file input-image " type="file"> <input name="image[3]" class="file input-image " type="file"> With Django how to integegrate: Django From: class AdsForm(forms.Form): title = forms.CharField(required=True) description = forms.CharField(required=True) price = forms.DecimalField(required=True, max_digits=10, decimal_places=2,) currency = forms.ChoiceField(choices=CurrencyChoise.CURRENCY_CHOICES, label=_('backend', 'ads_currency')) images = forms.FileField() I know : class FileFieldForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) bu it is noy my sloution. I tried: for x in range(0, 6): image[x] = forms.ImageField() but not working. error : IndexError: list assignment index out of range please help me! -
Django / Python - sorting different Class objects sharing the same attribute?
So let's say I have the following models in Django: class Review(models.Model): datetime = models.DateTimeField(("Date"), default=timezone.now) class Rating(models.Model): datetime = models.DateTimeField(("Date"), default=timezone.now) And my view looks like this: def get_page(request, id_slug): context_dict = {} reviews = Review.objects.filter(attribute=id_slug).order_by('-datetime') ratings = Rating.objects.filter(attribute=id_slug).order_by('-datetime') context_dict['reviews'] = reviews context_dict['ratings'] = ratings return render(request, 'page.html', context_dict) What I want to do is make a query set that would include both Review and Rating objects, ordered by the datetime attribute, so something like: activity = reviewsANDratings.order_by('-datetime') context_dict['activity'] = activity What would be the best way to achieve this? Thank you! -
Wagtail custom settings not showing
I created a new project using python 3.6 by following the link tutorial: http://docs.wagtail.io/en/stable/getting_started/index.html. Then I tried to create a custom configuration following the link tutorial: http://docs.wagtail.io/en/stable/reference/contrib/settings.html?highlight=Settings However, the link in settings never appears. Any tips on what it might be? -
Issue while trying to login automatically in django
I have following code in Django. def accountactivation(request): userid =request.GET['id'] userobject= User.objects.get(id=userid) print userobject.username print userobject.password new_user = authenticate(username=userobject.username, password=userobject.password) print new_user #login(request, new_user) #return redirect(reverse('home')) return render(request, 'blog/login.html') The problem is if I manually login, it always works but when I try to login automatically, it never works. Am I missing anything? Printed value of new_user is always None -
django template tag on multiple line
I am creating a custom django template tag by using such a code : @register.simple_tag(takes_context=True) def render_listing(context, *args, **kwargs): ... my code ... This works well, but in my template, it seems that all parameters must be on a single line, for example : this works: {% render_listing param1=val1 param2=val2 ... paramN=valN %} but on multiple lines, it does not work : {% render_listing param1=val1 param2=val2 ... paramN=valN %} I tried multiple escape sequences but I did not succeeded, Is there a way to specify a template tag on multiple lines ? -
Django Heroku Postgres Deployment TCP/IP connections error
I'm having a lot of trouble with the Heroku Postgres setup for my Django app. I'm trying to use the Postgres.app. When I run the Heroku Debugging Command: heroku pg:psql, I get: --> Connecting to postgresql-horizontal-77797 psql (10.3, server 10.2 (Ubuntu 10.2-1.pgdg14.04+1)) SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help. sales-mark-dash::DATABASE=> The Heroku App URL Error says: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port ####? File "/app/.heroku/python/lib/python2.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port ####? The Postgres.app documentation says the password is blank by default in the settings.py. Under the "How to connect" section on the Python tab it says (PASSWORD": "",). How do I set the password for the Postgres.app on a Mac? Maybe it will help me connect. Because I keep getting: psql: FATAL: password authentication failed for user "aliciaalexander" -
Removing a single <li> item causes everything to break in nested {% if %} statement
Removing the very first <li> item in this <ul> will strangely prevent everything else in the page from loading. And it will only happen for anonymous users. So something tells me it has to do with the is_authenticated check which occurs just below it. I can't figure out why removing the first <li> will break everything else. Any idea? <ul class="navbar-nav mr-auto"> <li class="nav-item"> {# this one #} </li> {% if request.user.is_authenticated %} {% if request.user.is_profile_to.profile_photo_thumbnail %} <li class="nav-item"> </li> {% else %} <li class="nav-item"> </li> {% endif %} <li class="nav-item"> </li> <li class="nav-item dropdown dropdown-notifications" data-open-notifications="{% url 'notifications:notifications_ajax' %}"> </li> <li class="nav-item"> </li> {% else %} <li class="nav-item"> </li> {% endif %} </ul> -
Django - Passing data from a view to be used client side using JavaScript in a template
Scenario: I am developing a text-based RPG game in Django and I am wondering what the best way would be to run an event (such as a fight between two characters) server side, and instead of simply passing the result back to the client via a template, such as who won, I want to re-run this 'fight' but in a slower speed using JavaScript. This would show each characters 'turn' and the damage they dealt, although this would be processed instantly on the server. The methods I thought about using were as follows: Pass the combat log/fight through to the template via context using some dictionary or JSON and access the template variable via JavaScript Send this data to an API which the JavaScript code in the template will fetch and modify to show at a reduced speed Do anyone have any better solutions? I don't think I should be posting the outcome of each fight using an API just to transfer this data to client side for use with JS, it's a waste of storage if this is the only use. Thanks! -
Django or Django Rest Framework
I have made a certain app in django and I know that django rest framework is used for API.But when I started to read about django rest framework on there website.Each and every thing in API Guide(like request, response, views etc).talks about it is superior than django(request, response, views etc.) The thing I am not understanding whether these API's will replace my existing django models, views etc. or how can I use them differently in my existing django code I am quite familiar with django but not able to understand what exactly what django rest framework is even after spending some time on it.(I know it is used for API) -
Saving two related models via one serializer and passing the first's id to the second as a foreign key in django rest framework?
I have a JourneySchedule model which stores depart and return journeys: class JouaneySchedule(models.Model): Owner = models.ForeignKey('Profile', on_delete=models.PROTECT) ReturnOf = models.ForeignKey('self', on_delete=models.CASCADE, null=True) JourneyDate = models.DateField(null=True) JourneyStartTime = models.TimeField() IsDepart = models.BooleanField(default=True) Fare = models.PositiveIntegerField(null=False, default=0) Depart and return journeys are connected via ReturnOf self foreign key. Journey serializer is: class JourneyScheduleSerializer(serializers.ModelSerializer): Owner = serializers.ReadOnlyField(source='user.id') ReturnOf = serializers.ReadOnlyField() class Meta: model = JourneySchedule fields = ( 'id', 'Driver', 'ReturnOf', 'JourneyDate', 'JourneyStartTime', 'IsDepart', 'Fare' ) I have defined Commute model to save depart and return journeys at once using nested object (both are instances of journey) class CommuteSerializer(serializers.Serializer): depart_journey = JourneyScheduleSerializer(required=False) return_journey = JourneyScheduleSerializer(required=False) class Meta: model = JourneySchedule fields = ('depart_journey', 'return_journey') So I need to save depart_journey first and then pass the id to return_journey as ReturnOf field. How can I achieve that? -
How to convert status of the user from Django Administration Page
I want to change the status of a registered user to staff or active/notactive. While logging in the Django Administration Page as a superuser I couldn't find any option to do that as you can see from the below screen shot. How can we do it. -
Django: Permission per instance
At the moment, I plan to write a website where users can write blog posts. I haven't started with the implementation yet because I am new to Django and want to get an overview in how I should solve problems and structure the overall project. My problem: The users aren't allowed to use Django's admin page (/admin). The users should only interact with the website that I write. The users at my website will be able to create blog posts. Now, I have to ensure that only the creator of the blog post should be able to edit/delete his own post. All the other users should only be able to read this post. So, I need permissions per user/instance. I know that there are some full-blown permission-systems like django-guardian, but I would like to prefer to solve it on my own. Also to better understand the Django framework. I`ve already read the Django docs, but I am overwhelmed. I guess this is such a common problem that I there is also a common solution to this problem. Can someone help me where I should look at, where to start? My idea so far (please comment): In create a page like … -
How to pass HyperLinkedModels to a form in Django with django-rest-framework
I have this serializer: class ProjectSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Project fields = ('id', 'name', 'project_id', 'user_set') read_only_fields = ('created', 'modified') Then I have a form which is derived from this answer. This is the code from it that I think is relevant: user_set = forms.ModelMultipleChoiceField(queryset=User.objects.all()) You might already see the problem. The API expects HyperLinkedModels to be passed, but instead I pass plain User objects. So posting the form results in this error: "user_set": [ "Invalid hyperlink - No URL match." ] I could edit the serializer to not expect a HyperLink but I would like to maintain that functionality. How can I parse the result from the queryset as HyperLinkedModels? Or how do I make it return HyperLinkedModels from the get go? Is there an easy way to do this? -
Django: 404 error No comment found matching the query
I'm having problems posting a comment related to a park when there are no previous comments posted. Everything works as expected after adding a comment to the park using the admin page. The comment app uses a GenerigForeignKey and currently only has a model. The parks app uses two different classbased views 'formview' and 'detailview' on a single url, as is explained in the django docs here. I have found that no code is executed after this line of code in the CommentFormView post definition: self.object = self.get_object() I have searched on stackoverflow for similar errors but those were mostly related to wrong url configurations. Error message Page not found (404) Request Method: POST Request URL: http://localhost:8000/parks/detail/1 Raised by: parks.views.ParkDetail No comment found matching the query Project urls.py urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), # Django Admin, use {% url 'admin:index' %} url(settings.ADMIN_URL, admin.site.urls), # User management url(r'^users/', include('mtbhub.users.urls', namespace='users')), url(r'^accounts/', include('allauth.urls')), # Your stuff: custom urls includes go here url(r'^parks/', include('mtbhub.parks.urls', namespace='parks')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Project settings.py LOCAL_APPS = [ # custom users app 'mtbhub.users.apps.UsersConfig', # Your stuff: custom apps go here 'mtbhub.parks.apps.ParksConfig', 'mtbhub.comments.apps.CommentsConfig', ] Parks app urls.py app_name='parks' urlpatterns = [ path('', ParkList.as_view(), name='list'), … -
Django: Make Object only editable by creator
I plan to create a small website, where users can log in and write a blog post. However, those users do not have access to the admin page! My goal ist that only the creator of a blog post can edit/delete this post. To be honest, I am a little bit overwhelmed because Django provides so many options in the auth/permissions area and I do not know which approach is best. How would you solve this permission problem in Django, is there a default way to handle this?