Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ProgrammingError at /api/contacts/
I get the following error in my app: I've have this model: from django.db import models from apps.account.models import Account from .category import Category class Contact(models.Model): name = models.CharField(max_length=60) number_phone = models.CharField(max_length=15) address = models.CharField(max_length=100) category = models.OneToOneField(Category, on_delete=models.CASCADE) created_by = models.ForeignKey( Account, on_delete=models.CASCADE, related_name='contacts') created_at = models.DateTimeField(blank=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, auto_now=True) def __unicode__(self): return self.name this view: class ContactViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer permission_classes = (permissions.IsAuthenticated, IsAdminContact) # def get_permissions(self): # if self.request.method in permissions.SAFE_METHODS: # return (permissions.AllowAny(),) # return (permissions.IsAuthenticated(), IsAdmin(),) The error begin when I define the following permissions for my api: class IsAdminContact(permissions.BasePermission): def has_permission(self, request, view): if request.user.role == "admin": return request.user.role == "admin" return False def has_object_permission(self, request, view, contact): if request.user.role == "admin": return request.user.role == "admin" return False All was right, but when I define the permissions for my api contacts, boom!! this error... I dont know which is the problem, I tried all, but neither result... What is the problem? -
Error Key (user_id)=(1) is not present in table "auth_user" when migrating
I am running into this error when i migrate.Is there any way to save data on my database.I know that dropping the auth_user table will fix the issue. I am running postgresql. Thanks! FATAL ERROR - The following SQL query failed: ALTER TABLE "api_poi" ADD CONSTRAINT "user_id_refs_id_20f256ff" FOREIGN KEY ("user_id") REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED; The error was: insert or update on table "api_poi" violates foreign key constraint "user_id_refs_id_20f256ff" DETAIL: Key (user_id)=(1) is not present in table "auth_user". -
Is there a way to write into docx file the stored TinyMCE html content properly (django python-docx)?
I am working on a project that stores some data on the database and writes them into docx file i am using for that python-docx lib, some fields should be in format of richtext and in wysiwyg format. In django models I decided to use htmlfield and use tinymce as wysiwyg editor. Because the database stores this data as html i needed to convert this html to text so i used html2text library in python. The problem is the html2text doesn't convert the data properly, the reason for that is most probably the html content is in format richtext, is there a way to convert the data properly and save it to docx file with python ? -
ImportError: cannot import name Profile django
I have created all my models in admin's model.py file, this admin app is my custom defined app, Now i want to use one of my model defined in admin's model.py file in my home's view.py file. so as per documentation i have write this code in home's model.py file. from django.db import models from admin.models import Profile Profile is my model class that i have defined in admin's model.py file. but its giving error ImportError: No module named models and if i write this code in home's model.py file from django.db import models from models import Profile it gives me error ImportError: cannot import name Profile Profile class in admin's model.py file is class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) start_date = models.DateField() phone_number = models.CharField(max_length=12) address = models.CharField(max_length=225) subscription = models.BooleanField(default=False) How can i use this Profile model class defined in admin app in home's view.py file. Please note that my admin app is custom defined app. Thanks -
Django Ajax response date and time format
Got a problem... I use Django, SQLite, jquery and AJAX. The problem is that when I get date and time from database it looks weird. Is there any way to display it normally? as dd/mm/yyyy HH:MM Modeles.py class QueryHistory(models.Model) : userID = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True, blank=True) View.py queries_list = serializers.serialize( 'json', (QueryHistory.objects.filter( userID = request.session['user_id'] ).order_by('-id')[:5]) ) return HttpResponse(json.dumps(queries_list), content_type="application/json") Js.js success : function(response) { var queries_list = jQuery.parseJSON(response); console.log(response); } Result: 2016-09-21T06:43:26.693Z Shold be: 21/09/2016 06:43 -
Get value of specific row in Django models
I'm trying to get a specific row through the get function but it returns more values than it should. My code in view: loan_amount = Transactions.objects.values('amount').get(amount__lt = 0, loans = l) There will be one negative value in this table, I want that value returned. The above code returns: %7B'amount':%20Decimal('-2000.00')%7D This value is from the url, because I'm passing this value as parameter to another view. I only want the -2000 value. What query option should I use? Any help or direction would be appreciated, Thanks in advance, -
Should I handle ajax requests in vanilla Django or rest Django?
I have a bunch of ajax requests on my website (ex. upvote sends request to server) Should I integrate this functionality server side just with another view function Or is it recommended that I shove all the necessary views into a Django rest framework? -
Swagger Response Messages using Django
views.py: from django.http import JsonResponse from rest_framework import schemas from rest_framework import status, response from rest_framework.decorators import api_view, renderer_classes from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer from DjangoProject.settings import db from DjangoProjectApp.serializers import RestaurantsSerializer @api_view() @renderer_classes([OpenAPIRenderer, SwaggerUIRenderer]) def schema_view(request): generator = schemas.SchemaGenerator(title='Restaurant API') return response.Response(generator.get_schema(request=request)) @api_view(['GET']) def restaurant_list(request): if request.method == 'GET': restaurantCollection = db.Restaurant restaurantlist = [] for s in restaurantCollection.find(): restaurantlist.append(s) serializer = RestaurantsSerializer(restaurantlist, many=True) return JsonResponse(serializer.data, status=status.HTTP_201_CREATED, safe=False) models.py: from django.db import models class Restaurant(models.Model): _id = models.TextField() name = models.TextField() rating = models.IntegerField() serializers.py: from rest_framework import serializers from DjangoProjectApp.models import Restaurant class RestaurantsSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = ('_id', 'name', 'rating') Now, how I can show the Response Messages in Swagger using Django. In Response Messages there is only 200 is showing as Response Code. I need to show the responses for different Status Codes. I need the full description for this. Thanks in advance. -
Django REST framework serialized field containing unexpected characters in test case environment
I am having two model definitions CTA and VariationCTA as follows: class CTA(AbstractTimestampClass): page = models.ForeignKey(Page, related_name='related_page_ctas') css_path = models.CharField(max_length=1000) source_content = models.TextField() category = models.CharField(max_length=100) subcategory = models.CharField(max_length=100) ctype = models.CharField(max_length=25, choices=CTA_TYPE_CHOICES, default=CTA_TYPE_HTML) deleted = models.BooleanField(default=False) class VariationCTA(AbstractTimestampClass): variation = models.ForeignKey(Variation, related_name='related_variation_ctas') cta = models.ForeignKey(CTA, related_name='related_cta_variation_ctas') target_content = models.TextField() deleted = models.BooleanField(default=False) To combine these two models I am making use of a serializer as follows: class PageCTASerializerForVariation(serializers.ModelSerializer): variation = serializers.SlugRelatedField( read_only=True, many=True, source='related_cta_variation_ctas', slug_field='variation' ) target_content = serializers.SlugRelatedField( read_only=True, many=True, source='related_cta_variation_ctas', slug_field='target_content' ) class Meta: model = CTA fields = ('id','css_path', 'source_content', 'category','subcategory', 'ctype', 'target_content','variation') The serializer is invoked as follows: PageCTASerializerForVariation(page.related_page_ctas.get(CTA Model Instance).data When the API is used from the browser the serialized instance is a follows: {'category': "Title", 'subcategory': "Page Title", 'target_content': u'asjbsnak', 'source_content': u'hsdvhas', 'ctype': 'HTML', 'css_path': u'asdjbjsdansdas>sakdbja>dafhds', 'id': 1} But when I call it through the test case,the serialized instance is as follows: {'category': u"[u'Title']", 'subcategory': u"[u'Page Title']", 'target_content': u'asjbsnak', 'source_content': u'hsdvhas', 'ctype': 'HTML', 'css_path': u'asdjbjsdansdas>sakdbja>dafhds', 'id': 1} Notice the category and subcategory fields in the serialized instances above. In the normal API call they are output as a normal string(this is the expected output),whereas in the test case call they are output as … -
Django ORM delete all then restart id to 1
As the title says. I have a command: Artist.objects.all().delete() But when I do: Artist.objects.create(name="Hello World") the id still continues like this object's id is 13 and I want it to go back to 1 after deleting all. How is it possible with ORM? I even tried: Artist.objects.create(id=1, name="Hello World") It will add an object with id 1 but the next time I add it will still continue the primary key increment -
Stuck in a django migration IntegrityError loop: can I delete those migrations that aren't yet in the db?
So, I committed and pushed all my code, and then deployed my web app. Then, I added a new model, which (for a reason I now understand), created an IntegrityError (django.db.utils.IntegrityError: insert or update on table "foo" violates foreign key constraint "bar"). However, even if I comment out this model (so that git status comes up with nothing but commented code), the Error still happens. If I connect to my db via a different python instance and download select * from django_migrations;, the latest db migration: 0020 there is eight migrations away from my latest local migration: 0028. --> My question is: is it safe for me to delete my local 0021-0028 migrations? Will this fix my problem? -
Paginating static assets display in Django
In a Django project, I have a list of emojis in the static folder which I need to display. I want it to be paginated. Normally, one paginates data objects via passing a queryset to Paginator class, or obfuscating all of that and using a ListView. But here, I don't have data objects; I have static assets numbering 200 and I want to use pagination to display them. Maybe the same rules apply, but I can't seem to cleanly wrap my head around this. Can someone give me an illustrative example of how to achieve this? Thanks in advance. Ideally, I don't want to have to build the static pages manually. -
boto3 'str' object has no attribute 'get
I am following the example at https://devcenter.heroku.com/articles/s3-upload-python for uploading files directly to s3 from the client and am coming up with errors views.api.sign_s3: def sign_s3(request): S3_BUCKET = os.environ.get('S3_BUCKET') file_name = request.GET.get('file_name',False) file_type = request.GET.get('file_type',False) s3 = boto3.client('s3') presigned_post = s3.generate_presigned_post( Bucket = S3_BUCKET, Key = file_name, Fields = {"acl": "public-read", "Content-Type": file_type}, Conditions = [ {"acl": "public-read"}, {"Content-Type": file_type} ], ExpiresIn = 3600 ) return json.dumps({ 'data': presigned_post, 'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name) }) settings.py: os.environ['S3_BUCKET'] = 'mybucketname' os.environ['AWS_ACCESS_KEY_ID'] = 'myaccesskey' os.environ['AWS_SECRET_ACCESS_KEY'] = 'mysecretaccesskey' html file <input id="file_input" name="video_files" type="file"> <!-- other html omitted --> <script> (function() { document.getElementById("file_input").onchange = function(){ var files = document.getElementById("file_input").files; var file = files[0]; if(!file){ return alert("No file selected."); } $(files).each(function(i,file){ getSignedRequest(file); }); }; })(); function getSignedRequest(file){ var xhr = new XMLHttpRequest(); console.log(file); xhr.open("GET", "/api/sign_s3?file_name="+file.name+"&file_type="+file.type); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status === 200){ var response = JSON.parse(xhr.responseText); uploadFile(file, response.data, response.url); }else{ alert("Could not get signed URL."); } } }; xhr.send(); } function uploadFile(file, s3Data, url){ var xhr = new XMLHttpRequest(); xhr.open("POST", s3Data.url); var postData = new FormData(); for(key in s3Data.fields){ postData.append(key, s3Data.fields[key]); } postData.append('file', file); xhr.onreadystatechange = function() { if(xhr.readyState === 4){ if(xhr.status === 200 || xhr.status === 204){ document.getElementById("preview").src = url; document.getElementById("avatar-url").value = … -
How To Make Function Perform Faster & More Efficient
I have this function that does a pretty difficult lookup scanning the JSONField via django/psql db with some specific arguments such as the player id, start date, the specific statistic and then returns an average by going back the specified games back. def player_running_average2(player_id,start_date,games_back,statistic): starting = True previous_games = Match.objects.filter(Q(start_date__date__lt=datetime(start_date.year, start_date.month, start_date.day),home__players__contains=[{'playerId': player_id, 'isFirstEleven': starting}]) | Q(start_date__date__lt=datetime(start_date.year, start_date.month, start_date.day),away__players__contains=[{'playerId': player_id, 'isFirstEleven': starting}])) previous_games = previous_games.order_by("-start_date")[:games_back] running_list = [] for x in previous_games: stat = len(x.event_set.filter(Q(match_event__satisfiedEventsTypes__contains=[statistic]) & (Q(match_event__contains={'playerId': player_id})))) running_list.append(stat) return numpy.mean(running_list) A sample call would be like... total_shots = player_running_average2(id,start_date,4,9) total_goals = player_running_average2(id,start_date,4,6) The reason I did it like this was because I liked the simplicity of getting a statistic but since the json fields are pretty large it becomes really taxing on the program once you add more calls which I would like to do. I was trying to find a way to get all the stats needed at once rather then making individual calls, but I couldn't figure out a proper approach. Any advice is much appreciated, thanks. -
django model inline set default value for each row
Model class GamePeriod(models.Model): # 游戏期 start_date = models.DateField('开始日期') end_date = models.DateField('结束日期') play_seq = models.CharField('游戏期号', unique=True, max_length=50, default=now().strftime("%Y%m%d")) class GameAmount(models.Model): gamePeriod = models.ForeignKey(GamePeriod, verbose_name='游戏期号') # 游戏期 gameRule = models.ForeignKey(GameRule, verbose_name='游戏规则') # 游戏规则 amount = models.IntegerField('金额', default=2) Admin class GameAmountline(admin.TabularInline): model = GameAmount def __init__(self, parent_model, admin_site): super().__init__(parent_model, admin_site) self.game_rules = GameRule.objects.all() self.rule_num = self.game_rules.count() self.extra = self.rule_num self.max_num = self.rule_num def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'gameRule': kwargs['initial'] = '' ##Question is here : need auto set value for each game rule return db_field.formfield(**kwargs) if have 5 gameRule, then create 5 gameRules edit rows, and auto set the gameRule value. please see image: enter image description here -
Return proper JSON from Django JsonResponse
My Model: class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone = models.CharField(max_length=20) email = models.EmailField() My View: def users(request): people = Person.objects.all() data = serializers.serialize('json', people) return JsonResponse(data, safe=False) All I want back is the data in JSON format. What I'm getting back is this: "[{\"model\": \"myapp.person\", \"pk\": 1, \"fields\": {\"first_name\": \"ahmet\", \"last_name\": \"arsan\", \"phone\": \"xxx-xxx-xxxx\", \"email\": \"aarsan@xxxxxxxx.com\"}}]" While technically that is valid JSON, there are 2 problems (for me) with this response: I don't want those double quotes escaped. I don't need the model name (myapp.person). I don't know if/what I'm doing wrong, but it seems like something is off here. Perhaps my query should be returning a dict but I don't know how to get it to do that. I am using Django 1.10.1, Python 3.4. -
How to create an auto increment field for a django model, with two keys which are unique_together?
I have a model like class Item(models.Model): site = Site() id_on_site = PositiveIntegerField() Now i want to create an instance Item(current_site, next_id_on_site) with next_id_on_site = Item.objects.filter(site=current_site).aggregate(next=Max("id_on_site"))['next'] The problem is, that the operation of generating the ID and creating the Item is not atomic, so there is a race condition which creates duplicate IDs, so .get(site=current_site, id_on_site=someid) will raise a MultipleObjectsReturned exception. setting the fields unique_together in the model does not help with the generation of the auto increment ID and doesn't seem to be implemented at the DB level at all. -
Is there much change in python code when I want to change the database from sqlite to postgres?
So far I've been using sqlite with django, however I might want to deploy it to heroku and therefore use postgresql instead. Other than installing postgres, connect it to my app and repopulate it with the same data, are there any necessary change in my python code? For example the models, queries to get the data, lines that perform adding data to my database, and so on. Does those things need change or is the syntax still the same? -
Trying to use Django-Leaflet - only see blank screen
I followed the instructions here, up to adding the map to my template, resulting in the following: example.html <!DOCTYPE html> {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} </head> <body style="height:100%; width:100%;"> {% leaflet_map "yourmap" %} </div> </body> </html> I installed Django-Leaflet without problems using pip. I also added the app to my installed apps and included Leaflet settings. settings.py INSTALLED_APPS = [ # 'leaflet', ] LEAFLET_CONFIG = { 'DEFAULT_CENTER': (52.00,20.00), 'DEFAULT_ZOOM': 6, 'MIN_ZOOM': 1, 'MAX_ZOOM': 20, } When I look in firebug, I see that the template tags have successfully loaded the leaflet js and css files, as well as created a "map" div in the body. However, the map does not include any leaflet attributes besides css/height. What could be going wrong here? -
Can you construct csrf from request object - csrf constructor exception?
I am following an example of user registration and my code looks like this from django.views.decorators import csrf def register_user(request): args={} args.update(csrf(request)) #---->Crashes here args["form"] = UserCreationForm() return render_to_response("register.html",args) I get an exception at the statement args.update(csrf(request)) stating that the module object is not callable. Any suggestions on what I might be doing wrong ? -
Django 1.8 calls to database in html code
long-time lurker for this website, but I finally decided to join the community. I have a quick question on some of my code. I took a job this year for my university developing a website for the journalist department. The website was being built the previous year by another student using Django 1.8, python 2, and everything else that comes with that. I knew a decent amount about these languages, and I have learned a lot testing out different methods for hours on end. However, there is one thing I am having trouble with that I have researched for forever. Basically, for my website, I have different "sections" for different pages of articles. These articles have many traits. One trait is called "section" and this section has the names of the pages. So for example: One page is named "look". I can call my code and display all of my featured_articles. HOWEVER, I am trying to only display the articles where the name of the section equals "look". Here is my current code. Any ideas? I have tried many things but I can't get it to work properly. For loops, if statements, different HTML processes, different pages in django, etc... … -
What's the most complete full stack framework with scaffolding?
I am looking for a RAD (Rapid Application Development) framework with scaffolding or a seed project. Any language is acceptable, but it needs to offer the following our of the box: CRUD scaffolding / seed (including UI) Authentication (including registration & login UI, ideally including password recovery and email validation) The options I have considered so far: MEAN.JS / Mean.io (closest match, but authentication can be better) WordPress / Drupal with custom plugins (not a very good fit) Ruby on Rails (good fit, but couldn't find much about authentication integration) Django (No UI scaffolding) -
java script in django template: error display within loop
I will just dump my code here first: {% for calibrations in equipment.calibration_set.all %} <script> function myFunction(cal_id) { document.getElementById(cal_id).innerHTML = "<ul><li>{{calibrations.id}}</li></ul>"; } </script> <ul> <li> <p onclick="myFunction( {{calibrations.id}} )">{{calibrations.cal_date}}</p> <div id = {{calibrations.id}}> YES </div> </li> </ul> so calibration is a foreign key of equipment. And here I would like to display a list of calibration associated to a equipment, and using the date of calibration as a javascript onclick event so that a user can click to display the detail information of this calibration. The problem I have is that now even if there are multiple calibrations, clicking the calibration date will change the "Yes" under it to the id of latest calibration. Like in the picture, I clicked the first and second calibration date and expect the text below it to be 1 and 2 respectively. Could somebody point out what's wrong here? -
tastypie: sequence item 0: expected string, function found
class ActionResource(ModelResource): #place = fields.ManyToManyField('restaurant.resource.PlaceResource', 'place', full=True, null=True) place = fields.ManyToManyField(PlaceResource, attribute=lambda bundle: PlaceInfo.objects.filter(action=bundle.obj)) class Meta: queryset = ActionInfo.objects.all() resource_name = 'action' filtering = { 'place' : ALL_WITH_RELATIONS, } class PlaceResource(ModelResource): location = fields.ManyToManyField(PlaceLocationResource, 'location') class Meta: queryset = PlaceInfo.objects.all() resource_name = 'place' filtering = { 'id' : ALL, } This is my resource.py. With this code i want to filter places with some id: http://localhost/api/v1/action/?place__id=2&format=json By action id i can find only one place, action is uniqe for place. With this url i get error: sequence item 0: expected string, function found Django models look like PlaceModel has ManyToMany field with reference to ActionModel http://localhost/api/v1/action/2/?format=json Gives me normal json with reference to places -
'str' object has no attribute 'keys' - Django database insert
I'm trying to insert the end of the url into a table. The end of the url is passed to views.py with the variable "anything". I then use a raw query to insert it into the table "products_cart1". So when the page is requested it adds the end of the url to the table and returns the original page. However when I load the page the record is added but the page returns an error: 'str' object has no attribute 'keys' This is the view: def cart(request,anything): with connection.cursor() as cursor: cursor.execute("INSERT INTO products_cart1 (id) VALUES (?)",(anything)) return render_to_response("products/index.html") Is there something fundamentally wrong that I am doing here? I'm new to both django and sqlite. Thanks for your help.