Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unit test will not update BooleanField
I have a situation where I want to have published functionality for articles, and I have it. The problem is that I can't get my unit test to work properly, trying to post True to the published field. Here's what my tests look like. class ArticleDetailViewTest(TestCase): def setUp(self): email = 'testuser@gmail.com' first_name = 'test' last_name = 'user' password = 'test15146' user = User.objects.create_user(email, first_name, last_name, password) self.client = Client() self.client.login(username='testuser@gmail.com', password='test15146') def test_can_publish_article_from_POST(self): other_article_two = Article.objects.create(name='Test Name One', author=User.objects.get(email='testuser@gmail.com')) correct_article_two = Article.objects.create(name='Test Name Two', author=User.objects.get(email='testuser@gmail.com')) response = self.client.post(reverse('publish_article', kwargs={'pk' : correct_article_two.pk})) self.assertEqual(response.status_code, 302) self.assertRedirects(response, f'/articles/{correct_article_two.pk}/') self.assertEqual(correct_article_two.published, True) Here's what my publish article view looks like. def publish_article(request, pk): article = get_object_or_404(models.Article, pk=pk) if request.method == "POST": article.published = True article.save(update_fields=['published']) return redirect('article_detail_view', pk=article.pk) else: raise Http404 Here are my urls. from django.urls import path from . import views urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('new/', views.ArticleCreateView.as_view(), name='article_new'), path('<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail_view'), path('<int:pk>/publish/', views.publish_article, name='publish_article'), path('<int:pk>/unpublish/', views.unpublish_article, name='unpublish_article'),] Here are my models. from django.conf import settings from django.db import models from django.urls import reverse from django import forms class Article(models.Model): name = models.CharField(max_length=255, blank=False) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) published = models.BooleanField(default=False) def __str__(self): return self.name def get_absolute_url(self): return reverse('article_detail_view', args=[str(self.id)]) … -
django query with prefetch_related
I am struggling to get at the data I need from a prefetch-related query. I have a table of events (the calendar table), a table of members and an attendee table which links the two. My models look like: class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=50) email = models.EmailField(blank=True, verbose_name ='e-mail') phone = models.CharField(max_length=40) membershipnum = models.CharField(max_length=40) class Attendee(models.Model): memberid = models.ForeignKey(Member, on_delete=models.SET(0), related_name="attendingmembers") calendarid = models.ForeignKey(Calendar, on_delete=models.SET(0)) attended = models.BooleanField(default=0) paid = models.BooleanField(default=0) class Meta: db_table = 'attendee' For a particular event I want a list of attending members with the attended and paid fields from the attendee table. In my view I have attendees = Member.objects.filter(attendingmembers__calendarid_id=id).prefetch_related('attendingmembers') I am getting the right members, but I don't know if this is the best way to do it? And I can't figure out how to get at the attendee fields. If I do for thisone in attendees: print(thisone) print(thisone.attendingmembers) I get the expected return from the first print, but the second just gives me myapp.Attendee.None Any advice much appreciated. -
select related in Django
I am trying to accomplish something very similar to: How to join 3 tables in query with Django Essentially, I have 3 tables. In the Django REST we are showing table 3. As you see below (models.py), table 3 has company_name which is a foreign key of table 2 and table 2 is a foreign key of table 1. Both table 2 and 3 are linked by the table 1 ID. Table 1 contains the actual text, which we want to display in the API output, not the ID number. Table 1: Manufacturer of Car -- Table 2: What the Car is -- Table 3: list of all cars Models.py Table 1: class ManufacturerName(models.Model): name_id = models.AutoField(primary_key=True) company_name = models.CharField(unique=True, max_length=50) class Meta: managed = False db_table = 'manufacturer_name' Table 2: class CarBuild(models.Model): car_id = models.AutoField(primary_key=True) car_icon = models.CharField(max_length=150, blank=True, null=True) company_name = models.ForeignKey('ManufacturerName', models.DO_NOTHING) class Meta: managed = False db_table = 'car_build' Table 3: class CarList(models.Model): list_id = models.AutoField(primary_key=True) company_name = models.ForeignKey('CarBuild', models.DO_NOTHING, db_column='news_source') title = models.CharField(unique=True, max_length=100) description = models.TextField() class Meta: managed = False db_table = 'cars' Within my views: This is what I am trying, based on the foreign key relationships: queryset = CarList.objects.all().select_related('company_name__company_name') I get … -
python interpreter version changed still not able to deploy on heroku
the problem is once i created the api i thought to push it on heroku. now the problem was it cant run any other version of python other then python-3.6.6. Now what i did i went to my pycharm and altered the version of my python enterpreter alongwith my requirements.txt file as well as my runtime.txt file. Now the problem still isnt solved it shows the error $git ppush heroku master Counting objects: 11974, done. Delta compression using up to 4 threads. Compressing objects: 100% (10841/10841), done. Writing objects: 100% (11974/11974), 30.62 MiB | 162.00 KiB/s, done. Total 11974 (delta 5058), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.6 (you are using Pyt hon-3.6.6, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3 .6.6). remote: Learn More: https://devcenter.heroku.com/articles/python- runtime remote: -----> Installing Python-3.6.6 remote: ! Requested runtime (Python-3.6.6) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/pytho n-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to … -
pass new filename with file using HttpResponse
The file is downloaded using the following code, but the downloaded file gets the whole filePath as a filename, I want to set the filename to "myfile.zip" import os from django.http import HttpResponse def getFile(request): currentPath = os.path.dirname(os.path.realpath(__file__)) filename = "somezipfile.zip" filePath = os.path.abspath(currentPath + "/../" + filename) response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename={}'.format(filePath) return response I have seen several questions about sending files, but I need to pass the path to the file and a parameter for the filename. Any ideas? -
Can't access through localhost to my web server on docker
I am following this tutorial to achieve a dockerized django app: http://ruddra.com/2016/08/14/docker-django-nginx-postgres/ I am able to build and run the docker image and conatiner without problem. For example my services from container are in these status: docker ps docker-compose logs web docker-compose logs nginx returs nothing Dockerfile is: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /config ADD /config/requirements.pip /config/ RUN pip install -r /config/requirements.pip RUN mkdir /src; WORKDIR /src docker-compose.yml is version: '2' services: nginx: image: nginx:latest container_name: ng01 ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: dg01 command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn helloworld_project.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./src:/src expose: - "8000" db: image: postgres:latest container_name: ps01 helloworld_project is: upstream web { ip_hash; server web:8000; } # portal server { location / { proxy_pass http://web/; } listen 8000; server_name localhost; } requirements.pip is Django==2.0.5 gunicorn==19.7.1 psycopg2==2.7.3.2 And all the project structure is: Why localhost:8000 and/or localhost:80 run with mozilla firefox says the connection is restarted and I am not able to view the app? -
Django ORM query to get data from multiple tables
I need to retrieve data from multiple tables to display shop name, shop location, shop monthly sales volume(unit), monthly sales amount, and sales person name who take orders from the shop. My sample table example below: Order id total_price added_by_id(employee id) customer_id 1 42480 2 1 2 74920 3 2 3 21000 3 2 1 42480 2 1 OrderItem order_id unit 1 1 1 2 2 2 2 2 3 2 4 5 Customer id full_name location 1 Shop1 Example location1 2 Shop2 Example location2 Employee id full_name 1 Employee Name1 2 Employee Name2 And the resultant table should be shop name location salesperson sales volume monthly sales Shop1 location1 Employee Name1 8 43630 Shop2 location2 Employee Name2 6 95920 My Try: Order.objects.select_related('account_customer').all() .values('customer_id') .annotate(total_sales=Sum('total_price')) .filter(created_at__year=today.year, created_at__month=today.month) It will return <QuerySet [{'customer_id': 1, 'total_sales': Decimal('43630.00')}, {'customer_id': 2, 'total_sales': Decimal('95920.00')}]> I can't retrieve other necessary information like shop name, location, salesperson name sales volume. How can I retrieve all of my necessary information? -
Django Query to Return Max 3 Field Names With Highest Sum
I have the following table in my Django Models: Date | Field1 | Field2 | Field3 | Field4 | Field5 | Field6 | 05/01/2018 | 7 | 1 | 8 | 4 | 9 | 2 | 05/02/2018 | 9 | 2 | 1 | 1 | 6 | 2 | 05/03/2018 | 8 | 1 | 3 | 1 | 5 | 1 | 05/04/2018 | 7 | 1 | 8 | 4 | 9 | 2 | 05/05/2018 | 7 | 1 | 8 | 4 | 9 | 2 | I would like to return the names of the top 3 fields with the highest sum over a custom time period. For example if I want to get the NAMES of the Top 3 fields with the highest sum between 05/02/2018 and 05/04/2018, this should return the following: 'Field1, Field5, Field3' because: Date | Field1 | Field2 | Field3 | Field4 | Field5 | Field6 | 05/02/2018 | 9 | 2 | 1 | 1 | 6 | 2 | 05/03/2018 | 8 | 1 | 3 | 1 | 5 | 1 | 05/04/2018 | 7 | 1 | 8 | 4 | 9 | 2 … -
Wagtail: PageChooserPanel not showing up
I'm trying to add a PageChooserPanel to a Related Links model, and it is not showing up in the admin. I get no errors in migrating or loading the page. Here is the code: sua_base.py: class RelatedLinks(models.Model): page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) title = models.CharField(max_length=255, blank=True) url = models.URLField("Embed URL", blank=True) panels = [ FieldPanel('title'), PageChooserPanel('page'), FieldPanel('url'), ] class Meta: abstract = True verbose_name = "Related Link" verbose_name_plural = "Related Links" app.py: from sua_base.models import WebPage, Section, RelatedLinks class SUAWebPage(WebPage): sidebar_content_panels = [ InlinePanel('related_links', label="Related Links") ] edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(sidebar_content_panels, heading='Sidebar'), ObjectList(WebPage.settings_panels, heading='Settings', classname="settings"), ObjectList(Page.promote_panels, heading='Promote'), ]) class Meta: verbose_name = "SUA Web Page" verbose_name_plural = "SUA Web Pages" class SUAWebPageRelatedLinks(RelatedLinks, Orderable): page = ParentalKey(SUAWebPage, related_name='related_links') -
Dynamically generate SQL column on runtime using Django Models
I am trying to create a model based on current active members of a particular sports team of different state, I want to generate a Member_Name field based on the number of Team_Members field value. For example, if there are 3 active Team_Members, Django model should create 3 Member_Name Fields accordingly. STATE_CHOICE = ['state1', 'state2', 'state3'] state = sorted(STATE_CHOICE) SPORT_CHOICE = ['basketball', 'football', 'cricket', 'hockey'] class Sports(models.Model): state = models.CharField(max_length=100, choices=state, default=state[0]) team_members = models.IntegerField(required=True) sport = models.CharField(choice=SPORT_CHOICE, default=STATE_CHOICE[0]) -
Django - Using {% for field in form %} on checkboxes, causes field to generate all alternatives
In my template I would like to display all my checkboxes, but having custom tags between each alternative. But the {{ field }} tag (to my surprise) does not generate one alternative at a time but rather spits out everything at once, since all alternatives belong to the same "field". How can I iterate through each alternative instead? See code example below. What I have: template.html <div id="checkRadios"> <div class="col-sm-6 col-lg-3"> {% for field in form %} <div class="checkbox"> {{ field }} <span class="checkmark"></span> </div> {% endfor %} </div> </div> What I get: <div id="checkRadios"> <div class="col-sm-6 col-lg-3"> <div class="checkbox"> <label for="id_0"><input type="checkbox" name="name_0" value="26" id="id_0" /> one</label> <label for="id_1"><input type="checkbox" name="name_1" value="27" id="id_1" /> two</label> <span class="checkmark"></span> </div> </div> What I want: <div id="checkRadios"> <div class="col-sm-6 col-lg-3"> <div class="checkbox"> <label for="id_0"><input type="checkbox" name="name_0" value="26" id="id_0" /> one</label> <span class="checkmark"></span> </div> <div class="checkbox"> <label for="id_1"><input type="checkbox" name="name_1" value="27" id="id_1" /> two</label> <span class="checkmark"></span> </div> </div> -
Django M2M with a large table
I have a typical M2M scenario where promotion activities are related to our retailers. However we have a large number of retailers (over 10k) and therefore I can't use the normal multiple select widget. What I would aim to do is have an 'activity' instance page with a 'retailer' sub-page which would have a table listing all those retailers currently related to the activity. In addition there would be a 'delete' checkbox next to each retailer so they could be removed from the list if necessary. (Naturally, I would also have another search/results page where users could select which retailers they want to add to the list, but I'm sure I can sort that out myself). Could someone point me in the right direction regarding modelforms and formset factories as I'm not sure where to go from here. It would seem obvious to directly manipulate the app_activity_associated_retailers table but I don't think I can do this with the existing functions. Is there was a pattern for doing this. class Activity(models.Model): budget = models.ForeignKey('Budget') activity_type = models.ForeignKey('ActivityType') amount = models.DecimalField(max_digits=8, decimal_places=2) associated_retailers = models.ManyToManyField('Retailer', related_name='associated_retailers') class Retailer(models.Model): name = models.CharField(max_length=50) address01 = models.CharField(max_length=50) address02 = models.CharField(max_length=50, blank=True) postcode = models.CharField(max_length=5) city … -
Cannot import name 'views',.Python, Django
I have read many answers in this forum, but they does not solve my problem. I will be very grateful for help. My file views.py returns this error: from . import views ImportError: cannot import name 'views' from '__main__' (C:/Users/tymot/Desktop/weather app/env/Environemnt/the_weather/weather/views.py) views.py from django.shortcuts import render from django.contrib import admin def index(request): return render(request, 'weather/index.html') #returns the index.html template from django.urls import path from . import views urlpatterns = [ path('', views.index), #the path for our index view ] Directory -the_weather --the_weather ---__init__ ---setting ---urls ---wsgi --weather ---migrations ----__init__ ---templates ----weather -----index ---__init__ ---admin ---apps ---models ---tests ---urls ---views --db --manage.py I try use to resolved my problem from __future__ import absolute_import, or homepage import views. I else try copy views.py to directory templates (and modify its code) but unfortunately it not work -
Django display different models/tabells
I get stuck. I try to display each time a other table in django with the same def in my view.py code. First problem is I can't transfer the string which I enter in the url to a model. For example if I type 0.0.0.0:8000/polls/Cashflows I wanna display the table Cashflows of my db. from django.http import HttpResponse from django.template import loader from django.apps import apps from .models import Cashflows,Garbage,Inputacturial def index(request): list_cashflows=Cashflows.objects.all() template=loader.get_template('polls/index.html') context={'list_cashflows':list_cashflows,} return HttpResponse(template.render(context,request)) def detail(request, table): #model = apps.get_model('polls', 'table') #model=apps.get_model ( 'polls',table.split('.',1)) model=Cashflows liste_column=model.objects.all() b=model._meta.get_fields() #b=a[:] liste_fields=list(b) template=loader.get_template('polls/index2.html') context={'liste_column':liste_column,'liste_fields':liste_fields,} return HttpResponse(template.render(context,request)) I try different options but none of these really work for. My next problem is to display these different tables. I try to start with the field names. <table>{% for item in liste_fields%} <tr><th>liste_fields.item</th> </tr> {% endfor %} </table> It's just give me three rows with liste.fields.item and not columns with each field. Can you help me? -
Sending data by POST in Reactjs to Django rest api endpoint
I am using react and Django. I am new to Django rest framework and react. I want to make a form that can update users detail by POST request. But when I do post it shows csrf token missing or method not allowed. class ProfileRUView(generics.RetrieveUpdateAPIView): serializer_class = ProfileSerializer lookup_field = 'pk' # permission_classes = [IsOwner] def get_queryset(self): return Profile.objects.all() @method_decorator(csrf_exempt) def put(self, request, *args, **kwargs): pk = self.kwargs.get('pk') this_user = Profile.objects.filter(pk = pk).first().user if request.user != this_user: res = {"code": 400, "message": "Bad Requset"} return Response(data=json.dumps(res), status=status.HTTP_200_OK) return self.update(request, *args, **kwargs) and serializer file is from rest_framework import serializers from profiles.models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ 'name', 'gender', 'bio', 'image', 'address' ] and in react side, I am using axios to make a post or put request but both are not working. updateUser() { axios .post('/me/api/1/', { "name": "Ishwar", "gender": "Male", "bio": "", "image": null, "address": "" } ) .then(function (response) { console.log(response); console.log(response.data); }) .catch(function (error) { console.log(error); }); } The API /me/api/1/ is created by Django rest framework and is working correctly and I can update users detail there. I want to use this API with react. How can I do … -
filling a Django form from a separate requests.post python script
while reading about the Requests library, it occurred to me that I could try to fill a form by using it. So, since I have Django and the server, I first checked that I got the URL well and got a 200 answer code. like this: import requests r = requests.get('127.0.0.1/myform') print(r.status_code) and yes, it was a 200 so the next step was going to be entering a value in the textfield, actually the form, for this example is just one field. I tried this: r = requests.post('127.0.0.1/myform', data ={'name' : 'Mexico'´} and nothing was entered. Here I have like 3 intriguing questions: When I inspect the element, because the form was created using the ModelForm of Django, I could not actually give the field a name, (which would have been name) and 2. Django instead fills me the name with the csrf token value and 3. actually, I don't see how the requests.post presses the submit button. What would be what is missing here in order to succeed posting the value through the form? thank you -
AttributeError: 'CSVupload' object has no attribute 'urls'
models.py class AdminProduct(models.Model): productname = models.CharField(max_length=50) barcode = models.BigIntegerField() def __str__(self): return self.productname class CSVupload(models.Model): csv = models.FileField(upload_to='product/',null=True,blank=True) admin.py from django.contrib import admin from .models import AdminProduct from .models import CSVupload # Register your models here. admin.site.register(AdminProduct,CSVupload) Want to register two models in admin,AdminProduct and CSVupload. Getting an error :- AttributeError: 'CSVupload' object has no attribute 'urls'. How do I do it? -
How can I use same serializer for GET and POST?
I have following snippet from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) class QuestionSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Question class ChoiceSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Choice depth = 1 class ChoiceAPI(ModelViewSet): queryset = Choice.objects.all() serializer_class = ChoiceSerializer Currently I got output as, [ { "id": 1, "choice_text": "choice-1", "votes": 1, "question": { "id": 1, "question_text": "Maximizing Assassin damage", "pub_date": "2018-07-13T13:29:36Z" } } ] Now, I wish to create new Choice instance with payload, { "choice_text": "choice-1", "votes": 1, "question": 1 } But, When I try with above payload, I got an exception as IntegrityError at /sample/test/ NOT NULL constraint failed: sample_choice.question_id. After I googled, I found a way to solve this by overriding get_serializer_class() method of ModelViewSet. My question is, Is there any way to do this without overriding get_serializer_class() method of ModelViewSet? -
Django 1.10: The current URL didn't match any of these
mysite/urls.py from django.conf.urls import url,include from django.contrib import admin from django.contrib.auth import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('blog.urls')), url(r'^accounts/login/$', views.login, name='login'), url(r'^accounts/logout/$', views.logout, name='logout', kwargs={'next_page': '/'}), ] blog/urls.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$',views.PostListView.as_view(),name='post_list'), url(r'^about/$',views.AboutView.as_view(),name='about'), url(r'^post/(?P<pk>\d+)/$', views.PostDetailView.as_view() ,name='post_detail'), url(r'^post/new/$', views.CreatePostView.as_view(), name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', views.PostUpdateView.as_view() , name='post_edit'), url(r'^drafts/$', views.DraftListView.as_view() , name='post_draft_list'), url(r'^post/(?P<pk>\d+)/remove/$', views.PostDeleteView.as_view() ,name='post_remove'), url(r'^post/(?P<pk>\d+)/publish/$', views.post_publish , name='post_publish'), url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post , name='add_comment_to_post'), url(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve , name='comment_approve'), url(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove , name='comment_remove'), ] Error ![This error occur when i try to edit the post, add comment, remove comment, or delete post]1 i can't fix the error ! -
Django + vue post request (form) issue
I'm trying to combine Django + Vuejs. So far I've found 2 ways of doing. Here : and here : using vue inside Django templates and here : totally splitting server (django) and client(vuejs) With the 2nd approach I've been struggling for hours just for submitting a simple form (might also just be because I'm a complete newbie in web dev). Could you please help me with this and tell me which approach is better. Here is my views.py from django: from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from rest_framework.response import Response from rest_framework import status from rest_framework.renderers import JSONRenderer from rest_framework.decorators import api_view, renderer_classes from .serializers import * from .forms import SignUpForm from .models import NighterProfile from django.contrib.auth.models import User import json @login_required def home(request): return render(request, 'home.html') @api_view(['GET', 'POST']) @renderer_classes((JSONRenderer,)) def signUp(request): if request.method == 'POST': form = json.loads(request.body) form = SignUpForm(form) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: formFields = (SignUpForm()).fields form = {} for field in formFields.keys(): form[field] = field return Response(form) I use request.body instead of request.POST as I was getting an error and then I read … -
Changing field in Django Form, overriding clean()
I have a date, passed as 2019-01-01T00:02. My objective is to replace the T with a whitespace, 2019-01-01 00:02. Using Form, i validate that field and some others.' klientForm = KlientForm(json.loads(request.body.decode())) bokningForm = BokningForm(json.loads(request.body.decode())) if klientForm.is_valid() and bokningForm.is_valid(): #Save model, etc. I'm using DateTimeField, and it will not accept the date unless I change it like above. I implemented my own clean() method, def clean(self): cleaned_data = super(BokningForm, self).clean() pumpStart = self.data['pumpStart'] pumpStart = pumpStart.replace("T", " ") cleaned_data['pumpStart'] = datetime.strptime(pumpStart, "%Y-%m-%d %H:%M") return cleaned_data This successfully converts it to a datetime object, I checked using print(cleaned_data) My issue is that the data is returned to late, as (I think) bokningForm.is_valid() has already failed, resulting in the model not being saved. I tried using clean_pumpStart(self): as in Django Forms but the function was not called when bokningForm.is_valid() failed, resulting in the same issue as above. Any help appreciated! -
to get better my custom def for validate login
i have a custom function for validate my login: def validate(request): if request.method=='POST': user = request.POST.get('user') pass = request.POST.get('pass') pass_enc = md5.new(pass).hexdigest() try: #validar si es admin usuarioAdmin = User.objects.get(user=user, pass=pass_enc, tipe=1, state=1) request.session['nameUser'] = user.name request.session['levelUser'] = "admin" return redirect('home') except User.DoesNotExist: message= "User/Password wrong !!" context = { 'message': message, } return render(request, 'login.html', context) on my home view: @login_required def home(request): template = loader.get_template('administrator/index.html') context = { } return HttpResponse(template.render(context, request)) for validate @login_required: def login_required(f): def wrap(request, *args, **kwargs): if 'nameUser' not in request.session.keys() : return redirect('logout') return f(request, *args, **kwargs) wrap.__doc__=f.__doc__ wrap.__name__=f.__name__ return wrap maybe any suggest or link for create my custom login and validate different tipes users(admin, comun user...etc..) thanks !! -
Why does Dramatiq fail to start in Docker-container?
I am trying to do distributed task-queue Django-project with Dramatiq as the worker-library. I'm able to run the project without errors when doing it from the dev-environment, but getting weird error when trying to run the Docker-container. I've run out ideas why this happens. The traceback of the error is: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django_dramatiq/management/commands/rundramatiq.py", line 83, in handle os.execvp(executable_path, process_args) File "/usr/lib/python3.5/os.py", line 615, in execvp _execvpe(file, args) File "/usr/lib/python3.5/os.py", line 660, in _execvpe raise last_exc.with_traceback(tb) File "/usr/lib/python3.5/os.py", line 650, in _execvpe exec_func(fullname, *argrest) FileNotFoundError: [Errno 2] No such file or directory I've made skeleton Django-project with single Dramatiq-task to reproduce the problem. If someone can take a look it can be cloned from here: https://bitbucket.org/AvareaToniN/dramatiqexample/src/master/ and here are the relevant parts from that repository: dramatiqexample │ .gitignore │ circus.ini │ Dockerfile │ entrypoint.sh │ manage.py │ requirements.txt │ ├───dramatiqexample │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───exampleapp │ admin.py │ apps.py │ models.py │ tasks.py … -
How to add drop-down list in django crispy forms and django filters
I want to add drop down choices for filtering. following is my piece of code forms.py from .models import Bowlers from crispy_forms.helper import FormHelper class BowlerListFormHelper(FormHelper): model = Bowlers form_tag = False filters.py import django_filters as df from .models import Bowlers class BowlerListFilter(df.FilterSet): class Meta: model = Bowlers fields = ['name', 'role', 'bat', 'bowl'] -
Is there a way I can initialize the value of an attribute of a django REST serializer based on the values of another field in the same serializer?
class MySerializer(serializers.Serializer): owner=serializer.ReadOnlyField(source='auth.username') ownerUrl = ..... Say I have a serializer like so, with the create and update methods (not shown here), now what I want is the ownerUrl to take a value when a serializer is made, according to the owner value of the same serializer, how do I do this? for example is we make a serializer like so serializer=MySerializer(MyModel.objects.get(pk=10)) then serializer.data.get('ownerUrl') has a value which is based on the value of the owner, may be something like <value of owner>+"/".