Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image link not working in css- django project
I am using django (py3) for my website. I am facing problem in image, I.e on running in the chrome browser , I can't see the image. The image file is stored in website>homepage>static>homepage>images>pic.jpg And my css file code for image is header{ background-image:url("./static/homepage/images/pic.jpg"); . . other styling stuffs . . } When I viewed the source code in the browser, clicked on the css link,. I can't see the blue link in my image url. I'm not getting what the problem is. Thanks in advance. -
"Select All" Checkbox for django-sortetm2m
Im looking for a way to integrate an "Select All" Checkbox into django-sortedm2m admin. Is there a simple way to achieve this? -
Will I be able to use Amazon Web Services ElastiCache Redis as a message broker/task queue data store in my Django Project?
Will I be able to use Amazon Web Services ElastiCache Redis as a message broker/task queue data store in my Django Project? If yes how can I set it up in my django settings? Thank You. -
generic view does not return any values
I am a beginner in django, and its version is 1.11.6 ,as well as the python version I use is 3.6. I am studying generic view, generic.ListViewdoes not return any values. views.py class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'Latest_question_list' def get_queryset(self): return Question.objects.order_by('-pub_date')[:5] urls.py from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/results/$', views.ResultView.as_view(), name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote, name='vote'), ] the output of above code is: no polls are available the html page is included the following code: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>no polls are available</p> {% endif %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"/> unfortunately, I could not get the reason of the error. -
how to get and post csrf token in swift
I am currently trying to log into a Django web server. The problem is that this server requires a csrf token for loggin. I've looked at the doc and I could not find anything on the internet regarding swift. Here is a func that I wrote. func getCsrf(){ // Get the webURL service let url = URL(string: "https:mywebServer") // Make url request let request = NSMutableURLRequest(url: url!) request.httpShouldHandleCookies = true; request.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: HTTPCookieStorage.shared.cookies(for: url!)!) // create a session let session = URLSession.shared // create a connection session.dataTask(with: request, completionHandler: { (data, response, error ) in var cookies = HTTPCookie.cookies(withResponseHeaderFields: ((response as? HTTPURLResponse)?.allHeaderFields)!, for: url) HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: nil) for cookie: HTTPCookie in cookies { if(cookie.name == "csrftoken"){ csrf_cookie = cookie.value break } } // for later request var laterRequest = NSMutableURLRequest(url: url) laterRequest.httpMethod = "POST" laterRequest.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: HTTPCookieStorage.shared.cookies(for: url)!) laterRequest.addValue(csrf_cookie, forHTTPHeaderField: "X_CSRFTOKEN") }) .resume() -
Django select model fields through in meta class
Here i need to choose user's first name and second name from another table. Model is StockTransfer but i need from Users model class Meta: model = StockTransfer fields = ( 'id', 'from_stock', 'to_stock', 'comment', 'products', 'status', 'user', 'transfer_request', 'created_date', 'date_delivery', 'modified_date', 'accepted_time', 'cancelled_time', 'first__name', 'second__name' ) model (users.py) class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255) second_name = models.CharField(max_length=255) ----- stocktransfer.py (model) class StockTransfer(BaseModel, DeleteMixin): PENDING = '0' APPROVED = '1' CANCELLED = '2' STATUS_CHOICES = ( (PENDING, 'pending'), (APPROVED, 'approved'), (CANCELLED, 'cancelled'), ) from_stock = models.ForeignKey('main.Stock', related_name='from_transfers') to_stock = models.ForeignKey('main.Stock', related_name='to_transfers') comment = models.CharField(max_length=255, blank=True, null=True) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=PENDING) user = models.ForeignKey('main.User', null=True) I think i can choose first name and second name just simple way write first_name and second_name in meta class fields. Is it right? Any ideas? -
Creating a custom menu in Django-xadmin dashboard using django-xadmin-extras
I have an app named Foo. Django-xadmin automatically creates menu under an app based on the models defined. I want to create a Custom menu with my custom view. Here is my Custom admin view written in adminx.py - from xadmin.views import CommAdminView class TestAdminView(CommAdminView): form = TestForm app_config = FooConfigForCustomMenu def get_context(self, *args, **kwargs): ctx = super(TestAdminView, self).get_context(*args, **kwargs) form = TestForm() ctx["form"] = form return ctx def get(self, request, *args, **kwargs): return render(request, "app/app.html", self.get_context()) def post(self, request, *args, **kwargs): # Do some stuff return render(request, "link to another template") # Registration xadmin.site.register_view(r"^foo-test/$", TestAdminView, name="foo-test") Here, i have inherited from xadmin's CommAdminView. FooConfigForCustomMenu is written according to Django-xadmin-extras documentation in apps.py like this - from xadmin_extras.apps import AdminAppMixin class FooConfigForCustomMenu(AdminAppMixin): name = 'test' verbose_name = 'test' icon = 'chart' def init_menu(self): return [{'url': r"^foo-test/$", 'icon': 'bolt', 'title': 'Test for foo', 'order': '', 'perm': None}] But there is no menu named test appearing in xadmin under Foo app. What am i doing wrong here ? I am stuck here for hours. The form is initiated like this in forms.py by inheriting Form class of django.forms - from django.forms import Form class TestForm(Form): # Initiation of form fields -
Pass many-to-many object to variable
I have 2 classes, with many-to-many relationship, my goal is to fill an 'item' list with data from that 2 models, here are my models: class Bakery(): title = models.CharField('restaurant_name', max_length=100) class DeliveryService(): title = models.CharField('deliveryservice_name', max_length=100) bakery = models.ManyToManyField(Bakery) Here is the logic on my 'views' file: item = [] bakerys = Bakery.objects.all() for i in bakerys: item.append(i.title) item.append(i.deliveryservice.title) I hope you got what exactly I want to accomplish. My current 'views' file logic is wrong and I know it, I just does not know what can I do to solver this problem. Thank you for your time. -
Django Inline formset not deleting intermediary model with no pk?
I have implemented an inline formset from this accepted answer I am having an issue when saving the formset namely, it does not delete records We can trace it into the formsets save method: def form_valid(self, form): '''Handle saving of the project membership formset ''' context = self.get_context_data() project_memberships = context['projectmembership_formset'] if project_memberships.is_valid(): self.object = form.save() project_memberships.instance = self.object project_memberships.save() And if we step deeper into the save method we get to: def save_existing_objects(self, commit=True): self.changed_objects = [] self.deleted_objects = [] if not self.initial_forms: return [] saved_instances = [] forms_to_delete = self.deleted_forms for form in self.initial_forms: obj = form.instance # If the pk is None, it means either: # 1. The object is an unexpected empty model, created by invalid # POST data such as an object outside the formset's queryset. # 2. The object was already deleted from the database. if obj.pk is None: continue if form in forms_to_delete: self.deleted_objects.append(obj) self.delete_existing(obj, commit=commit) elif form.has_changed(): self.changed_objects.append((obj, form.changed_data)) saved_instances.append(self.save_existing(form, obj, commit=commit)) if not commit: self.saved_forms.append(form) return saved_instances What I find is that the pk of the obj is empty and hence no deletion ever happens. POST Data: 'projectmembership_set-0-id': [ '8' ], 'projectmembership_set-0-user': [ '1' ], 'projectmembership_set-0-is_project_manager': [ 'on' ], 'projectmembership_set-0-full_time_equivalent': [ … -
How to allow others to connect to my Django website?
I'm very new to Django website hosting. Now that I have created a website, and I wish the users can connect to my website within a local network. However my website now can only be accessible from the localhost (my pc), the others are not able to connect to my website when typing my ip address for example xxx.xxx.xxx.xxx:8000 on their browser. I launch the service on my localhost using # python manage.py runserver. May I know if there is a way/command to allow the others to connect to my website? Thank you very much and appreciate your help! Note: I have tried # python manage.py runserver 0.0.0.0:8000 as well, which allow all incoming, but it didn't work. -
Django-REST API Raising an Error in Serializer when Email Exisit
so a quick over view, the Front ends sends me a email,password and confirmpassword. and i store them in an API and then will later on store in the database, but for the mean time, i am only saving them when the sent email doesn't exist first of all that's my views.py class UserList(APIView): def get(self,request): users = Users.objects.all() serializer = UserSerializer(users,many=True) return Response(serializer.data) def post(self,request): serializer = UserSerializer(data=request.data) #here i serialize the data entered by the user if serializer.is_valid(): try: #and then i check if the email already exists or not, if it not exist, it will save it in the API, if not it should raise an errro!, i tried saying serializers.validationerror bs that wouldn't work at all. match = Users.objects.get(email=serializer.validated_data["email"]) except Users.DoesNotExist: # Unable to find a user, this is fine] serializer.save() print ('money here come the money') return Response(serializer.data, status=status.HTTP_201_CREATED) raise (?!) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Why Model field validation happens before validate or validate_<field> is called?
I just started learning Django Rest Framework and I can't understand why DRF runs Model field validation before Own Validation I have a model which has a URLField and basically all I want to add http:// or https:// before it validates, so wrote custom validation method class ShortenerSerializer(serializers.ModelSerializer): class Meta: extra_kwargs = { 'count': {'read_only':True} } fields = ('id', 'url', 'short_url', 'count', 'created_at') model = Shortener def validate_url(self, url): if not 'http://' in url and not 'https://' in url: url = 'http://' + url url_validate = URLValidator() try: url_validate(url) except: raise serializers.ValidationError("Please Enter a Valid URL") return url I even overide the validate method but again it is called after model field validation as it raises Exception. I guess i need to overide some method but no idea which one to override. -
xframe_options_exempt not working with django
So I've configured a website that allows me to display data from the waves blockchain onto a django site running on an AWS EC2 instance. The webpage works as shown here www.wavesico.tk/Project/get-ico/jacks-easter-eggs In my views file I have included: from django.views.decorators.clickjacking import xframe_options_exempt and @xframe_options_exempt def crowdFund(request, company_name): c = WavesCompany.objects.get(name=company_name) data = tokens.getTokenData(c.holdersKey, c.tokenKey) return render(request, 'crowd_fund.html', data) I have also included the middleware in my settings file: 'django.middleware.clickjacking.XFrameOptionsMiddleware', However, Chrome still reports the error 'Refused to display 'https://www.wavesico.tk/Project/get-ico/jacks-easter-eggs/' in a frame because it set 'X-Frame-Options' to 'sameorigin' I have tried changing the 'render()' function to 'HttpResponse' but still no luck. Thanks everyone, Jack -
Handling ManyToMany field in DRF serializer
I have the following Django models: class Article(models.Model): name = models.CharField(max_length=30, unique=True) tags = models.ManyToManyField(Tag) ... class Tag(models.Model): name = models.CharField(max_length=30, unique=True) ... I would like to be able to add a list of existing tags while creating Article via POST request, i.e. { 'name': 'My Org Name', 'tags': [1,2,3] } Where [1, 2, 3] is a list of tag ids. My serializer looks like this: class ArticleSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(many=True, read_only=True, allow_null=True) class Meta: model = Article fields = ('name', 'tags', ...) def create(self, validated_data): # in create I will add tags, i.e. article.add(tag) return Article.objects.create_article(**validated_data) But then I would like to do some validation such that I know that tag ids that are passed in belong to existing Tag instances. So I tried adding the method below to my serializer. def validate_tags(self, tags): if tags: for tag in tags: if not Tag.get(pk=tag): raise ValueError('Tag with id not found...') return tags For some reason this validation method is not triggered. I'm trying to figure out the right way to handle adding tags to articles, any suggestions would be highly appreciated. -
django model field in url
I've been learning django for a little bit now but I've ran myself into the ground with this one. I've been looking for an answer for two days and, annoyingly, I think I stumbled across it at one stage but I didnt realise until later that I forgot to change the template (by which time I forgot what post I read so I could recreate it). I'm trying to create something where users can signup then create a "channel" to store their stuff. I have that working just fine, but now I want to make it so the URL's look nicer (like Github or youtube). I'd like the URL's to display as "example.com/channels/channel-name" rather than "example.com/channels/1" This is what I have so far: url: url(r'^(?P<slug>[\w-]+)/$', channel_views.DetailView.as_view(), name="channel-detail"), (note: when slug is changed out for (?P< pk >[0-9]+) it works) views: class DetailView(generic.DetailView): model = Channel template_name = 'channels/channel-detail.html' models class Channel(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=150) def get_absolute_url(self): return reverse('channels:channel-detail', kwargs={'slug':self.name}) index.html: <a class="channel-link text-center" href="{% url 'channels:channel-detail' channel.id %}">{{channel.name}}</a> I feel like I need to run the "name" field through slugify then call that in the HTML template instead of "channel.id"? -
I have deleted the registration from site-packages but still it is not showing me import error
urls.py in my main app my project structure, it can be seen that there is no module named registration Still when i run the server it doesn't give me any error any runs as it was before deleting. Please help me to resolve this issue. -
What is the purpose of defualt=False in django management command
I'm trying to write a management command in django. According to the documentation default is set to False. I would assume that the default is the default value of the argument that is being passed. Make django custom management command argument "Not Required" What's the benefit of stating that deafult=False class Command(BaseCommand): help = "helps in doing stuff" def add_arguments(self, parser): parser.add_argument( 'name', type=str, default=False help="The name of the folder to be created") def handle(self, *args, **options): pass -
Celery task.delay blocked in docker container
I use celery in my django project. It works well on my MacBook and in a CentOS VM. When I run it in a docker container, the request which contains add.delay(add is a task) method is always blocked. I created a demo project on github: https://github.com/fengyouchao/proj_test My task: @shared_task def add(x, y): return x + y My view: def index(request): a = int(request.GET.get('a', 1)) b = int(request.GET.get('b', 2)) add.delay(a, b) return HttpResponse("Hello world") def hello(request): return HttpResponse("hello") In the demo project I created three services in docker-compose.yml: web - The service which run "manage.py runserver 0.0.0.0:8000" celery - The service which run "celery" rabbitmq - The service wich run rabbitmq-server Run services docker-compose up Test curl localhost:8000 # blocked curl localhost:8000/hello # OK Run the django project in current system(use the same rabbitmq-server in docker container) manage.py runserver 0.0.0.0:18000 Test curl localhost:18000 # OK , and the "celery" service printed task logs This problem has been bothering me for a long time, and I don't know where the problem is. I hope someone can help me. Thanks! -
Apps aren't loaded yet exception occurs when using multi-processing in Django
I'm doing a Django project and try to improve computing speed in backend. The task is something like a CPU-bound conversion process Here's my environment Python 3.6.1 Django 1.10 PostgreSQL 9.6 And I stuck with following errors when I try to parallel a computing API by python multi-processing library. File "D:\\project\apps\converter\models\convert_manager.py", line 1, in <module> from apps.conversion.models import Conversion File "D:\\project\apps\conversion\models.py", line 5, in <module> class Conversion(models.Model): File "C:\\virtenv\lib\site-packages\django\db\models\base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "C:\\virtenv\ib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "C:\\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") look like each process import Conversion model and Conversion model is like from django.db import models Conversion(model.Model): conversion_name = models.CharField(max_length=63) conversion_user = models.CharField(max_length=31) conversion_description = models.TextField(blank=True) ... Below is my sample function which I want to parallel, each iteration is independent but will access or insert data into SQL. Class ConversionJob(): ... def run(self, p_list): list_merge_result = [] for p in p_list: list_result = self.Couputing_api(p) list_merge_result.extend(list_result) and I'm try to do is from multiprocessing import Pool Class ConversionJob(): ... def run(self, p_list): list_merge_result = [] p = Pool(process=4) list_result = p.map(self.couputing_api, p_list) list_merge_result.extend(list_result) In computing_api(), it'll try to get current conversion's info which has completed and … -
Pass xml file from directory to javascript using django
I'm creating an .xml file and then trying to pass this file to javascript, so I could use it there. Here's the output in browser's console: Failed to load file:///D:/Geoinformation%20systems/Maps/Markers/static/Markers/data.xml: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. Here is my view function: def index(request): markers_set = Marker.objects.all() root = Element('markers') tree = ElementTree(root) for m in markers_set: name = Element('marker') name.set('id', str(m.id)) name.set('name', m.name) name.set('address', m.address) name.set('lat', str(m.lat)) name.set('lng', str(m.lng)) name.set('type', m.type) root.append(name) tree.write(open(r'Markers\static\Markers\data.xml', 'wb')) return render_to_response('index.html', {'xmldata' : r'D:\Geoinformation systems\Maps\Markers\static\Markers\data.xml'}) Here is a piece of template "index.html" where javascript code is located: <html> <body> <div id="map"></div> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(-33.863276, 151.207977), zoom: 12 }); var infoWindow = new google.maps.InfoWindow; <!--Here I'm taking data that is passed--> downloadUrl('{{ xmldata }}', function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName('marker'); ... function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function() { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } }); } </script> </html> How should I pass/get the file, so not to failing loading it? I know … -
TypeError: save() missing 1 required positional argument: 'self'
this is views class RegisterView(View): def get(self,request): register_form = RegisterForm() return render(request,'register.html',{'register_form':register_form}) def post(self,request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get("email", '') pass_word = request.POST.get("password", '') user_profile = UserProfile user_profile.username = user_name user_profile.email = user_name user_profile.password = make_password(pass_word) user_profile.save() #error send_register_email(user_name,"register") I want to save user_profile to mysql,But user_profile.save() has an error, TypeError: save() missing 1 required positional argument: 'self',How should I solve it? -
Django admin cannot load data from database
After I create feature translate use Django model translation and then I was deployed Django project to the server and get I problem, My code was running well, in local development, Django admin can load data from the database without any problem. But the problem is when code deployed to server data in Django admin cannot load, they load blank data without error or any problem. But in database data is still available. models.py: from django.db import models from base.models import BaseModel class Platform(BaseModel): name = models.CharField(max_length=255) icon = models.ImageField(upload_to='gopay_platformicon') order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name class Method(BaseModel): name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) platform = models.ForeignKey(Platform) note = models.TextField(blank=True, null=True) picture = models.ImageField(upload_to='gopay_method', blank=True, null=True) order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name class TopupStep(BaseModel): name = models.TextField() method = models.ForeignKey(Method) picture = models.ImageField(upload_to='gopay_topupstep', blank=True, null=True) order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name translation.py: from modeltranslation.translator import translator, TranslationOptions from . import models class MethodTranslationOptions(TranslationOptions): fields = ('name', 'description', 'note', ) class TopupStepTranslationOptions(TranslationOptions): fields = ('name', ) translator.register(models.Method, MethodTranslationOptions) translator.register(models.TopupStep, TopupStepTranslationOptions) admin.py : from django.contrib import admin from base.admin import BaseAdmin from gopay … -
Django Roles and permissions
I am working on django roles and permissions, for this i am using django-role-permissions library. Issue : Create one role 'Director', director role assign user able to login into django admin area and view ( only view permissions ) filter data ( just like that : student which have 90% and above ) . Note : I already have two roles 1. Teacher 2. Student. -
Using django app config to change model.Meta.managed
Given the following architecture of django projects apps and database schemas: There is a django app which I want to share between several django projects. Each project has it's own postgresql schema in behind. All schemas live in the same postgresql database. One project is owner of the apps data, this project is responsible to run migrations and the data should live in its schema. All other projects may access the data from the other projects schema, because they have a proper postgresql search path set. We already use this concept with an app that has all models set to unmanaged, which works. But database changes always needs to be done manually. I'd like to benefit from django migrations and therefore I want my models either managed or unmanaged. Do you think app config is good place to change the models meta? Any other suggestions and approaches on how to solve the requirement are also welcome. -
Not able to make a ajax request in django using postgresql
So i've developed a django app,and i'm trying to POST something to Postgresql,i understand that CSRF token is necessary during an ajax request made to a view,which i have done,this is my csrf.js,which i've included in my header template // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); and this is my ajax request being made in a template $.ajax({type: 'POST', url: '/sample/saveData/', // some data url data: {param: workHours.length, param1: $(getDayName[i]).text(),param2: bla,param3: bla1,param4: bla2}, // some params success: function (response) { // callback if (response.result === 'OK') { if (response.data && typeof(response.data) === 'object') { // do something with the successful response.data // e.g. response.data can …