Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How save date fields in django model?
I can't save an object through form from model because i get an error that says "sportsession.date may not be NULL" models.py class SportSession(models.Model): session_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) sport_type = models.ForeignKey(SportType) date = models.DateField() usuario = models.ForeignKey(User) def __unicode__(self): # python 2 return self.name forms.py class SportSessionForm(ModelForm): class Meta: model = SportSession exclude = ("usuario", "date", "session_id") views.py def sport(request): form = SportSessionForm(request.POST or None) if form.is_valid(): form_data = form.cleaned_data # obtenemos la info del formulario obj = SportSession.objects.create() obj.name = form_data.get("name") obj.sport_type = form_data.get("sport_type") obj.date = date.today() obj.save() context = { "sport_session_form": form, } return render(request, "sport.html", context) -
How to automatically fill-in model fields in Django rest_framework serializer?
Let's assume I have a model like this: class Data(models.Model): a = models.CharField() b = models.CharField() c = models.IntegerField() I would like to setup a serializer in such a way that it automatically fills in field c and it is not required for a POST. I tried to overwrite the create function of the serializer, but it doesn't work: class DataSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Data fields = ('a', 'b') def create(self, validated_data, **kwargs): Data.objects.c = 5 return Data.objects.create(**validated_data) However, if I try this, I end up with an IntegrityError: NOT NULL constraint failed: model_data.c. What is the syntax that I have to use here? -
Django - null value in column "user_id" violates not-null constraint
I keep getting this error after countless trials: Traceback (most recent call last): File "C:\...\tests.py", line 82, in test_profile_creation w = self.create_profile() File "C:\...\tests.py", line 78, in create_profile self.user = Profile.objects.create(id=1) ... django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (1, null). I try to cover these area: I am not sure how to proceed testing with other two methods as marked ( get_screen_name() and get_association_name()) so guidance would be helpful. It is my first time in unit testing and still fresh on this so appreciate your guidance, folks! tests.py class ProfileTest(TestCase): def create_profile(self): self.asoc = Association.objects.create(id=2) self.admin = Administrator.objects.create(id=1, association=self.asoc) self.user = Profile.objects.create(id=1) return Profile.objects.get(user=self.user, administrator=self.admin) def test_profile_creation(self): w = self.create_profile() self.assertTrue(isinstance(w, Profile)) self.assertEqual(w.__str__(), w.user.username) models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Meta: db_table = 'Administrator' def __str__(self): return self.username def __unicode__(self): return self.username class Profile(models.Model): user = models.OneToOneField(Administrator) class Meta: db_table = 'Profile' def __str__(self): return self.user.username def get_screen_name(self): try: if self.user.get_full_name(): return self.user.get_full_name() else: return self.user.username except: return self.user.username def get_association_name(self): try: if self.user.association: return self.user.association else: return self.user.username except: return self.user.username class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True, unique=True) class Meta: db_table = 'Association' def __str__(self): return self.asoc_name def __unicode__(self): … -
Scrapy: run a spider from python script and wait until it end
I created a small Scrapy project with this structure: scrapyProject/ ├── scrapy.cfg └── scrapyProject ├── __init__.py ├── items.py ├── pipelines.py ├── settings.py └── spiders ├── crawl_products.py └── __init__.py The crawl_products.py contain the spider products_spider. To start the spider I am using: scrapy crawl products_spider Now I want to start the spider from another python script and wait until its execution end. IF IT CAN HELP : The other script from which I want to run the spider is a django view -
Occasion 503 error from google login callback, Django
Somehow I receive 503 error report related to Google Social Login. Does it mean Google occasionally broke down? I have a hard time to reproduce it on either development server or production server. Internal Server Error: /accounts/google/login/callback/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py", line 55, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py", line 116, in dispatch response=access_token) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/google/views.py", line 20, in complete_login resp.raise_for_status() File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 840, in raise_for_status raise HTTPError(http_error_msg, response=self) HTTPError: 500 Server Error: Internal Server Error for url: https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxxx&alt=json Environment: Django==1.8.8 django-allauth==0.24.1 -
How do the Django csrf token work
I have a Django applications that run various websites. On the site I have various forms that always submit to a baseview form url. On my form I have {% csrf_token %} The form works fine and i see the CSRF token generated properly. If I try to change or remove this token the submit will fail. Now if I record this whole process with Fiddler set to decrypt SSL, I can take that Post action and put it into the composer and as long as I don't modify the csrfmiddlewaretoken and I am submitting valid data it will work. The question is there something more I have to do in the view where the formprocessor lives to prevent other sites from accessing it, or is this a limitation of the csrfmiddlewaretoken -
Whitenoise + Django + Cloudfoundry - http 500 when compression is enabled
I've successfully deployed Django with Whitenoise on Cloudfoundry except for the compression. If I set on my settings.py to enable compression: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I get a 500 error and nothing on my cf logs. Please not that I don't have SSH access nor/heroku as this is running on Predix. My settings.py: STATIC_URL = "/media/" STATIC_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'itcave/media'), ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', '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', ] wsgi.py: from whitenoise.django import DjangoWhiteNoise from django.core.wsgi import get_wsgi_application import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "itcave.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) Please also note that all my static files are stored within a media folder at the same level as my settings.py file. -
Move django website from one server to another
I have a django website on a webserver and I want to change hosting service, how can i move the django website to the new server? And how can I make sure that it works the same? I am using SQLite Database so that shouldn be a problem. -
ajax request with data to vanilla python file
I have some maintenance scripts in python, and was working to create a quick html interface to work with in order to kick the stuff off and handle configuration with a GUI. I was thinking it would be as simple as ajax to a python file with some data params as follows: $.ajax({ type:"POST", url: "sample.py", data: {json: self.json, filename: self.filename}, success: function(){ console.log("success"); }, error: function(){ console.log("error"); } }).done(function(){ console.log("done"); }); and it found the file, but the response was the content of the python file, not an execution. For the ease of use, sample.py is just as follows: #!/usr/bin/python import os def main(): os.system("echo 'test file' > sampleFile.txt") if __init__ == "__main__": main() the file runs independently, but i am having 2 issues: 1: How do i get the ajax file to make the python run? 2: How do i catch and process the params. When looking at the file permissions, it says it has full control, so it doesnt seem to be something as easy as chmod +x sample.py I didnt want to go through all the overhead of creating a Django application just to do this, as it is a single page html file, with an … -
Django login form error styling
I am attempting to create a custom login page for users in django. Here is the template I placed under registration/login.html {% block content %} <div class="container login-container"> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-default">Login</button> </form> <br> <p><strong>-- OR --</strong></p> .... </div> {% endblock %} Here is how the page is reached" server/urls.py: from django.contrib.auth import views as auth_views ... url(r'^login/$', auth_views.login, name='login'), ... My issue is that I have no control over the way the errors or form objects are displayed and can find nothing in the documentation. If you know how I can control how the form is rendered that would be much appreciated. Thank you! -
Assign multiple variables in a with statement after returning multiple values from a templatetag
Is there a way to assign multiple variables in a with statement in a django template. I'd like to assign multiple variables in a with statement after returning multiple values from a templatetag My use case is this: {% with a,b,c=object|get_abc %} {{a}} {{b}} {{c}} {% endwith %} -
How do I create a many to many relationship with an existing record?
In my Django 1.11 blog app, I have a many to many relationship between authors and posts. # models.py class Post(models.Model): title = models.CharField(max_length=200) class Author(models.Model): name = models.CharField(max_length=200) posts = models.ManyToManyField(Post, related_name='authors') I could create a post with an author as follows: $ post = Post.objects.create(title='My post') $ post.authors.create(name='John Doe') But how can I create a post and author explicitly and connect them through the association? $ post = Post.objects.create(title='My post') $ author = Author.create(name='John Doe') $ post.authors.????(author) If I call post.authors.get_or_create(name='John Doe') it would create a new author, which is not what I want. I could access the join table directly by making it a separate model (PostAuthor), but is there a way to connect an existing author to the post through the QuerySet API? -
Django get form with data from the database
I am trying to create a form that allows users to edit their profile data. As such I want to have the most recent data from the database be displayed when the user goes to edit the form. Heres what I have so far: # models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) def __str__(self): return self.user.username # forms.py class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['location', 'birthdate'] # views.py class EditProfileFormView(View): form_class = EditProfileForm template_name = 'forums/edit-profile.html' def get(self, request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404('The User "' + username + '" could not be found.') if (not request.user.is_authenticated): return HttpResponseForbidden() elif (user.id is not request.user.id): return HttpResponseForbidden() form = self.form_class(None) return render(request, self.template_name, {'form': form}) Setting the form to form_class(None) is what gives me an empty form, however dropping user.profile in the same spot gives me an error 'Profile' object has no attribute 'get' -
Django administered Excel Download via IIS
I have a django project being served via IIS. In one of my django templates, I have the following. When the client hits the button, the excel file downloads. In development this works fine. In IIS this does not work. The status of http://SERVER/static/output.xlsx always returns as 404. {% load static %} <form action="{% static "output.xlsx" %}"> <input type="submit" value="Excel" /> </form> I only have one other file in my static folder, and its a css file. That loads ok via via the url. So I know its not an issue with the static folder setup. Instead its something in IIS. I see in MIME Types that xlsx is defined. Any help would be appreciated. -
Extracting a nested list with Django and replacing values
Thanks in advance for any assistance you can provide. I am building an app using the Django Rest Framework and Vue.js. I am consuming the Spotify API as well as providing data from the DRF. When i do an artist search using the following code: def get(self, request, *args, **kwargs): artist = services.spot_artist_search(self.kwargs['artist']) return Response(artist) It returns exactly what I expect which is an artist search from Spotify's API. The result looks something like this.(I am only showing the first two entries for brevity) { "artists": { "href": "https://api.spotify.com/v1/search?query=adele&type=artist&offset=0&limit=10", "items": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/4dpARuHxo51G3z768sgnrY" }, "followers": { "href": null, "total": 6175115 }, "genres": [ "dance pop", "pop" ], "href": "https://api.spotify.com/v1/artists/4dpARuHxo51G3z768sgnrY", "id": "4dpARuHxo51G3z768sgnrY", "images": [ { "height": 1000, "url": "https://i.scdn.co/image/ccbe7b4fef679f821988c78dbd4734471834e3d9", "width": 1000 }, { "height": 640, "url": "https://i.scdn.co/image/f8737f6fda048b45efe91f81c2bda2b601ae689c", "width": 640 }, { "height": 200, "url": "https://i.scdn.co/image/df070ad127f62d682596e515ac69d5bef56e0897", "width": 200 }, { "height": 64, "url": "https://i.scdn.co/image/cbbdfb209cc38b2999b1882f42ee642555316313", "width": 64 } ], "name": "Adele", "popularity": 85, "type": "artist", "uri": "spotify:artist:4dpARuHxo51G3z768sgnrY" }, { "external_urls": { "spotify": "https://open.spotify.com/artist/19RHMn8FFkEFmhPwyDW2ZC" }, "followers": { "href": null, "total": 3504 }, "genres": [], "href": "https://api.spotify.com/v1/artists/19RHMn8FFkEFmhPwyDW2ZC", "id": "19RHMn8FFkEFmhPwyDW2ZC", "images": [], "name": "Robyn Adele Anderson", "popularity": 42, "type": "artist", "uri": "spotify:artist:19RHMn8FFkEFmhPwyDW2ZC" }, { "external_urls": { "spotify": "https://open.spotify.com/artist/5yUp79jSBSGdkbufl2hmcY" }, "followers": { "href": null, … -
Get rid of 'en-us' in Django urls i18n
Using Django 1.8.17 I have a lot of 404 in my google stats. This is because some urls are formatted like this: http://www.example.com/en-us/some_content_here I can't figure how to get rid of these en-us lang, best would be to replace with en in this case. Here are my i18n settings: # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en' # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True LANGUAGES = (('de', gettext('German')), ('en', gettext('English')), ('es', gettext('Spanish')), ('it', gettext('Italian')), ('fr', gettext('French')), ('ru', gettext('Russian')), ('ja', gettext('Japanese')), ('pt', gettext('Portuguese')),) Is there a way to redirect to corresponding languages with default to en if nothing match ? -
Aggregation and track back relations to multiple models in a single view Django
I am doing first steps in Django and currently can't resolve further difficulties. Imagine we have next data scheme: class Categories(models.Model): name = models.CharField() class Inventories(models.Model): name = models.CharField(unique = True) unit = models.CharField() category = models.ForeignKey(Categories) class Suppliers(models.Model): name = models.CharField() class InventoryReceiving (models.Model): name = models.ForeignKey(Inventories, related_name='item_received') quantity = models.DecimalField(max_digits=6, decimal_places=2) supplier = models.ForeignKey(Suppliers, related_name = 'item_supplier') I would like to group_by names in InventoryReceiving to get distinct values and aggregated quantity fields. Then track back relations and get a single grouped_by name table with human readable name, unit, category, supplier and quantity labels. I came up with an expression which return name_id (I need names from the related table) and sum: inventory_list = InventoryReceiving.objects\ .values('name')\ .annotate(agg_sum=Sum('quantity')) -
Django Messages not working as Expected
I am trying to display a warning banner when a particular Django view returns a message to inform the user that the action has failed, I am not using forms. I think I am doing everything correctly, however I cannot get a message to display on my site. I have looked around on stack overflow and all the solutions I come across are either already in place or not relevant for what I am trying to do. Below is all code I have previously seen asked for, please let me know if you need more! settings.py INSTALLED_APPS = [ 'serversignup.apps.ServersignupConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py ... ... ... else: messages.add_message(request, messages.WARNING, 'This machine has already been claimed.') return render(request, 'serversignup/index.html', context) index.html ... ... ... <div class="col-sm-2 col-md-12 main-content"> {% if messages %} <div class="alert alert-warning"> {% for message in messages %} <strong>Action Failed: </strong> {{ message }} {% endfor %} </div> {% endif %} The result is that the page refreshes, and does … -
ValidationError [u'ManagementForm data is missing or has been tampered with'] only in special cases
When editing a model field through Django Admin, I'm getting a [u'ManagementForm data is missing or has been tampered with'] validation error. Steps: Edit a model through Django Admin and insert a special character (é,ñ) The data is saved OK. When editing again the model field (charField) the validation error is raised, whatever the input is. When editing without special characters, the form is working ok. Django Version: 1.4.21 Python Version: 2.7.9 -
Django - Best way to implement authorization (both on a per-role as well as per-user basis)?
I'm working on a django web-app that requires two kinds of authorization: Role-based (users should not be able to access urls that are for other roles) User-based (Users of the same role should not be able to access content of other users) For eg, we have a role called HOD (head of department). These are some of the urls that they can access: url(r'^retest/(?P<retest_id>[0-9]+)/$' , views.details, name='details' ), url(r'^retest/(?P<retest_id>[0-9]+)/accept$' , views.accept, name='accept' ), url(r'^retest/(?P<retest_id>[0-9]+)/request$' , views.request, name='request' ), url(r'^retest/(?P<retest_id>[0-9]+)/accepted$' , views.accepted, name='accepted' ), url(r'^retest/(?P<retest_id>[0-9]+)/retreq$' , views.retreq, name='retreq' ) Some of the controller functions that correspond to these are as follows: @login_required def details(request, retest_id): try: retest= Retest.objects.get(pk=retest_id) except Retest.DoesNotExist: raise Http404("Request does not exit") return render(request, 'retest/details.html' , { 'retest': retest }) @login_required def accept(request, retest_id): retest = get_object_or_404(Retest, pk=retest_id) # update is_hod attribute only if the request is a POST. if request.method == 'POST': retest.is_hod = True retest.save(update_fields=['is_hod']) return render(request, 'retest/details.html' , {'retest': retest}) Now, these are the concerns that I have and want to safeguard against: Right now, anyone can view any retest request (views.details function), irrespective of role. How should I implement this authorization? Through group filtering or using the inbuilt permissions system in django? Either of … -
Django wildcard in request.path
don't know much about django but trying to resolve something quickly for a client, they want some content to only show up on certain pages but the code is nav (used across all pages) hence was trying to add: {% if request.path == '/*/projects/' %} something {% endif %} but this doesn't work. Each project has a unique number, hence unique url, but I cannot do: {% if 'projects' in request.path %} something {% endif %} as some pages on the site contain "projects" in the url where we do not want "something" showing. Hence I wanted to use a simple * as wildcard in url, but this does not work. Many thanks! -
Django- Object representation based on a Foreign Key
I'm testing a relatively simple model in my Django project: class Restricted_Form(models.Model): Form = models.ForeignKey(Form) Authorized_Users = models.ManyToManyField(User) Authorized_Groups = models.ManyToManyField(Group) The point is to simply associate each form with some users, and groups. In the Django Admin, I want to have these Restricted_Fom objects listed, being represented by the "title" of the Form they are associated to (instead of having them all listed indistinguishably as Restricted_Form object) . I've tried something like @property def __str__(self): return self.Form.title but it's incorrect. How do I achieve this? Is there a way to, for example, have another field, that's a string, that automatically populates itself based on the other field (the ForeignKey one, Form)? -
Can you declare multiple with variables in a django template?
I know it's not good practice, but is there a way to declare multiple variables in a with statement in a django template. For example I want to do something like this: {% with a="a", b="b", c="c" %} {{a}} {{b}} {{c}} {% endwith %} -
How to add ModelChoice field of django form in template
Currently, I am developing a web application. I am using forms to render the fields. I have multiple ModelChoiceField in my application. I am facing error in rendering ModelChoiceField. What I was done is... <div class="row"> <div class="input-field col s6"> {{ form.state }} <label for="id_company">Company</label> {{ form.country }} </div> </div> Here state and country are the two ModelChoiceFields. It's only displaying labels and the field is not visible. But when I did inspect element, I am able to see the choices. But in the template it's not showing correctly. What may be the reason? -
How to show input value next to it ? Python
So I'm sending an item to my html page and put a value off this item in an input. What i want is when i change the input, i want to dynamically print the new value next to the input. Something like that : <input type='text' value="{{item.qty}}"/> {{myNewInputValue}} I know how to do this with angular but don't know if it's possible with Python Thanks