Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display the user's username when displaying their row from a seperate database table
On my website, I have a page where I display all my user's profiles (containing info such as bio, location etc). This data is NOT stored in my 'User Model' but in a model named 'Profile'. Obviously, I display this information like this: views.py queryset_list = Profile.objects.all() template {% for Profile in queryset_list %} {{Profile.bio}} {% endfor %} I also want to display these user's 'usernames' (which is stored in the User Model, NOT the Profile Model) but I don't know how to reference the User Model in relation to the Profile Model to get the connected username. Any help would be much appreciated. -
How to save ordered multiple upload files in Django
I have a Django form to upload multiple images. With Javascript, I allow user to see files name and sort it using sortable.min.js library before submit the form. It's possible to save the files using the order the user gives? last_position = property.images.last().position for index, item in enumerate(self.request.FILES.getlist('image'), start=last_position + 1): i = Image(prop=property, image=item, position=index) i.save() -
slug as detail view in django
I have a little problem. I want to use slug as a detail view in my project. But I don't know what I must change. My project files are models. py from django.db import models from django.utils import timezone class Kategorie(models.Model): title = models.CharField(max_length=250, verbose_name="Kategoria") slug = models.SlugField(unique=True, max_length=250, verbose_name="Przyjazny adres url") class Meta: verbose_name="Kategoria" verbose_name_plural="Kategorie" def __str__(self): return self.title class Wpisy(models.Model): title = models.CharField(max_length=400, verbose_name="Tytuł") slug = models.SlugField(unique=True, max_length=400,verbose_name="Przyjazny adres url") content = models.TextField() created_date = models.DateTimeField(blank=True, null=True, verbose_name="Data utworzenia") category = models.ForeignKey(Kategorie, verbose_name="Kategoria", on_delete=models.CASCADE) class Meta: verbose_name="Wpis" verbose_name_plural="Wpisy" def __str__(self): return self.title urls.py from django.urls import path from . import views urlpatterns = [ path('', views.lista_bajek, name="lista_bajek"), path('bajki/',views.lista_bajek, name='lista_bajek'), path('bajki/(?P<pk>\d+)/$', views.detale_bajki, name='detale_bajki'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Wpisy def lista_bajek(request): lista_bajek = Wpisy.objects.all() context ={'lista_bajek': lista_bajek,} return render(request, 'bajki/lista_bajek.html', context=context) def detale_bajki(request, pk): detale_bajki = get_object_or_404(Wpisy, pk=pk) return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki}) the one of html file {% extends 'bajki/index.html'%} {% block content %} <!DOCTYPE html> <html> <head> <title>Bajki</title> </head> <body> {% for bajki in lista_bajek %} Tytuł : <a href="{% url 'detale_bajki' pk=bajki.pk %}">{{bajki.title}} </a><br> {% endfor %} {% endblock %} </body> </html> Can somebdy tell me what I must to change … -
how can set a default value for MultiSelectField of a django model
from django.db import models from multiselectfield import MultiSelectField class Shop(models.Model): DAYS = ( ('sunday', 'Sunday'), ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday'), ('thursday', 'Thursday'), ('friday', 'Friday'), ('saturday', 'Saturday'), ('Not any day', 'None'), ) closingDay = MultiSelectField(choices=DAYS) click here to get picture -
Celery + Sqs. Worker suddenly crash
I use SQS as broker for celery. When I start worker, it suddenly shutdown. My configs BROKER_URL = 'sqs://XXX:YYY@' BROKER_TRANSPORT_OPTIONS = { 'region': 'us-east-1', 'queue_name_prefix': 'dev-' } CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_CONTENT_ENCODING = 'utf-8' CELERY_QUEUES = ( Queue('high', Exchange('high'), routing_key='high'), Queue('low', Exchange('low'), routing_key='low'), ) When i start celery i see: [2018-01-21 15:05:17,193: INFO/MainProcess] Starting new HTTPS connection (1): queue.amazonaws.com [2018-01-21 15:05:17,889: INFO/MainProcess] Connected to sqs://XXX:**@localhost// [2018-01-21 15:05:17,932: INFO/MainProcess] Starting new HTTPS connection (1): queue.amazonaws.com After it worker stops Installed packages: boto3==1.5.19 botocore==1.8.33 celery==4.1.0 crypto==1.4.1 kombu==4.1.0 pycrypto==2.6.1 pycurl==7.43.0.1 -
URL is not changing though page redirects in django
I have developed a simple django project in which photos will be stored and displayed. The problem is whenever I redirect to a page, the page gets loaded but the url does not change in the address bar. So when i refresh the page again, I am getting errors. For example, I created an album. For that the url is: 127.0.0.1:8000/create_album/ Then it has to redirect to the albums page where all albums of user are stored. That url is 127.0.0.1:8000/10/ But i am not getting that url when i redirect to that page. The views.py: **def create_album(request): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: form = AlbumForm(request.POST or None, request.FILES or None) if form.is_valid(): album = form.save(commit=False) album.user = request.user album.album_logo = request.FILES['album_logo'] album.save() return render(request, 'photo/detail.html', {'album': album}) context = { "form": form, } return render(request, 'photo/create_album.html', context) def detail(request, album_id): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: user = request.user album = get_object_or_404(Album, pk=album_id) return render(request, 'photo/detail.html', {'album': album, 'user': user})** The page has to be redirected to photo/detail.html. It redirects to the required page but the url doesn't change. Please help me with this. -
Removing the primary key in class based views ( django rest framework )
Problem : Currently in my api/urls.py I have this line url(r'^profile/(?P<pk>[0-9]+)/$', views.UserProfileView.as_view()), but I want to get the profile based on request.user and so I have the code in class UserProfileView as the following : class UserProfileView(generics.RetrieveUpdateAPIView): serializer_class = UserProfileSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) pagination_class = LimitTenPagination def get_queryset(self): try: queryset = UserProfile.objects.filter(user=self.request.user) except: raise APIException('No profile linked with this user') return queryset But If I remove the pk field from urls.py file, I get an error like this : AssertionError at /api/profile/ Expected view UserProfileView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. Which is expected. Possible solution : I made a function based view like this : @api_view(['GET', 'PUT']) def user_detail(request): """ Retrieve, update or delete a code snippet. """ try: user_profile_data = UserProfile.objects.get(user=request.user) except: raise APIException('No profile linked with this user') if request.method == 'GET': serializer = UserProfileSerializer(user_profile_data) return Response(serializer.data) elif request.method == 'PUT': serializer = UserProfileSerializer(user_profile_data, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And in the urls.py file added this line : url(r'^me/$', views.user_detail), This gets the work done, but I want a class based solution, so that in … -
How to get currency symbol from ISO country code in Django application?
I just want to get the Currency symbol for different countries in my Python Django application from the country code I have. For example I have a country code 'US', the output I need is '$' or 'US$'. Now I achieve this with the help of two libraries, namely pycountry and forex-python. Can I achieve this in a more simple way? import pycountry from forex_python.converter import CurrencyCodes code = "US" country = pycountry.countries.get(alpha_2=code) currency = pycountry.currencies.get(numeric=country.numeric) country_codes = CurrencyCodes() c.get_symbol(currency.alpha_3) Output: 'US$' -
Django admin - display children fields on "change" page
I am trying to display children fields (result.status and result.version) in "Select test to change" page. My current "Select test to change" page looks: enter image description here And I would like to add additional fields (as much as children items) and inside each of them I would like to have the status and version. While models looks like: class TestPlan(models.Model): test_plan_name = models.CharField(max_length=200) def __str__(self): return self.test_plan_name class Test(models.Model): test_plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE) test_name = models.CharField(max_length=200) test_type = models.CharField(max_length=200) manual_ttc = models.IntegerField(default=0) priority = models.IntegerField(default=0) owner = models.CharField(max_length=200) drop_name = models.CharField(max_length=200) test_description = models.CharField(max_length=200) note = models.CharField(max_length=200) ac = models.CharField(max_length=200) def __str__(self): return self.test_name class Result(models.Model): plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE) test = models.ForeignKey(Test) status = models.CharField(max_length=100) version = models.CharField(max_length=100) bug = models.CharField(max_length=100) result_path = models.CharField(max_length=100) def __str__(self): return self.status Thanks for your help, Eran Zilkha -
Setting multiple hosts in django-post_office
I am using django-post_office to send my emails but my problem is that I need to support more than 1 host, p.e. smtp.host1.com smtp.host2.com Each of this hosts has several users with their usernames and passwords. As far as I can see, django-post_office takes EMAIL_HOST, EMAIL_PORT etc only from the project settings. Is there a way to set the hostdata and userdata on the fly? Thanks! -
[Django-Social-Auth]: Current user always shows as "AnonymousUser"
I don't know why but when i authenticate user from social_auth (google OAuth2) it gets threw without any issue, but request.user always return "AnonymousUser", am i missing anything here, i tried with enabling all auth pipeline as well but no luck. views.py from django.contrib.auth import authenticate, login, logout def logoutUser(request): print("inside logout") logout(request) return render(request, 'Home/welcome.html') def likePost(request): print("inside like") print() print(dir(request.GET)) context={} context['User'] = request.user return render(request, 'Home/index.html', context) url.py from django.conf.urls import url,include from django.contrib import admin from authUser.views import loginUser, logoutUser from Home.views import homePage, newUserPage urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^loginUser/$', loginUser, name='loginUser'), url(r'^logoutUser/$', logoutUser, name='logoutUser'), url(r'^$', homePage, name='homePage'), url('', include('social_django.urls', namespace='social')), ] Templates <li> <a href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.path }}">Login with Google</a> </li> <li class="nav-item dropdown"> <li><a href="{% url 'logoutUser' %}"><span class=" nav navbar-nav navbar-right"></span>Logout! {{User}}</a></li> </li> Server log after enabling "social.pipeline.debug.debug" in settings.py {'access_token': 'xyz', 'circledByCount': 27, 'displayName': 'Madhur', 'emails': [{'type': 'account', 'value': 'xyz@gmail.com'}], 'etag': '"xyz"', 'expires_in': 3600, 'gender': 'male', 'id': 'xyz', 'id_token': 'xyz', 'image': {'isDefault': True, 'url': ''}, 'isPlusUser': True, 'kind': 'plus#person', 'language': 'en', 'name': {'familyName': 'xyz', 'givenName': 'xyz'}, 'objectType': 'person', 'token_type': 'Bearer', 'url': 'https://plus.google.com/xyz', 'urls': [{'label': 'Picasa Web Albums', 'type': 'otherProfile', 'value': 'http://picasaweb.google.com/xyz'}], 'verified': False} ================================================================================ {} ================================================================================ () ================================================================================ … -
azure web app deployment in django not working
when i deploy my django app in azure with sql database it is showing me The page cannot be displayed because an internal server error has occurred.but when i deploy it without sql database it works fine. what is the problem Thank you. -
Django custom authentication with email as username
So I am a bit stuck right now.I know about django user model and what means to extend it..kinda. The thing is that I don't know how to get started... I have a student model where name, surname and student ID are entered in by the admin. Fields of email, phone and photo, are readonly. I want that a student can make an account, where he can enter all those fields himself, but name, surname and student ID need to match with those from database, otherwise he cannot make account. What is a good approach ? class Student(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) photo = models.ImageField(upload_to='students_images') email = models.EmailField() phone = models.CharField(max_length=15, ) def __str__(self): return self.name + self.surname This is how I started. -
calling values from a different model - Django
A little stuck on this, i'm close to it, but sure i'm missing something I have 2 models. Equipment & Bookings I have a foreign key in Bookings to look up the equipment name works fine. Then in the booking form i want to show the hourly rate of the equipment selected (I will add some more functionally later to multiply by the days or hours selected, but just trying to get it to screen first) I trying to do it with some java script, my console log returns the ID of the equipment so i'm sure the problem is in the view, where i need to add some context for equipment, just no too sure how to do that. Here is the part of the java script i have: $('#id_equipment').on('change',function(){ var equid; equid = $('option:selected', this).attr('value'); console.log(equid); $.get("{% url 'equipment:add-equipmentbooking' %}", {content: equid, name: "equip_sum"}, function(data){ var result = $('<div />').append(data).find('#xhttp').html(); $('#xhttp').html(result); console.log(result) }); }); The logs return the ID of the item selected and the html, but not that data i'm after Here is the current view, only one model class EquipmentBookingCreateView(CreateView): model = EquipmentBooking template_name = 'equipment/equipmentbooking_form.html' form_class = EquipmentBookingForm success_url = '/equipment/list-equipmentbooking' def showval(request): equipment_list = … -
Django project applying user login and registration
hi i am very new in django and really need for your help. i am making a web sit in django which consist 4 small web app(gallery, news, live camera, realtime data).i want to only login user can upload pictures ,see the news ,can use live camera option. so my project struct like that WEBSITE gallery news Camera Realtime data now i want to introduce registration and login logout option.i want ,once user login from homepage ,can use any option(gallery,news etc) so where i write coding for login and registration. inside each webapp? if you can give me any link about this.. very helpful for me -
] ^ SyntaxError: invalid syntax
from django.contrib import admin from django.urls import path from webexample import views from django.conf.urls import url, includes urlpatterns = [ path('admin/', admin.site.urls), path('webexample/', include(webexample.views.index), ] ] ^ SyntaxError: invalid syntax File "C:\Users\admin\Desktop\ccc\mysite\mysite\urls.py", line 23 -
CSS file not loading in Django Progect
I have a CSS file in which i added a background initially to it. Then after some time i added some more background images to my media folder and tried to change the background. But this time, it didn't work. And moreover, the previous background image itself is loaded again. I tried to inspect the webpage. There, in sources, I opened the CSS file. It was not updated. It is still showing the previous background image url. How to rectify this issue? My CSS file(previously): body { background: white url("images/background.png"); } ul.errorlist { padding-left: 0; } ul.errorlist > li { list-style: none; } .navbar { border-radius: 0; } .navbar-brand { font-family: 'Satisfy', cursive; } Then I changed the background image url to: body { background: white url("images/ak.jpg"); } The new image is not loading. When I inspect the element, the previous CSS file is shown. -
Django serializer - unable to pass correct data in Many to Many relation with nested serializers
I am trying to solve this problem : A user can add skills to his profile and other user can upvote the skill on his profile . I have implemented adding skills in system . Now next I am trying build adding a skill (which is already added in system by admins ) to be added to the user profile . But in my POST API , i am always getting following error { "user": { "user": [ "This field is required." ] } } Body Input : { "user":{ "username": "USERN", "email": "diahu@gail.com", "first_name": "", "last_name": "" }, "new_user_skill": { "id": 1, "skill_name": "C" } } My View : elif request.method == 'POST': data = { 'user':request.data.get('user'),'skill_item':request.data.get('new_user_skill')} serializer = UserSkillSerializer(data=data) print("-------------------> serializer ") print(serializer) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Model : class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') extra_kwargs = { 'username': { 'validators': [], } } class UserProfileSerializer(serializers.ModelSerializer): user=UserModelSerializer() class Meta: model = UserProfile fields = '__all__' def create(self, validated_data): user_serializer = UserModelSerializer.create(UserModelSerializer(),validated_data = validated_data) user,created=UserProfile.objects.update_or_create(user=user_serializer) return user class UserSkillSerializer(serializers.ModelSerializer): user = UserProfileSerializer(required=True) skill_item = SkillSerializer(required=True) class Meta: model = UserSkill fields= '__all__' def create (self,validated_data): user_data = … -
Django Query - Prefetch filter based on query data?
Im trying to filter a prefetch based on its parent query object, is this possible? hopefully the below example explains. live link type from SiteData and circuit type from Circuits use the same child model. so for example if the live link type is 'Fibre' I want to prefetch only the circuit that has the circuit_type of 'Fibre'. each site can have many circuits but I only want the live one at this moment This is the query: conn_stats = SiteData.objects.all() .exclude(site_type__site_type='Factory') \ .exclude(site_type__site_type='Data Centre') \ .Prefetch( 'circuits_set', queryset=Circuits.objects.filter(SiteData.objects.live_link_type.circuit_type) ) ) these are the models: class CircuitTypes(models.Model): circuit_type = models.CharField(max_length=50) monitor_priority = models.IntegerField(verbose_name="Monitoring Priority", blank=True, null=True) class Meta: verbose_name = "Circuit Types" verbose_name_plural = "Circuit Types" def __str__(self): return self.circuit_type class SiteData(models.Model): location = models.CharField(max_length=50) site_type = models.ForeignKey(SiteTypes, verbose_name="Site Type", \ on_delete=models.PROTECT) is_live = models.BooleanField(default=False, verbose_name="Is this a live site?") live_link_type = models.ForeignKey(CircuitTypes, verbose_name="Link Type", \ on_delete=models.PROTECT, default=1) live_link_preference = models.CharField(max_length=200, blank=True, null=True) live_link_query_timestamp = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Circuits(models.Model): site_data = models.ForeignKey(SiteData, verbose_name="Site", on_delete=models.PROTECT) order_no = models.CharField(max_length=200, verbose_name="Order No") expected_install_date = models.DateField() install_date = models.DateField(blank=True, null=True) circuit_type = models.ForeignKey(CircuitTypes, verbose_name="Circuit Type", on_delete=models.PROTECT) ... -
SMTPAuthenticationError , username and password not accepted
So I am trying to make a registration form which requires confirmation sent by email before account is created. But I get error: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials g60sm43019864wrd.92 - gsmtp') I already tried the solution for this issues. I allowed low secure apps and also allowed account access(DisplayUnlockCaptcha). I cant seem to find any more fixes for this. def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('index') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'youremail@gmail.com' EMAIL_HOST_PASSWORD = 'yourpassword' EMAIL_PORT = 587 Traceback: http://dpaste.com/2S96YSK -
How to use a form showing selected and not selected in Django Admin
In django admin the Groups element of the Change User form gives you two lists with arrows to move from one list to the other. Something like the attached. I have a many to many field where I would like Django Admin to use this form but I cannot find out how to use it. Can anyone help? Thanks -
Using Django CreateView how can I access the request.session.user variable?
class ViewCreate(CreateView): model = view_C author_name = self.request.user.username #this is the error author = get_user_model().objects.get(username=author_name).pk publish_date = datetime.date.today() initial={ 'author':author, 'publish_date':publish_date, } author_name = self.request.user.username ... NameError: name 'self' is not defined How do I access the request.user variable from within a subclass of CreateView? I am trying to make use of a CreateView were the entries for author are automatically filled in using the session data and so don't have to be manaully entered. -
Return serializer data of a SET in Serializers.py in Django Rest Framework
I use Django Rest Framework for my project. I have a serializer function which return a SET but I dont know how to return it into data. Please help me! class BookSerializer(ModelSerializer): class Meta: model = Book fields = [ 'pk', 'book_name', ] class UserSerializer(ModelSerializer): booklist = SerializerMethodField() class Meta: model = User fields = [ 'username', 'booklist', ] def get_booklist(self, obj): ... booklist = set(result_user_obj).intersection(result_user_req) # Return data: [5, 2] ##### How to return it by BookSerializer????? ##### return booklist I want to print result: [{pk: 5, book_name: A}, {pk:2, book_name: B}] instead of [5, 2] -
Can't find model related descriptor field in django
I've checked a field class in the model and it is: django.db.models.fields.related_descriptors.RelatedManager I can't find in any file this field to be declared, where it may be stored or how to find it? -
Collect remarks for task in django-viewflow
Is there way to collect remarks for specific task when user submits his task form? Lets say i have below step to perform approval, where i'm exposing only ìs_approvedfield which will get stored in actual process model. Now along with ìs_approved, i also want to capture remarks for the same task. approve = ( flow.View( UpdateProcessView, fields=["is_approved"], task_title="Approve the document" ).Permission( lambda process: 'core.can_approve_{}'.format(process.process.type) ).Next(this.check_approve) )