Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get singular value from a generator?
I'm writing an app to monitor chicken deaths in a poultry farm and have the following code: today = datetime.date.today() deaths = (sum(cd.count) for cd in ChickenDeath.objects.filter(date__gte=datetime.date(today.year, today.month, 1))) print(deaths) My problem is it just prints out <generator object chickens_overview.<locals>.<genexpr> at 0x110010678> instead of the actual sum. I've tried next(deaths) as well however I just get the error 'int' object not iterable. Is there another way to get the value from this generator? -
How to write code that works in both Python 2 and Python 3?
A Django website I maintain currently uses Python 2.7 but I know that I'll have to upgrade it to Python 3 in a couple of months. If I'm writing code right now that has to work in Python 2, is there a Pythonic way to write it such that it would also work in Python 3 without any changes if I know what the syntax is going to be in Python 3? Ideally I'd like the code to continue to work even after the upgrade without changing it but it would be easy for me to spot where I've done this in the codebase so that I can change the code when I have time. Here's an example of what I'm talking about: # Python 2 uses 'iteritems' def log_dict(**kwargs): for key, value in kwargs.iteritems(): log.info("{0}: {1}".format(key, value)) # Python 3 uses 'items' def log_dict(**kwargs): for key, value in kwargs.items(): log.info("{0}: {1}".format(key, value)) -
django.db.utils.DatabaseError: ORA-30673: column to be modified is not an identity column
thanks everybody, I have a django project, this is my enviroment: Database: Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production Python: Python 3.5.1rc1 cx-Oracle==6.3 Django==2.0.4 I am trying this: python manage.py test I am getting this error: django.db.utils.DatabaseError: ORA-30673: column to be modified is not an identity column Thanks. -
Cannot add a new user after extending user model in django
I can't add a new user it just says that the foreign key constraint failed I don't know why. I don't know which foreign key is violated and why is it violated. Here is my models.py: from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser def user_avatar_path(instance, filename): return 'user_{0}/avatar/{1}'.format(instance.id, filename) class board(models.Model): name = models.CharField(max_length=20) def __str__(self): return (self.name) class User(AbstractUser): boards = models.ManyToManyField( board, through='board_member', related_name="members") def __str__(self): return self.username class list(models.Model): title = models.CharField(max_length=20) board = models.ForeignKey( board, related_name="lists", on_delete=models.CASCADE) class board_member(models.Model): User = models.ForeignKey( User, related_name="memberships", on_delete=models.CASCADE) board = models.ForeignKey( board, related_name="memberships", on_delete=models.CASCADE) access = models.CharField(max_length=20) def __str__(self): return ("%s is %s in board %s" % (self.user, self.access, self.board)) class card(models.Model): list = models.ForeignKey(list, related_name="cards", on_delete=models.CASCADE) text = models.CharField(max_length=100) date = models.DateField(auto_now=True) due = models.DateField() flag = models.CharField(max_length=20) can anyone help me please? -
Django : creating a Cluster and registering its nodes
I have just finished tutorials on Django basics and Django REST Framework, and now I would like to create a Web Application where a User ( admin ) can create a new cluster ( via Django Form class ) , register N nodes in it ( via Django Form class ), and store that information in configured DB. Problem is that I have no idea where to start. I am not sure how clusters actually work, and what is needed for ones implementation. This is a personal project of mine, and the main idea is to train a Neural Network on one of the clusters once they are registered. I would really appreciate any kind of reference, literature or idea on how to get started with this. Thank you in advance! -
HTML code to pass a drop down search to a database via django and return results [duplicate]
This question already has an answer here: django - post form on select 1 answer I am working on my senior capstone project for IT at ASU. I have never worked with Django. I can find plenty of information on searches with Django but it doesnt tell me how to setup my HTML code to do this. my current HTML code looks like this <from id="searchform" method="get" accept-charset="utf-8"> <tr> <td> Part Number: <select name="Part Number"> <option value="3750">3750</option> </select></td> </tr> </form> what do i need to add to pass this search to Django and get results? thanks -
How to add serializers.RelatedField() to Meta class fields in django rest framework
I have a simple API for a football game. I am using Django 2.0 and Django REST framework. I have these two models for Team and Player class Team(models.Model): name = models.CharField(max_length=60) budget = models.FloatField(default=100.0) # Millions? 114.53 M user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE) competitions = models.ManyToManyField(Season) def __str__(self): return self.name class Player(models.Model): name = models.CharField(max_length=50) age = models.IntegerField(null=True) inMarket = models.BooleanField(default=False) lastInMarket = models.DateTimeField(null=True) team = models.ForeignKey(Team, null=True, on_delete=models.DO_NOTHING, related_name='team') As far as I've read, this is the properly way of defining OneToMany relations, this is, a Team has many Players. Now, in the other hand, I want to display an APIView for a concrete team to show all the information of the team including the information of players. I have these two Serializers: class PlayersSerializer(serializers.ModelSerializer): team = serializers.RelatedField(read_only=True) class Meta: model = Player fields = ('id', 'name', 'age', 'position', 'team') def create(self, validated_data): pass def update(self, instance, validated_data): pass class TeamSerializer(serializers.ModelSerializer): players = serializers.RelatedField(read_only=True, many=True) class Meta: model = Team fields = ('name', 'user', 'competitions') def create(self, validated_data): return Team.objects.create(**validated_data) def update(self, instance, validated_data): instance.players = validated_data return instance This is the best way I've found so far of retrieving the players of the team. However, I'm not … -
Compare request.path to path saved in user models Django
I am attempting to build a referral system based on pinax-referrals. I am only using the creation of the referral URL from that service. I am trying to track when a referral URL has been used to access the site and adding a +1 to the User that referred the new user. I have the paths working, and they direct to my home page, now I need to compare the request.path that was used to all users, and find the corresponding one. My trouble is getting the request.path and comparing it. It seems to skip over the referral pathhttp://127.0.0.1:8000/referrals/some_long_stuff and just show the reversed path, which is home /. Views.py def index(request): if request.method == 'GET': path = request.get_full_path() try: c = UserAddress.objects.get(referral_link=path) c.referral_count = int(c.referral_count) + 1 c.save() return HttpResponse("working") except: return HttpResponse('not working') return render(request, 'ico_login/index.html') models.py class UserAddress(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_address') btc_address = models.CharField(max_length=300, blank=True, default=' ') eth_address = models.CharField(max_length=300, blank=True, default=' ') ltc_address = models.CharField(max_length=300, blank=True, default=' ') tokens = models.DecimalField(max_digits=12, decimal_places=8, default=0) referral_link = models.CharField(max_length=300, blank=True, default=' ') referral_count = models.IntegerField(max_length=200, blank=True, default=0) @receiver(post_save, sender=User) def create_user_address(sender, instance, created, **kwargs): if created: UserAddress.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_address(sender, instance, **kwargs): instance.user_address.save() urls.py urlpatterns = … -
Syntax in HTML from my code looks alien
I was given an assignment and I came across this line of code in one of HTML file of problem set. What does {% random code here %} means in HTML, is it a comment or what? I tried google but could not find it. one TODO looks like this: {% extends "layout.html" %} {% block body %} <div class="col"> <form action="/compare" enctype="multipart/form-data" method="post"> <!-- TODO --> </form> </div> {% endblock %} -
Model property as a filter field in API
I have this model: class Auction(models.Model): start_price = models.IntegerField() price_step = models.IntegerField() finish_time = models.DateTimeField() @property def is_active(self): return self.finish_time > timezone.now() I also have this in my serializer class: class AuctionSerializer(serializers.ModelSerializer): is_active = serializers.ReadOnlyField() class Meta: model = Auction fields = '__all__' And this in my view class: class AuctionViewSet(ModelViewSet): queryset = Auction.objects.all() serializer_class = AuctionSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('is_active',) But it throws "'Meta.fields' contains fields that are not defined on this FilterSet: is_active". How do I properly implement filtering by model property not just model field? -
how could i make Emailfield case insensitive on django?
i'm new at django and i run into this little issue when at the moment to check if there is the same email address on the db it doesn't take into account if it has a different letter case configuration, is there any method to achieve this? -
Django Media, mp4 serving
I am working on a Django project right now. I am serving the media files with ease, but when I am trying to fetch a video from the media folder I have the following response. The HTTP response code is: 206 Partial Content (from disk cache) and console log is resource interpreted as document but transferred with mime type video/mp4 Anyone knows how I am able to solve this? -
How can I link to two different DetailView pages (two different models)?
I tried to use this answer from @alasdair: Multiple models generic DetailView to template I added two separate urls to the urls.py file in my application folder, however I'm still getting an error. Most recently I'm getting an error that 'detail is not a valid view function or pattern name. Can someone respond with an example of how to make this work, but with each of the necessary code bits? (ie models.py, views.py, urls.py and an html page with links to both pages)? Thank you -
Deleting rows from jQuery Datatables Django
there is a problem. DO NOT delete records in datatables. All the code seems to be correct, but for some reason instead of deleting the record, it simply reboots ajax. Is there a handler on the server side? $(document).ready(function() { var dt_table = $('#DataTable1').dataTable(); $(' #DataTable1 tbody').on( 'click','tr', function () { if ( $(this).hasClass('selected') ) { $(this).removeClass('selected'); } else { dt_table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } } ); $('#DeleteButton').click( function () { dt_table.row('.selected').remove().draw( false ); } ); } ); -
Django: Initialize classes from POST JSON data
I am writing a Django app, which will send some data from the site to a python script to process. I am planning on sending this data as a JSON string (this need not be the case). Some of the values sent over would ideally be class instances, however this is clearly not possible, and the class name plus any arguments needed to initialize the class must some how be serialized into a JSON value. This could be achieved with the code below, but it has several problems: My attempt I have put all the data needed for each class, in a list and used that to initialize each class: import json class Class1(): def __init__(self, *args, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) self._others = args class Bar(): POTENTIAL_OBJECTS = {"RANGE": range, "Class1": Class1} def __init__(self, json_string): python_dict = json.loads(json_string) for key, value in python_dict.items(): if isinstance(value, list) and value[0] in Bar.POTENTIAL_OBJECTS: setattr(self, key, Bar.POTENTIAL_OBJECTS[value[0]](*value[1], **value[2])) else: setattr(self, key, value) example = ('{ "key_1":"Some string", "key_2":["heres", "a", "list"],' '"key_3":["RANGE", [10], {}], "key_4":["Class1", ["stuff"], {"stuff2":"x"}] }') a = Bar(example) The Problems with my approach Apart from generally being a bit messy and not particularly elegant, there are other … -
Wrong mocking inside one test case of two different urls in terms of GET params using responses
I am using responses library (https://github.com/getsentry/responses) for mocking response data in test. Inside one test case I add two responses for GET with different url in terms of GET params. 1) https://maps.googleapis.com/maps/api/geocode/json?latlng=52.212917394179335,20.983095079636158&key=key 2) https://maps.googleapis.com/maps/api/geocode/json?latlng=52.20212145989611,21.006183521756945&key=key what happens? my test case inside in class overriden by django.test.TestCase looks like: @responses.activate def test_address_is_updated_correctly_when_spot_location_changed(self): latitude_1, longitude_1 = 52.226297, 20.982749 url = REVERSE_GEOCODING_URL.format( latitude=latitude_1, longitude=longitude_1, api_key=settings.GOOGLE_MAP_API_KEY ) responses.add( responses.GET, url, body=json.dumps(RESPONSE_GEOCODING_MOCK_2), content_type="application/json" ) s1 = SpotFactory( name='test', location=Point(longitude_1, latitude_1) ) s1.save() street_before = s1.address_street self.assertEqual(street_before, 'Kolejowa') latitude_2, longitude_2 = 52.27904, 20.980366 url2 = REVERSE_GEOCODING_URL.format( latitude=latitude_2, longitude=longitude_2, api_key=settings.GOOGLE_MAP_API_KEY ) responses.add( responses.GET, url2, body=json.dumps(RESPONSE_GEOCODING_MOCK), content_type="application/json" ) s1.location.coords = (longitude_2, latitude_2) s1.save() s1 = Spot.objects.get(pk=s1.pk) self.assertEqual(s1.address_street, 'Mickiewicza') firs assert is OK the second one FAILS because, the response is from the old one mock. -
django get form data in dict type
I have a form with many part. How to get these data in a dictionary type. <form method="post" action=""> <p> <label>first_field</label><br /> <input type="text" id="first_field" name="field[1][points]" /><br /> <input type="input" name="field[1][group]" checked /><br /> </p> <p> <label>second_field</label><br /> <input type="text" id="second_field" name="field[2][points]" /><br /> <input type="input" name="field[2][group]" checked /><br /> </p> </form> and I hope to get a dict at backend like follow: print(request.POST['field']) >>> { {'points':points_data_1, 'group':group_data_1}, {'points':points_data_2, 'group':group_data_2}, } how can i do? thanks. python 3.6 django version = 1.11.8 -
Getting username of logged in user in django
I am new to Django and I just want to find a way to get the username of a logged in user and use it to get the boards of the user. I may have done the models wrong by adding another user model but I would like some help in getting the user's username. Here is my views file: from django.shortcuts import render from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth import authenticate,login from django.contrib.auth.models import User from .models import board_member,user # Create your views here. def index(request): # Login form submitted? if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) # Login succeeded if user is not None: login(request, user) return HttpResponseRedirect(reverse('login_success')) # Login failed return HttpResponseRedirect(reverse('login_fail')) return render(request, 'Boards/login.html') def login_success(request): return render(request, 'Boards/Homepage.html') def getboards(request): username = request.user.get_username() boards = [] for Memberships in board_member.objects.all(): if username == Memberships.user.username: boards.append(Memberships.board) return render(request, 'Boards/Homepage.html', {'boards': boards, 'username':username}) def login_fail(request): return render(request, 'login_fail.html') and this is my models file: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class board(models.Model): name = models.CharField(max_length=20) def __str__(self): return (self.name) class user(models.Model): username … -
DRF send media file to download in client
im tying to send requested video file to client to start download .. file addrees(that is hashed) is comming to server, and it should return file to download ... Now when i enter url like below in browser , it works , " localhost:8000/api/v1/store/download/?q=e8000074ab4d,eJwLyygpKbDS18/JT07MycgvLrGyMDAw0C8tyMlPTNFPy8xJ1U9M1MstMOEqMODSAwB4gQ8P" but in client side when i make the same request i takes error like this: Http failure response for (unknown url): 0 Unknown Error" name: "HttpErrorResponse" in firefox and in chrome i takes empety response frome server my view is like this class DownloadVideoAPI(APIView): def get(self, request, ): query = request.GET.get('q') pre = query.split(",") hash = pre[0] dec = pre[1] de_hash = decode_data(hash, dec) if de_hash is not None: resp = HttpResponse() resp['Content-Disposition'] = 'attachment; filename=%s' % de_hash resp['content_type'] = 'application/force-download' return resp else: return Response(status.HTTP_400_BAD_REQUEST) where is the problem and how can i fix it? -
data cannot be saved in form
data cannot be saved in form.I wrote html like <form action="/app/save" method="POST"> <input id="classname" name="classname"> <input id="score" name="score"> <input id="course" name="course"> <button type="submit">SEND</button> </form> in forms.py from django import forms from .models import Student class SaveForm(forms.ModelForm): class Meta: model = Student fields = ("classname", "score", "course") in views.py @csrf_exempt def save(request): save_form = SaveForm(request.POST or None) print(save_form.is_valid()) if request.method == "POST" and save_form.is_valid(): item = save_form.save(commit=False) classname = request.POST.get("classname", "") score = request.POST.get("score", "") course = request.POST.get("course", "") item.classname = classname item.score = score item.course = course item.save() return render(request, 'index.html') When I run this codes ,put data in html and put SEND button,save method can be called but data cannot be saved.print(save_form.is_valid()) shows False.I really cannot understand why I can't send data.What is wrong in my codes?How should I fix this? -
I was trying to use apps.get_model function. And, I want to use this without specifying the app name, is there any way to do that.
I was referring this link : Django: Get model from string? . And, I found there is a way to do this by using apps.get_model. But,In my scenario, the model can be from other apps. So, I can't actually name the app_name here. Is there any way to do this ? -
Custom prefix for redis keys with Celery
I am using redis as a broker between Django and Celery. The redis instance I have access to is shared with many other applications and so the broker is not reliable (the redis keys it uses are deleted by others, the messages often get sent to workers in other applications). Changing redis database does not solve the problem (there are few databases and many applications). How can I configure Celery to prefix all the keys it uses with a custom string? The docs mention ways to add prefixes to queue names, but that does not affect the redis keys. The underlying library (Kombu) does not seem to let the user prefix the keys it uses as far as I can tell. -
How do I make djangorestframework play nice with MongoDB
So I'm currently using djangorestframework and it is intended to work well with Django's models. At the moment everything works just fine with MySql as a db, now one of the requirements is to switch to a MongoDB cluster. Apart from the authorisation/authentication part which is already written and works nice with MySql, I have to make records into the database which are nothing but nested JSONs. I don't want to change the models that are already written. They must always remain the same regardless of what database I use. I've almost managed to do it with the help of djongo, basically I just installed djongo and used it as my database engine. Now I need to construct a model, a mongo document model, to be specific, in order to be able to write jsons into my mongo cluster. So in accordance with the MSV pattern, I have to write a model, serializer and a view. #models.py class MyModel(models.Model): data = models.TextField() #serializers.py class MySerializer(serializers.ModelSerializer): data = serializers.JSONField(binary=True) def create(self, validated_data): test = MyModel(data=validated_data) test.save() return test class Meta: model = MyModel fields = ['data'] #views.py class MyView(APIView): serializer_class = MySerializer def post(self, request): serializer = self.serializer_class(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() … -
MongoEngine update double nested subdocument value
I want to update double nested subdocument value, My document looks something like this: { "_id": ObjectId("5addb3f69dc9a505e4b1000f"), "name": "Movie name", "advertisement": [ { "id": ObjectId("5addb8089dc9a5061ff3549b"), "name": "Drinks Ad" "sub_advertisement": [ { "id": ObjectId("5addb81f9dc9a5061ff354a9"), "title": "Pepsi Ad.", "url": "ad url" }, { "id": ObjectId("5addb81f9dc9a5061ff354a9"), "title": "Tang Ad.", "url": "ad url" } ] }, { "id": ObjectId("5ae417009dc9a505a20bc20d"), "name": "Cars Ad" "sub_advertisement": [ { "id": ObjectId("5ae4172f9dc9a505a20bc237"), "title": "Ford Figo", "url": "ad url" }, { "id": ObjectId("5ae417629dc9a505a20bc263"), "title": "Ritz", "url": "ad url" } ] } ] } I want to update the title of sub_advertisement of second advertisement from 'Ritz' to 'Maruti' having ID: 5ae417629dc9a505a20bc263. I'm using the mongoengine command: Movie.objects(id="5addb3f69dc9a505e4b1000f", advertisement__id="5ae417009dc9a505a20bc20d", advertisement__sub_advertisement__id="5ae417629dc9a505a20bc263").update_one(set__advertisement__S__sub_advertisement__S__title="Maruti") but I'm getting error: Update failed (Too many positional (i.e. '$') elements found in path 'advertisement.$.sub_advertisement.$.title') -
django ignore slash in url and take parameter
hi i have url like this: path('api/v1/store/download/<str:ix>/', DownloadVideoAPI.as_view(), name='download'), it accept long string . i want keep allthing after download in above url as parameter . but when i enter long string that contain some slash django say page not found for example when if enter "/api/v1/store/download/asdasd2asdsadas/asdasd" will give me 404 not found ... how can i do that? this is my view: class DownloadVideoAPI(APIView): def get(self, request, ix): pre = ix.split(",") hash = pre[0] dec = pre[1] de_hash = decode_data(hash, dec)