Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin not recognized after enabling django-social-auth backends
I have used django-social-auth in my project to sign in using facebook but then I couldn't login to django admin page even after logout from facebook. I thought I forgot my password and tried to change it from shell got: >>> from django.contrib.auth.models import User >>> User.objects.filter(is_superuser=True) <QuerySet []> Here's my setting.py file: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'social.apps.django_app.default', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'portfolio', ] AUTHENTICATION_BACKENDS = ( # For Facebook Authentication 'social.backends.facebook.FacebookOAuth2', # Default Django Auth Backends 'django.contrib.auth.backends.ModelBackend', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # Setting of Template Context Processors for Social Auth 'social.apps.django_app.context_processors.backends', 'social.apps.django_app.context_processors.login_redirect', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I know I can create a new superuser but I want to understand why this is happening and how can I use both the django-admin and django-social-auth? I appreciate some clarification here, I am new to django framework. -
NameError: name 'articles' is not defined
I'm beginner in Django and I am having errors on my very first day. Can anyone help me? Here is error I'm getting File "/home/akshay/Desktop/cdsmalpha/cdsmalpha/urls.py", line 23, in module> url(r'^hello/', articles.views.hello, name = 'hello'), NameError: name 'articles' is not defined Here is my url.py file in main project directory from django.conf.urls import include, url from django.contrib import admin from articles import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/', articles.views.hello, name = 'hello'), ] -
django rest framework: change in ListAPIView return format?
Just in the process of upgrading django rest framework from 3.2.3 to 3.4.6. I also upgraded django from 1.8.6 to 1.10 It looks like return values from ListAPIView have changed format? i.e. they used to be objects like { "count": 0, "next": null, "previous": null, "results": [] } but now are just straight arrays? [] I'm looking all over the place trying to find documentation for this change but can't find any. Is anyone able to help point me in the right direction? -
How to get Choice Field name instead of id in template using django rest framework
I am getting id of choice field in the template.But I want name of the choice field to display. Please review the below files and let me know how to get the name. here is my models.py =============================================================== class Posted(models.Model): name = models.CharField(_('Posted In'),max_length=255, unique=True) class Tags(models.Model): name = models.CharField(_('Tag Name'),max_length=255, unique=True) class Blogs(models.Model): author = models.ForeignKey(CustomUser) title=models.CharField(max_length=100) posted=models.ForeignKey(Posted, blank=True) tags= models.ManyToManyField(Tags, blank=True) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) serializers.py class BlogsSerializer(serializers.ModelSerializer): author = AccountSerializer(read_only=True,required=False) class Meta: model = Blogs fields = ('id','author','title','tags','posted','content','created_at','updated_at') read_only_fields=('id','created_at','updated_at') class TagsSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField() class Meta: model = Tags fields = ('id','name') read_only_fields=('id','name') class PostedSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField() class Meta: model = Posted fields = ('id','name') read_only_fields=('id','name') views.py class BlogViewSet(viewsets.ModelViewSet): queryset=Blogs.objects.order_by('-created_at') serializer_class= BlogsSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) return (permissions.IsAuthenticated(),IsAuthorOfBlog(),) def perform_create(self,serializer): serializer.save(author=self.request.user) return super(BlogViewSet,self).perform_create(serializer) class TagsViewSet(viewsets.ModelViewSet): queryset=Tags.objects.all serializer_class= TagsSerializer class PostedViewSet(viewsets.ModelViewSet): queryset=Posted.objects.all serializer_class= PostedSerializer Template <div class="row"> <div class="col-sm-12"> <div class="well"> <div class="blog"> <div class="blog__meta"> <a href="#"> +{{ blog.author.first_name }} </a> </div> <div class="blog__content"> <p>{{ blog.title }}</p> <p>{{ blog.posted}}</p> <p>{{ blog.tags}}</p> <p>{{ blog.content }}</p> </div> </div> </div> </div> </div> Thanks in advance -
ngMessages not working and causing Angular to load more than once error
Hey so I'm currently creating a registration form using Angular and I'm trying to amp it up by adding ngMessages to it for password confirmation, email errors, and invalid entries, etc etc. What I thought would be a simple implementation is causing a huge headache and many useless hours of debugging. So basically I included ngMessages in my main app like so... Index.html (function () { 'use strict'; angular .module('thinkster', ['thinkster.config', 'thinkster.routes', 'thinkster.authentication', 'thinkster.layout', 'hrlite.profiles', 'ngMessages']); angular .module('thinkster.config', []); angular .module('thinkster.routes', ['ngRoute']); angular .module('thinkster') .run(run); run.$inject = ['$http']; /** * @name run * @desc Update xsrf $http headers to align with Django's defaults */ function run($http) { $http.defaults.xsrfHeaderName = 'X-CSRFToken'; $http.defaults.xsrfCookieName = 'csrftoken'; } })(); Then I include angular-messages.js into my javascript.html (I'm building on Django framework) Javascripts.html {% load compress %} {% load staticfiles %} {% compress js %} <script type="text/javascript" src="{% static 'bower_components/jquery/dist/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'bower_components/bootstrap/dist/js/bootstrap.js' %}"></script> <script type="text/javascript" src="{% static 'bower_components/bootstrap-material-design/dist/js/material.js' %}"> </script> <script type="text/javascript" src="{% static 'bower_components/bootstrap-material-design/dist/js/ripples.js' %}"> </script> <script type="text/javascript" src="{% static 'bower_components/underscore/underscore.js' %}"></script> <script type="text/javascript" src="{% static 'bower_components/angular/angular.js' %}"></script> <script type="text/javascript" src="{% static 'bower_components/angular-route/angular-route.js' %}"></script> <script type="text/javascript" src="{% static 'bower_components/angular-cookies/angular-cookies.js' %}"></script> <script type="text/javascript" src="{% static 'bower_components/ngDialog/js/ngDialog.js' %}"></script> <script type="text/javascript" src="{% static … -
passing arguments to template in angularjs django
Im using angular js instead of the usual jinja for Django templating. I know that with jinja, I could call a primary key that I defined in the URLs file. Also, I could call the request.User and generally the request object from the template. How can I access these Objects and integers with angular? -
Django: naive datetime while time zone support is active
I'm struggeling with Django and datetime. I have a datetime-string as this "Sun, 28 Aug 2016 11:42:00 +0200" - so from my point of view with timezone information "+0200" Then I convert it using this: date_published = time.strptime(date_published, "%a, %d %b %Y %H:%M:%S %z") It gives me this: time.struct_time(tm_year=2016, tm_mon=8, tm_mday=28, tm_hour=11, tm_min=42, tm_sec=0, tm_wday=6, tm_yday=241, tm_isdst=-1) Then I try to convert it like this: date_published = datetime.fromtimestamp(time.mktime(date_published)) Which gives me: 2016-08-28 11:42:00 And then Django complains when saving it. How do I correctly convert the input string so that I can save it in a datetime-model's fields? Best Regeards Kev -
The 'photo' attribute has no file associated with it
Template error: In template D:\virtualEnv\alumni\member\templates\member\index.html, error at line 15 The 'photo' attribute has no file associated with it. 5 : <!-- Albums --> 6 : <div class="row"> 7 : <div class="col-sm-12"> 8 : <h3>{{ user.username }}'s Albums</h3> 9 : </div> 10 : {% if all_persons %} 11 : {% for person in all_persons %} 12 : <div class="col-sm-4 col-lg-2"> 13 : <div class="thumbnail"> 14 : <a href="{% url 'member:detail' person.id %}"> 15 : <img src=" {{ person.photo.url }} " class="img-responsive"> 16 : </a> 17 : <div class="caption"> 18 : <h2>{{ person.name }}</h2> 19 : <h4>{{ person.category }}</h4> 20 : 21 : <!-- View Details --> 22 : <a href="{% url 'member:detail' person.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> 23 : 24 : 25 : Traceback: File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _resolve_lookup 885. current = current[bit] During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred: File "D:\virtualEnv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "D:\virtualEnv\lib\site-packages\django\template\response.py" in render 109. self.content = self.rendered_content File "D:\virtualEnv\lib\site-packages\django\template\response.py" in rendered_content 86. content = template.render(context, self._request) File "D:\virtualEnv\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render … -
Extracting error message from JSON returned by a Django REST API call
I am using the Django rest-auth package with Django allauth to allow users to sign up with the /res-auth/registration api call. If the registration fails I get some JSON returned that contains the reason for the failure. I am having difficulty working out how to extract the error reason for all cases. Here is an example of the JSON returned when the username is too short: { "_body":"{\"password1\":[\"This password is too short. It must contain at least 8 characters.\"]}", "status":400, "ok":false, "statusText":"Bad Request", "headers":{ "Date":[ "Sun", " 28 Aug 2016 16:56:40 GMT" ], "Content-Type":[ "application/json" ], "Server":[ "WSGIServer/0.2 CPython/3.4.3" ], "X-Frame-Options":[ "SAMEORIGIN" ], "Access-Control-Allow-Origin":[ "*" ], "Allow":[ "POST", " OPTIONS" ] }, "type":2, "url":"http://al8f24a9.ngrok.io/rest-auth/registration/" } How would I extract the failure reason if it was for password or if it was for username? -
I can't able to install gunicorn whitenoise in heroku
I'm trying to deploy my python-django website on heroku .I used the command (firstproject) $ pip install dj-database-url gunicorn whitenoise I got an error like this Requirement already satisfied (use --upgrade to upgrade): dj-database-url in /home/aparna/firstproject/lib/python3.4/site-packages Requirement already satisfied (use --upgrade to upgrade): gunicorn in /home/aparna/firstproject/lib/python3.4/site-packages Downloading/unpacking whitenose Could not find any downloads that satisfy the requirement whitenose Cleaning up... No distributions at all found for whitenose Storing debug log for failure in /home/aparna/.pip/pip.log How can I solve this error to deploy my website on heroku? -
how can i display hierarchical data using django & js?
OVERVIEW I want to make a similar widget to that used on this website: The peculiarity of this hierarchical widget is the way it displays results. Case 1 Case 2 QUESTION I'd like to use django & mysql to achieve this but I'm not sure how to do it. I'm aware of some of the options to store hierarchical data in a relational database and I've seen there are few available packages to work with trees in django. The main purpose will be displaying only-read information with almost no updates. Could you recommend me some well suited django/js combo for this particular task? Or even better, if you know a simpler way to code it by myself, could you give me some hints? -
Django Form use of user id
The following code is working nicely: class SelectTwoTeams(forms.Form): campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] currentCampaignNo = campaignnoquery[0].campaignno cantSelectTeams = UserSelection.objects.filter(campaignno=currentCampaignNo) currentTeams = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)) team_one = forms.ModelChoiceField(queryset = currentTeams) team_two = forms.ModelChoiceField(queryset = currentTeams) However, you can see that the user id is currently hardcoded into the filter as 349. I would like this to be the id of the user logged in. I know in the view I can use: currentUser = request.user currentUserID = currentUser.id But this code does not work within the forms section. If anyone could point me in the correct direction that would be ideal. Many thanks, Alan. -
Location of static files when creating a Django exe using pyinstaller
I have a Django project with the following structure: root videos static templates and the STATIC_URL setting in settings.py is STATIC_URL = '/static/' I managed to use pyinstaller to create a windows executable from manage.py. I can start the Django server but I can't figure out where to put the static files. When I first started the server it could not find the templates as well, it searched for them in : 'root\django\contrib\admin\templates\videos\' I copied the templates to this folder and it worked. But I can't figure out where to put the static files. I tried putting them in 'root\django\contrib\admin\static' to recreate the original structure. But it seems it doesn't search for them there... Anyone knows where the static files should go? Or how to define the place where a bundled pyinstaller exe will look for them ? -
Django Product Total
I'm trying to learn in Django. I'm trying to prepare the inventory application. But I do not calculate the input and output products. I prepare models & views. Models: class Kategori(models.Model): adi = models.CharField(max_length=10, verbose_name="Kategori") def __str__(self): return self.adi class Birim(models.Model): birim = models.CharField(max_length=2, verbose_name="Birim") def __str__(self): return self.birim class Urunler(models.Model): adi = models.CharField(max_length=50, verbose_name="Ürün Adı") kod = models.PositiveSmallIntegerField(verbose_name="Ürün Kodu", blank=True, null=True) etkenMadde = models.CharField(max_length=100, verbose_name="İçerik Etken Madde", blank=True, null=True) tarih = models.DateField(default=datetime.now(), editable=False) birim = models.ForeignKey(Birim, verbose_name="Birim") kategori = models.ForeignKey(Kategori, verbose_name="Kategori") aciklama = models.CharField(max_length=50, verbose_name="Açıklama", blank=True, null=True) def __str__(self): return self.adi class StokCikis(models.Model): urun = models.ForeignKey(Urunler, related_name="scikis_urun", verbose_name="Ürün") tarih = models.DateTimeField(default=datetime.now()) miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0) teslimAlan = models.CharField(max_length=20, verbose_name="Teslim Alan") tesimEden = models.CharField(max_length=20, verbose_name="Teslim Eden") def __str__(self): return self.urun.adi class StokGiris(models.Model): urun = models.ForeignKey(Urunler, related_name="sgiris_urun", verbose_name="Ürün") tedarikci = models.CharField(max_length=100, verbose_name="Tedarikçi", blank=True, null=True) irsaliyeNo = models.PositiveSmallIntegerField(verbose_name="İrsaliye No", blank=True, null=True) tarih = models.DateField(default=datetime.now().strftime("%d.%m.%Y")) miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0) aciklama = models.CharField(max_length=100, verbose_name="Açıklama", blank=True, null=True) def __str__(self): return self.urun.adi Views.py def kategori(request): kategori = Kategori.objects.all() return render_to_response('stok_kategoriler.html', locals()) def kategoriEkle(request): kategoriId = request.GET.get('id') if kategoriId: ktgr = Kategori.objects.get(pk=kategoriId) form = KategoriForm(instance=ktgr) else: form = KategoriForm if request.method == 'POST': if kategoriId: form = KategoriForm(request.POST, instance=ktgr) else: form = KategoriForm(request.POST) if form.is_valid(): form.save() return … -
does python function work if multiple user call it at same instant
I am using django framework. I have built one web application using python and django. I am not using any classes or oops concept in my application. I am just using python's function. for e.g. def addnum(request): a=request.GET.get('a') b=request.GET.get('b') res=a+b return HttpResponse(json.dumps(res), content_type="application/json") Now this kind of functions i am calling from client side using ajax and getting back my result My question is .. if multiple users are accessing the application at same instant.. so this 'addnum' function will get call at same instant ... Then how will it work. will it get break for some of user and incorrect output ? will it decrease performance and increase response time? will it work parallely and everything will work fine? Please help me to get out of this problem/confusion! -
Django Multi-site with shared database
I am about to develop multiple sites for different real estate companies. All share the same html, sections, etc. The difference is in the content, specially the properties... But some of those properties can be shared among the rest of the companies. I am thinking in sharing the same database and differentiate content using the url. In this way I can use only one project instead of one for each company. Does anyone have recommendations for this kind of projects? Thanks, -
How to get request.user out of views?
I want to get user.pk from request (for logged in user) in order to avoid additional DB queries. In views there is incoming request variable. How to get this request somewhere out of views? Directly importing HttpRequest does not help, because HttpRequest gets user object because of middleware modification. How can I get this 'modified' HttpRequest with user object? What do I need to import? -
Strange behavior with Django register view
I have server and app. In app I send JSON to register view. JSON looks like: $.ajax({ dataType: 'json', type : "POST", url : BASE_URL+"register/", data: {username: un, password1: ps1, password2: ps2, email: e}, }); And my view: def register(request): form = RegistrationFormUniqueEmail(request.POST) if form.is_valid(): new_user = RegistrationView().register(request, **form.cleaned_data) rest of code it's doesn't matter because in this above line getting me an error. new_user = RegistrationView().register(request, **form.cleaned_data) TypeError: register() got an unexpected keyword argument 'password2' It's works recently on python 2.7, but now I migrate to python 3.5 Could you help me? -
jQuery Not Rearranging Elements
I'm trying to add 2 sort options to a web page. Currently, when I click the respective links (.alpha and .finish), I see an animation on the screen and can tell that the names are moving, but then the output remains the same. Below is the jQuery script I'm working with off of this JSFiddle that I found in a google search. I am using Django to display the page and currently have an order_by to correctly order each div alphabetically. Is this affecting it? var $divs = $('div.col-xs-3'); $('.alpha').on('click', function () { var alphabeticallyOrderedDivs = $divs.sort(function (a, b) { return $(a).attr('data-name') > $(b).attr('data-name'); }); $('.people').html(alphabeticallyOrderedDivs); }); $('.finish').on('click', function () { var numericallyOrderedDivs = $divs.sort(function (a, b) { return $(a).attr('id') < $(b).attr('id'); }); $('.people').html(numericallyOrderedDivs); }); -
Reverse for 'detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/$']
My traceback: File "D:\virtualEnv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\virtualEnv\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "D:\virtualEnv\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in post 217. return super(BaseCreateView, self).post(request, *args, **kwargs) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in post 183. return self.form_valid(form) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in form_valid 163. return super(ModelFormMixin, self).form_valid(form) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in form_valid 79. return HttpResponseRedirect(self.get_success_url()) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in get_success_url 151. url = self.object.get_absolute_url() File "D:\virtualEnv\website\music\models.py" in get_absolute_url 13. return reverse('music:detail', kwargs={'pk': self.pk}) File "D:\virtualEnv\lib\site-packages\django\urls\base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "D:\virtualEnv\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix 389. (lookup_view_s, args, kwargs, len(patterns), patterns) Exception Type: NoReverseMatch at /music/album/add/ Exception Value: Reverse for 'detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['music/(?P[0-9]+)/$'] my Album model is: class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def get_absolute_url(self): return reverse('music:detail', kwargs={'pk': self.pk}) my views.py: class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' class AlbumCreate(CreateView): model = Album fields … -
How to use TextInput widget with ModelChoiceField in Django forms?
In Django, the ChoiceField or ModelChoiceField represent the data in a Select widget. This is helpful when the list of objects is small. However it is extremely difficult to manage (for the end-user) if the number of objects are in thousands. To eliminate the said problem I'd like the end-users to manually enter the field value in an input box of type text (i.e, via TextInput widget). So far, I have created the below code. As ModelChoiceField has Select widget by default; It behaves in similar manner as before even after changing the widget to TextInput. It expects a pk or id value of the model object and thus raising an error : Select a valid choice. That choice is not one of the available choices. However, I'd want the end-user to enter sku_number field in the input box rather than the pk or id of the object. What is the correct way to solve this problem? models.py class Product(models.Model): sku_number = models.CharField(null=False, unique=True) product_name = models.CharField(null=Flase) def __str__(self): return self.sku_number forms.py class SkuForm(forms.Form): sku_number = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.TextInput()) extra_field = forms.CharField(required=True) Note : I did try another approach to solve this problem. By displaying only last 10 objects by slicing … -
DRF serializer with generic foreign key - check if given object ID exists before saving
I'm trying to find a way of checking whether given object ID exists in a generic relation in serializer, like there is for PrimaryKeyRelatedField. So far, I came with this approach: models.py: class Comment(models.Model): person = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, limit_choices_to={'pk__in': CONTENT_TYPES_PK}) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') serializers.py: class CommentSerializer(serializers.ModelSerializer): person = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) content_type = serializer.PrimaryKeyRelatedField(queryset=ContentType.objects.filter(pk__in=CONTENT_TYPES_PK), write_only=True) class Meta: model = Comment extra_kwargs = { 'created': {'read_only': True}, 'object_id': {'write_only': True} } def create(self, validated_data): obj = Comment(**validated_data) if not obj.content_object: raise serializers.ValidationError({'object_id': ['Invalid pk "'+str(obj.object_id)+'" - object does not exist.']}) obj.save() return obj But this isn't a robust way of doing such, because it actually doesn't raise a field error - it just imitates it and therefore in API Viewer the field isn't highlighted. I wonder if there's some better solution for this? Thanks in advance! This is how it looks like after submitting the form: -
Page not found (404) error on django
I am trying to get price value as soon as product is selected in sale form. There is a sale form which has field of price, quantity and product. When user selects for product, the price of that product should be shown to the input box of price. For that i have used ajax. But i am getting an error of 404 page not found in sales/price/2. When i enter that url in browser i get the result as {"price-pk": 2, "price": 890.0} The code sales/views.py def fetch_price(request, pk): response = {} product = get_object_or_404(Product, pk=pk) print('product',product) if request.method=='GET': price = product.price print('price',price) response['price-pk'] = product.pk response['price'] = price json_data = json.dumps(response) return HttpResponse(json_data, content_type='application/json') sales/urls.py url(r'^price/(?P<pk>\d+)$', views.fetch_price, name='fetch_price'), add_sale.html <script> $('#id_product').on('change', function() { price_id = $(this).val(); // if shoe is selected price_id value becomes 2 as pk of shoe is 2 console.log(price_id); url = "/sale/price/"+price_id+"/"; $.ajax({ type:'GET', url:url, success: function(data){ console.log('price will be updated based on product selected'); $('#id_price').val(data.price); } }) }); </script> -
Revoke a task from celery
I want to explicitly revoke a task from celery. This is how I'm currently doing:- from celery.task.control import revoke revoke(task_id, terminate=True) where task_id is string(have also tried converting it into UUID uuid.UUID(task_id).hex). After the above procedure, when I start celery again celery worker -A proj it still consumes the same message and starts processing it. Why? When viewed via flower, the message is still there in the broker section. how do I delete the message so that it cant be consumed again? -
How to correctly implement both site.com/username and site.com/id123?
I want to let users to have customized urls, such as site.com/username, but I do not want to force them to do this, so in this case I would like to have addresses like this one: site.com/id123 Current approach: # root urls.py urlpatterns = [ url(r'^((?P<user_id>[i][d]\d+)|(?P<username>[\w.+-]+))/', include('profiles.urls', namespace='profiles_user')), # profiles/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.profiles_home, name='profiles_home'), ] # profiles/views.py def profiles_home(request, user_id=None, username=None): if user_id: user_id = int(user_id.replace('id', '')) user = get_object_or_404(UserProfile, pk=user_id) else: user = get_object_or_404(UserProfile, username=username) return render(request, 'profiles/profiles_home.html', {'profile_user': user}) This approach is not flexible. Particularly the problem is with navigation\menu, where I want to make a button My page. For navigation I use django-sitetree, where there is no built-in feature to use 'double'-link for 1 button which would depend on whether user has username or not. The scheme, which sitetree uses in order to connect buttons to links is defining url_namespace:url_name. Could anyone advise me how to improve\simplify urls?