Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to neaten a long built in template tag in django?
How do you neaten a long template tag like this: <td>{{ membership.is_project_manager|yesno:"<span class='glyphicon glyphicon-ok'></span>,<span class='glyphicon glyphicon-remove'></span>"|safe }}</td> -
Django celery beat not working
I am trying to get started with celery, but I can't get my task up and running. I have installed django-celery-beat and celery4. My settings file. Installed apps (with celery packages) ... 'django_celery_beat', 'django_celery_results' the celery configuration CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sandbox.settings') app = Celery('sandbox') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and my simple task, which i configured to run through the admin panel of django celery beat. from __future__ import absolute_import, unicode_literals from sandbox.celery import app @app.task() def try_celery(): print "Trying out Celery" I am trying to run this task as a periodic task (beat) with cron tab as */2 * * * * The log I am getting is, $ celery -A sandbox worker --loglevel=debug [2017-10-24 14:28:02,999: DEBUG/MainProcess] … -
Testing a utility method that doesn't belong to a class in django
I have a file I created called utils.py In that I have a few little methods that don't really belong on a model, they don't really belong in the view. They don't do a lot of work and are just used once or twice in my application so I felt they best fit into a 'utility' kind of role. My question is - how do I test them? I currently test my models and forms - but I wanted to put together some tests to go against this utils file, too. I just don't know how to do that without a class to call in the test_utils.py file -
Can't authenticate Django user in shell
For some reason I can't authenticate a newly created user in the Django shell and I really don't know what's wrong. Must be something very stupid... Start Django shell: (venv) xxx:xxx xxx$ python ../manage.py shell Python 3.6.0 (v3.6.0, ...) [GCC 4.2.1 (...) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) Create a new user: >>> from django.contrib.auth import get_user_model >>> email = "testemail@gmail.com" >>> password = "testpassword" >>> user = get_user_model().objects.create_user("TestUser", email, password) The new user seems to have been added to the database correctly: >>> get_user_model().objects.all() <QuerySet [<MyUser: testemail@gmail.com>]> >>> u = get_user_model().objects.first() >>> u.username 'TestUser' >>> u.email 'testemail@gmail.com' >>> u.password 'pbkdf2_sha256$36000$Onrvxuy09b6r$sCuz/2/bIbeg5j7cfO934kCIvzVdxqo1s1v6x6nwYLY=' But authentication fails: >>> from django.contrib.auth import authenticate >>> user = authenticate(email = email, password = password) >>> user.email Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'email' >>> I have a custom User model hence the use of get_user_model(). models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = … -
Conflicting models when overriding
It seems like oscar is not picking up my pointed local folder. INSTALLED_APP = [] + get_core_apps(['myoscar.partner']) My error is Conflicting 'partner' models in application 'partner': <class "oscar.app.partner.models.Partner"> and <class "myoscar.partner.models.Partner"> This also leads me to another related question - there's two settings.py. I've tried adding in both. When I remove myapp.partner in my main app, I obviously dont get the error but it gives me oscar's default model - which makes sense but then I run into the above error when I add it in. I don't know of anywhere else I'm registering the partner model before this override - at least not that I know of. My question is 1) which settings.py is the right one? I want to make sure. 2) why do I get this error when I pointed to the forked folder? Is it not picking up my folder? App/myoscar/partner/models.py from django.contrib.auth import get_user_model from django.db import models from oscar.apps.partner.abstract_models import AbstractPartner User = get_user_model() class Partner(AbstractPartner): users = models.OneToOneField(User,related_name='partner_user') from oscar.apps.partner.models import * #per some answers on stackoverflow, I've also tried removing this but the docs say this should be added here to keep the other models. my folder structure: App |--app |----__init.py__ |----settings.py … -
How to pass function result to a templage?
i'm working on django projects and i have a problem : I would like to pass the results of function to a dynamic template. def liste_ebauche(request): if not request.is_ajax() and not request.method == 'GET': raise Http404 try: param_json = None param = request.GET for json_liste_eb in param: param_json= json.loads(json_liste_eb) of_select= param_json['numof'] reponse= {} reponse_json= {} reb={} c=connection.cursor() c.execute("BEGIN") c.callproc("p_web_get_ebauche",[of_select]) ebauches=c.fetchall() c.execute("COMMIT") c.close() html = render_to_string("paquet/ss_ebauche.html", locals()) except Exception as e: logger.warning("error :" + e.message) return HttpResponse(html) In my templates i' m doing : {% for ebauche in ebauches %} <tr style="text-align:center"> <td class="id_ss_ebauche" style="display:none;">{{forloop.counter}}</td> <td class="case">{{ebauche.ebauche}}</td> <td class="case">{{ebauche.type}}</td> <td class="case">{{ebauche.longueur}}</td> <td class="case">{{ebauche.ligne}}</td> </tr> {% endfor %} It's ok if i transmit a queryset but not with results function. How can i adapt result function to transmit to my template? Please help me. -
GAE Stackdriver: SOURCE_LOCATION_ERROR (No code found at...)
I'm debugging a custom django command by using GAE Stackdriver Debug. It's used the GAE source code: I published a new version and I see the updated files in GAE, but executing the command via python manage_gae.py gives a SOURCE_LOCATION_ERROR: No code found at line ... in /base/data/home/apps/e~my_project/.../my_command.py. Try lines ... -
u' admin' is not a registered namespace in django
I am writing an application for django admin and everything seems to be going well till I used admin: in url on my templates and I got error u' admin' is not a registered namespace I am using the latest django version as at october 2017 html {% extends "admin/base_site.html" %} {% load staticfiles %} {% block extrastyle %} <link rel="stylesheet" type="text/css" href="{% static " css/admin.css " %}" /> {% endblock %} {% block title %} Order {{ order.id }} {{ block.super }} {% endblock %} {% block breadcrumbs %} <div class="breadcrumbs"> <a href="{% url " admin:index " %}">Home</a> &rsaquo; <a href="{% url " admin:orders_order_changelist " %}">Orders</a>&rsaquo; <a href="{% url " admin:orders_order_change " order.id %}">Order {{ order.id }}</a> &rsaquo; Detail </div> {% endblock %} admin.py def order_detail(obj): return '<a href="{}">View</a>'.format( reverse('orders:admin_order_detail', args=[obj.id])) order_detail.allow_tags = True urls.py url(r'^admin/', admin.site.urls), app urls.py url(r'^admin/order/(?P<order_id>\d+)/$', views.admin_order_detail, name='admin_order_detail'), further codes would be provided on request -
djando ManyToMany models views and templates
I have the Gammer model that is User extension and the Competition model. many users can play a competition and a competition can have many users (ManyToMany) class Gammer(User): competition=models.ManyToManyField(Competition) puntaje_global = models.IntegerField(default=0) ranking = models.IntegerField(default=0) class Competition(models.Model): name = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) finish_date=models.DateTimeField(blank=True, null=True) duration = models.DurationField(blank=True,null=True) def finish(self): self.finish_date = timezone.now() self.save() def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.name Add in admin.py: admin.site.register(Gammer) The admin can view player competitions (users) or assign them competencies Now I want the players (users) can register the competitions(choose competitions). How do I continue? -
django.db.utils.IntegrityError: (1048, "Column 'category_id' cannot be null")?
goods.py class Goods(models.Model): category = models.ForeignKey(GoodsCategory, verbose_name='xxx') goods_sn = models.CharField(default='', max_length=50, verbose_name='xxx') name = models.CharField(max_length=300, verbose_name='xxx') click_num = models.IntegerField(default=0, verbose_name='xxx') sold_num = models.IntegerField(default=0, verbose_name='xxx') import_goods_data.py from apps.goods.models import Goods, GoodsCategory, GoodsImage from db_tools.data.product_data import row_data for goods_detail in row_data: goods = Goods() goods.name = goods_detail['name'] goods.market_price = float(int(goods_detail['market_price'].replace('¥', '').replace('&', ''))) goods.shop_price = float(int(goods_detail['sale_price'].replace('&', '').replace('元', ''))) goods.goods_brief = goods_detail['desc'] if goods_detail['desc'] is not None else '' goods_goods_desc = goods_detail['goods_desc'] if goods_detail['goods_desc'] is not None else '' goods.goods_front_image = goods_detail['images'][0] if goods_detail['images'] is not None else '' category_name = goods_detail['categorys'][-1] category = GoodsCategory.objects.filter(name=category_name) if category: goods.category = category[0] goods.save() in the goods.py, not 'category_id', why running 'import_goods_data.py' get the error: _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1048, "Column 'category_id' cannot be null") and must be add 'category_id'? -
Retrieving by a different parameter using DRFs ModelViewSet
How can I retrieve a user by username rather than the primary key while using the rest frameworks ModelViewSet? Here is my current view: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer -
Is there a way to refer to only some fields in a Django ForgeinKey?
I believe this is best explained by an example. So, I am making a program for saving weightlifting results for international and national competitions. Below is a (weight)lifter model: class Lifter(Person): # Changed from dateTime, as we don't need time of birth birth_date = models.DateField(null=True) gender = models.CharField(max_length=10, choices=Gender.choices(), null=True) club = models.ForeignKey('Club', null=True) I would like to connect the lifter model to the InterntionalResult model: class InternationalResult(models.Model): lifter = models.ForeignKey(Lifter, null=True) body_weight = models.FloatField(verbose_name='Kroppsvekt', null=True) # International group can be (for example) "A" or "B" group = models.CharField(max_length=5, verbose_name='kategori') snatch = models.IntegerField() clean_and_jerk = models.IntegerField() total = models.IntegerField() However, lifter has a ForeginKey to group (club = models.ForeignKey('Club', null=True)). When I connect Lifter to InternationalResult, I would like to exclude this ForgeinKey, but still connect Result to the rest of Lifter. This is because international competitions don't have clubs in the same way. Is there a way to do this, or should I just create a new InternationalLifter-model? Thank you for your time! -
Paho MQTT and Django - Working, but Many Errors
I have a Django application. This application is meant to get data and display it to the user. I have chosen (for the moment) to use MQTT as my method of passing information between my Django application and a separate server that collects data. When a user loads a page, an AJAX request is made (seen below) to request data. My goal is to make the AJAX request, subscribe to a topic, and have my other server publish a message to that topic. When the message is received, I return it as JSON to the template. Now, this may be a little backwards, as I am turning MQTT into a request/response architecture, which is not what it was designed for - but MQTT solves some other problems for me. I any case, the solution you see below works - but it has some errors. Load a page works perfectly fine. The request is made, it is blocked until a response is received, and then the response is returned as a JsonResponse and is displayed to the user. But, if the page is refreshed while the first request is being made (so a number of refreshes in a row) then a … -
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.