Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Autopopulate slug field without using third party app in django
This is my model: class Child(models.Model): child_name = models.CharField(max_length=150, null=True, blank=True) slug = models.SlugField(max_length=150,null=True, blank=True) # slug = AutoSlugField(populate_from='child_name') blood_group = models.CharField(max_length=5, blank=True) startup = models.ForeignKey(Startup) class Meta: verbose_name_plural = 'children' unique_together = ('slug', 'startup') def save(self, *args, **kwargs): if self.id is None: self.slug = slugify(self.child_name) else: self.slug = slugify(self.child_name) super(Child, self).save(*args, **kwargs) But this does not auto-populate my slug field in form. My form is : class ChildForm(SlugCleanMixin, forms.ModelForm): class Meta: model = Child fields = '__all__' widgets = {'startup': HiddenInput(), } my views.py: class ChildCreate(NewsLinkGetObjectMixin,StartupContextMixin, CreateView): form_class = ChildForm model = Child def get_initial(self): startup_slug = self.kwargs.get( self.startup_slug_url_kwarg) self.startup = get_object_or_404( Startup, slug__iexact=startup_slug) initial = { self.startup_context_object_name: self.startup, } initial.update(self.initial) return initial How do I autopopulate my slug field in form from when I typing child name. Is there any way to do that? I tried using django-autoslug but it not create unique slug and does not maintain my combined unique-together constraints. -
Set field as the second field of my form
I use django-allauth. How can I set item_name form field as the second field of my form?(currently is as first field after rendering in html) class CustomSignupForm(forms.Form): item_name = forms.CharField(...) def signup(self, request, user): pass ACCOUNT_SIGNUP_FORM_CLASS = 'app.forms.CustomSignupForm' -
Getting data from csv
I am getting some extra data frommy csv fields like "('value',)". How can I remove this from my value. I am Searching from yesterday but nothing worked for me. please help me. Thanks in advance. My model from django.db import models # Create your models here. class CSVReader(models.Model): Run = models.CharField(max_length=100, null=True, blank=True) Model = models.CharField(max_length=100, null=True, blank=True) Name = models.CharField(max_length=100, null=True, blank=True) Odometer = models.CharField(max_length=100, null=True, blank=True) VIN = models.CharField(max_length=100, null=True, blank=True) BidType = models.CharField(max_length=100, null=True, blank=True) Ammount = models.CharField(max_length=100, null=True, blank=True) BuyerName = models.CharField(max_length=100, null=True, blank=True) class UploadFile(models.Model): upload = models.FileField(upload_to='csv_files') My view -- coding: utf-8 -- import os, re import csv import string from django.shortcuts import render from .forms import UploadFileForm from django.shortcuts import HttpResponseRedirect from .models import CSVReader, UploadFile def CSV(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): up = UploadFile.objects.create() up.upload = request.FILES['upload'] up.save() path='C:\Users\\benq\Desktop\CSV\media\csv_files\data_ZXcwWnf.csv' var = "('bnmv')" var.split("(") print var # # script_dir = os.getcwd() # <-- absolute dir the script is in # rel_path = "\media\csv_files\data_ZXcwWnf.csv" # abs_file_path = os.path.join(path, rel_path) remove = "'()," with open(path, 'rb') as csvfile: reader = csv.reader(csvfile) for row in reader: c= CSVReader.objects.create() if row[1]!='': c.Run = row[1].replace("('", '').split("')"), temp = row[1].replace("('", '').split("')"), print temp … -
selenium testing with django gives 'NoneType' object has no attribute 'path'
I cannot see what is making this error happen because it does not give me more information. The tests pass, but they print this message to the console. I will post my files below. tests.py: class MainAppTests(LiveServerTestCase): """Testing the interactions on the main page""" def setUp(self): """Opening the browser""" selenium_logger = logging.getLogger('selenium.webdriver.remote.remote_connection') # Only display possible problems selenium_logger.setLevel(logging.ERROR) self.browser = webdriver.Firefox() self.user = make_user() def tearDown(self): """Closing the browser""" self.browser.quit() def test_homepage(self): """Testing that everything work""" self.browser.get(self.live_server_url) self.assertIn("Site", self.browser.title) views.py: def home(request): """View for displaying the home page""" if request.user.is_authenticated(): # Pulling and ordering by the 'full_name' field, shows users what is available active_languages = Language.objects.filter(active=True).order_by('full_name') context = {'active_languages': active_languages} return render(request, 'main/home_loggedin.html', context) return render(request, 'main/home_loggedout.html', status=302) -
Django: Reverse for '*' with arguments '()' and keyword arguments '{a,b}' not found. 1 pattern(s) tried: ['order/pay/(?P<pk>\\d+)/$']
I have to views. One that triggers an overview of a guest's orders. And one that sets an order to paid and then should go back to the overview: @login_required def guest_detail(request, pk): guest = get_object_or_404(Guest, pk=pk) open_orders = Order.objects.filter(guest = guest, is_paid=False) paid_orders = Order.objects.filter(guest = guest, is_paid=True) if request.method == "POST": form = RegisterGuestForm(request.POST, instance=guest) if form.is_valid(): guest = form.save(commit=False) guest.save() #post.published_date = timezone.now() return redirect('guest_detail', pk=guest.pk) else: form = RegisterGuestForm(instance=guest) context = {'form': form} context['open_orders'] = open_orders context['paid_orders'] = paid_orders return render(request, 'hotel/guest_detail.html', context) This view is rendered to this template: <div class="col-md-8 col-xs-12"> <h3>Guest Information:</h3> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save-guest btn btn-default">Save</button> </form> <h3>Open orders:</h3> <table class="table table-condensed table-guest-order"> <tr> <th>Date</th> <th>Amount</th> <th>Item</th> <th>Price</th> <th><th> </tr> {% for order in open_orders %} <tr> <td>{{ order.date }}</td> <td>{{ order.amount }}</td> <td>{{ order.item }}</td> <td>{{ order.price }}</td> <td><a href="{% url 'pay_order' pk=order.pk order_guest=order.guest.pk %}">pay</a></td> </tr> {% endfor %} </table> </div> The pay_order link then calls the following view, which should then redirect me back, to where I come from: @login_required def pay_order(request, *args, **kwargs): order = Order.objects.get(pk=kwargs['pk']) if order.is_paid is False: order.is_paid = True order.paid_date = timezone.now() order.save() return redirect(views.guest_detail, pk=kwargs['order_guest']) But … -
Dynamically dependent choice form fields in django
I am new to django and what I am trying to do is to link two fields in a django form. First field contains choices as: States = (('1', ('solid')), ('2', ('liquid')), ('3', ('gas'))) StatesFiels = forms.ChoiceField(choices= States) And second field substances names: Substances = (('1', ('benzene')), ('2', ('water')), ('3', ('salt'))).... SubstancesFiels = forms.ChoiceField(choices= Subsances) How can I make that the second field provides as the options only e.g. "benzene" and "water" if in the first field the option "liquid" is selected? -
How to write web services using Python?
I need to write a web service by python. I do not know anything about how to do that. I need someone tell me how to start and which resources to study. -
Post API using Token from headers
I am posting using an API to create a new entry in the model Movie. Using headers, I would like to be able to POST so the OWNER is the user who has posted it. The users token is sent via headers. models.py @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class Movie(models.Model): title = models.CharField("Title", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) created = models.DateTimeField("Created", auto_now_add=True) owner = models.ForeignKey('auth.User', blank=True, null=True) Views.py class OwnerFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter(owner=request.user) class AllViewSet(viewsets.ModelViewSet): filter_backends = (OwnerFilterBackend,) queryset = Movie.objects.order_by('-created',).exclude(deleted=True).exclude(typetask=2) serializer_class = AllSerializer Serializers.py class AllSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=True) class Meta: model = Movie fields = ('title', 'mail', 'pk', 'tag', 'info', 'created', 'deleted', 'status', 'typetask') def create(self, validated_data): tags_data = validated_data.pop('tag') movie = Movie.objects.create(**validated_data) for tag_data in tags_data: tag_qs = Tag.objects.filter(name__iexact=tag_data['name']) if tag_qs.exists(): tag = tag_qs.first() else: tag = Tag.objects.create(**tag_data) task.tag.add(tag) return movie -
'QueryDict' object has no attribute 'users'
So I am trying to redeem a coupon I have created on the backend and I am encountering an error in my models.py I am using the django-coupons package which has very little documentation and I am struggling a bit with it. Please help! traceback: Traceback (most recent call last): File "/Users/krippee/Documents/Projects/lularippee/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Users/krippee/Documents/Projects/lularippee/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/krippee/Documents/Projects/lularippee/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/krippee/Documents/Projects/lularippee/main/views.py", line 198, in gift_card Coupon.redeem(request.POST) File "/Users/krippee/Documents/Projects/lularippee/coupons/models.py", line 124, in redeem coupon_user = self.users.get(user=user) AttributeError: 'QueryDict' object has no attribute 'users' views.py def gift_card(request): user = request.user if request.user.is_authenticated: edit_profile = EditProfileForm(user=user) redeem = CouponForm() if request.method == 'POST': edit_profile = EditProfileForm(request.POST, user=user) redeem = CouponForm(request.POST, user=user) if redeem.is_valid(): Coupon.redeem(request.POST) else: edit_profile = EditProfileForm(user=user) return render(request, 'main/profile.html', {'edit_profile': edit_profile, 'redeem': redeem}) return render(request, 'main/profile.html', {'edit_profile': edit_profile, 'redeem': redeem}) else: return redirect('/') forms.py class CouponForm(forms.Form): code = forms.CharField(required=True, label=_("code"), widget=forms.TextInput (attrs={'placeholder':_('Code'), 'class': 'text-center'})) def __init__(self, *args, **kwargs): self.user = None self.types = None if 'user' in kwargs: self.user = kwargs['user'] del kwargs['user'] if 'types' in kwargs: self.types = kwargs['types'] del kwargs['types'] super(CouponForm, self).__init__(*args, **kwargs) def clean_code(self): code = self.cleaned_data['code'] … -
Default date format using generic views in Django
I have a generic.UpdateView but when I display the dates I got this format "2016-11-15 00:00:00" When I want something like this dd/mm/yyyy. class Updatebooking(generic.UpdateView): model = booking fields = ['name', 'mobile', 'email', 'date_out', 'date_in', 'indications'....] I already change the settings.py to this LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False USE_TZ = True DATETIME_FORMAT = 'd/m/Y P' SHORT_DATETIME_FORMAT = 'd/m/Y' To display my html has a loop that is why I am not using something like this {{ date_in|date:"D d M Y" }} <div class="widget-content" > <div class="form-group"> <label class="col-md-2">{{ field.label_tag}}</label> <div class="col-md-4"> {{field}} <span class="text-danger">{{field.errors}}</span> {% if field.help_text %} <span class="text-muted">{{ field.help_text }}</span> {% endif %} </div> </div> </div> -
Django Rest Framework PrimaryKeyRelatedField queryset params
I have this model which has 2 foreign keys: project and registry class Worker(models.Model): project = models.ForeignKey(Project, related_name="workers", on_delete=models.CASCADE) registry = models.ForeignKey(Registry, related_name="workers", on_delete=models.CASCADE) image = models.CharField(max_length=254, null=False) and this serializer showing them: class WorkerSerializer(serializers.ModelSerializer): project = ProjectSerializer(many=False, read_only=True) registry = RegistrySerializer(many=False, read_only=True) registry_id = serializers.PrimaryKeyRelatedField(source='registry', queryset=Registry.objects.all()) class Meta: model = Worker fields = ('id', 'registry_id', 'image', 'project', 'registry') When I browse via the REST api to /projects/1/workers I can see a form asking for image and a dropdown with registries to pick from. The problem is that I don't know how to alter the queryset param in order to fetch registries added by the current user hence the: Registry.objects.all(). I tried by playing with the source param but when I log the queries it still fetches all the registries without any user id being accounted for. Any ideas? -
Text overflow in django template
I am Trying to render a string stored in variable ShortDesc in my model. But when I try to render it in the template and place it in a materialize card, the information stored gets out of the card and is hidden. my template.py <div class="col s12 m7 l3"> <div class="card small"> <div class="card-image"> <img src="images/sample-1.jpg"> <span class="card-title" style="color: black">{{ event.EventName }}</span> </div> <div class="card-content container"> <span>{{event.ShortDesc}}</span> </div> </div> </div> -
Django rest framework not updating extended user model
I have extended user model in Django, and it is of Customer type. I am using django rest framework (DRF). So, while going through docs in DRF I came to know about writing in nested models, so I did override create and update methods in serializer, creation is working fine but not the update as it says : HTTP 400 Bad Request Allow: GET, PUT, PATCH, DELETE, OPTIONS Content-Type: application/json Vary: Accept { "user": { "username": [ "A user with that username already exists." ] } } Here is my Customer model: from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, related_name="customer", on_delete=models.CASCADE) date_of_birth = models.DateField(max_length=8) def __unicode__(self): return u'%s' % self.user.username My User serializer: from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') And my extended customer model serializer: from django.contrib.auth.models import User from django.contrib.auth import get_user_model from rest_framework import serializers from customers.models import Customer from api.serializers import UserSerializer class CustomerSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = Customer fields = ('url', 'date_of_birth', 'user') depth = 1 def create(self, validated_data): print "coming inside create" user_data = validated_data.pop("user") user = User.objects.create(**user_data) customer = Customer.objects.create(user=user, … -
HttpResponse won't display `post` information when submitting a form
I'm working my way through Django and I'm creating an app that will allow users to use an ID number to sign-in to a system. So I have two views, one for users to log-in, and the other to sign-up. The former view works just fine, I can get it to display the information the user has submitted. However I can't get the second view to display the POST data to the user: from .forms import NameForm, IdForm from django.shortcuts import render from django.http import HttpResponse def sign_in(request): if request.method == "POST": #here will construct the form with the POST data form = NameForm(request.POST) #the next part is to check that the information submitted is valid if form.is_valid(): post = form.save() post.save() return HttpResponse(post) else: return HttpResponse("Form is invalid") else: form = NameForm() return render(request, 'checkin/base.html', {'form': form}) def sign_up(request): if request.method == "POST": form = IdForm(request.POST) if form.is_valid(): post = form.save() post.save() return HttpResponse(post) else: return HttpResponse('Form is invalid') else: form = IdForm() return render(request, 'checkin/base.html', {'form': form}) Basically I want to make the response to be "thank you, your ID number is: post". Here is the class for my model: from __future__ import unicode_literals from django.db import models … -
Django's admin form not working for one model while it's working for the other models
I'm getting a strange error while trying to open one of my models in Django's admin forms. Funny thing is, the admin forms work perfectly for all other models for the EXACT same code. Please take a look and tell me what could be wrong here. Very much appreciated. models.py: class ForumQuestions(models.Model): """ Table to store questions fq_id - Question Id fq_label - label as [New Question/Trending Topic] fq_category - Questions Category fq_question - Actual question fq_author - Author for the question fq_short_answer - short answer for the question """ fq_id = models.AutoField(primary_key=True, db_column='q_id') fq_label = models.CharField(db_column='q_label', max_length=30, default='') fq_category = models.CharField(db_column='q_category', max_length=30, default='') fq_question = models.CharField(db_column='q_question', max_length=500, default='') fq_author = models.CharField(db_column='q_author', max_length=50, default='') fq_short_answer = models.CharField(db_column='q_short_answer', max_length=100, default='') def __unicode__(self): return self.fq_question admin.py: from cmpon.models import Exams from cmpon.models import Expert_video from cmpon.models import Concept_video from cmpon.models import ForumQuestions admin.site.register(Exams) admin.site.register(Expert_video) admin.site.register(Concept_video) admin.site.register(ForumQuestions) Error: ProgrammingError at /admin/forum/forumquestions/ (1146, "Table 'cmpon.forum_forumquestions' doesn't exist") Request Method: GET Request URL: http://127.0.0.1:8000/admin/forum/forumquestions/ Django Version: 1.9.2 Exception Type: ProgrammingError Exception Value: (1146, "Table 'cmpon.forum_forumquestions' doesn't exist") Exception Location: /usr/lib/python2.7/dist-packages/MySQLdb/connections.py in defaulterrorhandler, line 36 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/media/deepak/Laniakea/Projects/Chan/Chan Real/cmpon', '/usr/local/lib/python2.7/dist-packages/unidecode-0.4.19-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/django_php_bridge-0.1.1-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/phpserialize-1.3-py2.7.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/var/www/cmp'] … -
Form coming back with <django.db.models.query_utils.DeferredAttribute object at 0x10e6ee898>
Disclaimer: I am fairly new to Django (trying to teach myself) and am currently trying to get a package that had little to no documentation https://github.com/byteweaver/django-coupons working for an app I am building. I am trying to redeem a coupon I have created on the backend with the following code and I am getting some very strange errors. When I submit my form the <django.db.models.query_utils.DeferredAttribute object at 0x10e6ee898> that comes back in the form box and I am given a "This code is not valid" error. Any assistance on this would be greatly appreciated as I have been beating my head against a wall with this for hours and hours now. views.py def gift_card(request): user = request.user if request.user.is_authenticated: edit_profile = EditProfileForm(user=user) redeem = CouponForm({'code': Coupon.code}, user=user) if request.method == 'POST': edit_profile = EditProfileForm(request.POST, user=user) redeem = CouponForm({'code': Coupon.code}, user=user) if redeem.is_valid(): CouponForm({'code': Coupon.code}, user=user) else: edit_profile = EditProfileForm(user=user) redeem = CouponForm({'code': Coupon.code}, user=user) return render(request, 'main/profile.html', {'edit_profile': edit_profile, 'redeem': redeem}) return render(request, 'main/profile.html', {'edit_profile': edit_profile, 'redeem': redeem}) else: return redirect('/') forms.py class CouponForm(forms.Form): code = forms.CharField(required=True, label=_("code"), widget=forms.TextInput (attrs={'placeholder':_('Code'), 'class': 'text-center'})) def __init__(self, *args, **kwargs): self.user = None self.types = None if 'user' in kwargs: self.user = kwargs['user'] del … -
Filter API request according header auth token
I would like to filter the objects according to the token header which gets sent with the GET requests. My request is sending the token in the header (get curl -H "Authorization: Token 3f5452023a83c88853018c874712fb518d69434a" https://1.com/api) The code below returns no results (just an empty array- no error). I am unable to determine where my request object headers are. views.py class AllViewSet(viewsets.ModelViewSet): queryset = Movie.objects.order_by('-created',) serializer_class = AllSerializer def get_queryset(self): Movie.objects.filter(owner = self.request.user) I tried some debugging after the def_queryset (using import pdb; pdb.set_trace()). def(sel.request) returns: http://dpaste.com/2VQARE3 Here are other parts of my code which may be relevant. models.py class Movie(models.Model): title = models.CharField("Title", max_length=10000, blank=True) tag = models.ManyToManyField('Tag', blank=True) created = models.DateTimeField("Created", auto_now_add=True) owner = models.ForeignKey('auth.User', blank=True, null=True) setting.py REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) -
tzlocal gives me UTC as my local timezone
I am having alot of trouble getting Django to render a datetime field in my local timzeone. Settings.py has: TIME_ZONE = 'UTC' USE_TZ = True USE_L10N = True In my model I have: class ExportRecord(models.Model): [...] created = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): [...] self.created = timezone.now() Created gets stored as a UTC time object in MySQL. If I have "2016-11-08 01:25:15" in the database after the created field is populated, when I render my template I expect it to be translated into the local time of the client (I am in eastern time, so I expected it to be "2016-11-07 20:25:15". However, no matter what tags I use (for example {{ date_obg | localtime }}), the date will not be rendered as my local time. I installed tzlocal and when I run get_localzone() in my view it shows 'UTC' as the output. Furthermore, if I try this (converting my created field from UTC to my local timezone variable): lctz = get_localzone() self.created.replace(tzinfo=pytz.utc).astimezone('lctz') >>>>2016-11-08 01:25:15 The created date stays the same as it is in the DB (which is in UTC). Is this because the local timezone of my Google App Engine instance is in UTC? How do I get … -
Adding a reverse related model on the fly in a django form like in the admin
Let's say for the classical example of an Author has many Books and each Book belong to an Author. When I am adding a book (say using a CreateBookView), I get a select input with authors populated as options. Now, if the author I need is not already there, like in django admin, I need to be able to create the author on the spot, and upon submission, the id and name of the author should be inserted back to the create book form as selected option. I would also like the solution to be easily reusable on other models. What is the best way to tackle this problem? -
Websocket Best Practices for dealing with Human-to-Server interactions
I are implementing some new services in django-channels, using websockets. So far it has been relatively straight forward, and I have multiplexed 6 data streams into one socket. One of the immediate problems I noticed is that the traditional reliable pattern of HTTP connections has been lost. For example, in HTTP land I can fire of a request, and at some point I'll get a response that may contain an error code, a success code, extra data etc. I can then reliably show a success message, an error message etc. to the end user to let them know what is going on. Websockets break this mould. I can send 2 lots of data across to the server, A and B, but I can't be sure of their return value (or even if there is one), nor their return order etc. This represents a new way of thinking-about and handling problems for me (I have only ever done HTTP web stuff before), and I am not sure where to turn. Can someone provide me some resources I can read to understand best practices, including practical examples, for dealing with asynchronous, non-determinate sequences of messages in (web)sockets (and maybe even django-channels) -
Can I use an external database table for the login process in Django?
So I'm starting a new Django project that essentially requires the login & registration process be routed through an EXTERNAL & ALREADY created database. Is it possible to have the User model use an EXTERNAL database table ONLY when Django is: Logging in a user, to check if the login is valid Registering a user, inserting data for that user in the external database I would like for the rest of the Django server to use a local database. -
How to save inline formset user field in Django using views
I've been using this great post http://kevindias.com/writing/django-class-based-views-multiple-inline-formsets/ to setup my site. I was wondering how to save the user field automatically to an inline formset in views (I used the blockquote for changes to the original). I know Django suggests using BaseInlineFormSet, but most people suggest saving user field in views.py and not forms or models for many different reasons. I would appreciate any suggestions or answers # models.py from django.db import models class Recipe(models.Model): owner = models.ForeignKey(User) title = models.CharField(max_length=255) description = models.TextField() class Ingredient(models.Model): owner = models.ForeignKey(User) recipe = models.ForeignKey(Recipe) description = models.CharField(max_length=255) class Instruction(models.Model): recipe = models.ForeignKey(Recipe) number = models.PositiveSmallIntegerField() description = models.TextField() # forms.py from django.forms import ModelForm from django.forms.models import inlineformset_factory from .models import Recipe, Ingredient, Instruction class RecipeForm(ModelForm): class Meta: model = Recipe IngredientFormSet = inlineformset_factory(Recipe, Ingredient) InstructionFormSet = inlineformset_factory(Recipe, Instruction) # views.py from django.http import HttpResponseRedirect from django.views.generic import CreateView from .forms import IngredientFormSet, InstructionFormSet, RecipeForm from .models import Recipe class RecipeCreateView(CreateView): template_name = 'recipe_add.html' model = Recipe form_class = RecipeForm success_url = 'success/' def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ self.object = None form_class = self.get_form_class() form = … -
Django tastypie relative queryset
Here is the model: class Project(models.Model): creator = models.ForeignKey(User) name = models.CharField(max_length=64) def __unicode__ (self): return self.name Now I want to get the user projects by REST/tastypie. I made the resource class by tutorials like this: class ProjectResource(ModelResource): class Meta: queryset = Project.objects.all() resource_name = 'project' But this code returning all data for every user. I know how to add authentication, but I can't understand how to return not all projects, but some subset od this data, based on logged user id. -
Serve large dataset w/ Docker, nginx, & django
I am working on a research project that involves large video datasets (100s of GB, possibly multiple TB in the near future). I am fairly new to linux, sysadmin, and setting up servers, so please bear with me. I've provided quite a bit of info, and let me know if there is anything else that would be helpful. I am using Ubuntu, Docker (w/ docker-compose), nginx, Python3.5 & django 1.10 Uploading a large-ish (60GB) dataset leads to the following error: $ sudo docker-compose build postgres uses an image, skipping Building django Step 1 : FROM python:3.5-onbuild # Executing 3 build triggers... Step 1 : COPY requirements.txt /usr/src/app/ ---> Using cache Step 1 : RUN pip install --no-cache-dir -r requirements.txt ---> Using cache Step 1 : COPY . /usr/src/app ERROR: Service 'django' failed to build: Error processing tar file(exit status 1): write /usr/src/app/media/packages/video_3/video/video_3.mkv: no space left on device My files are on a drive with 500GB free, and the current dataset is only ~60GB. I found this discussion on container size. Perhaps I am misunderstanding Docker, but I believe I just want my volumes to be larger, not the containers themselves, so this doesn't seem appropriate. It also doesn't use docker-compose, … -
No module named django error when running any manage.py command in docker with docker-compose
I'm getting ImportError: No module named django when trying to up my containers running docker-compose up. Here's my scenario: Dockerfile FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ docker-compose.yml version: '2' services: db: image: postgres web: build: . command: bash -c "python manage.py runserver" volumes: - .:/code expose: - "8000" links: - db:db manage.py import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) The containers were built successfully My packages are present in the container (I get them when I run pip freeze) I've changed the manage.py content for import django print django.get_version() and it worked. This is basically the same example as in this tutorial, except for starting a new project.