Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to get response from Django application when running it in docker
I've created a Django application and I was able to run it locally. But when I try to run it using Docker, I'm not getting response. Inside the Dockerfile, I've exposed the port 8000 using EXPOSE 8000 and built the docker image using docker build -t myimage_name . I've done port mapping for Django application container and my localhost using docker run -it -p 8000:8000 myimage_name The docker container runs successfully and I'm able to see the server starting in the console with no issues. Django version 2.2.7, using settings 'SA.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. But, when I hit the endpoint http://127.0.0.1:8000/ from Postman client, it is returning the below error: This site can’t be reached. 127.0.0.1.8000’s server IP address could not be found. What might be wrong? -
Decoding base64 string return None
I tried to generate uid for a user confirmation email. 'uid':urlsafe_base64_encode(force_bytes(user.pk)), so, it's works nice, it returns something like "Tm9uZQ" Then, when I tried to decode it, using force_text(urlsafe_base64_decode(uidb64)) it return None. The next string urlsafe_base64_decode(uidb64) also, return b'None' I tried to google it, and see different implementations, but copy-paste code not works. I write something like b64_string = uidb64 b64_string += "=" * ((4 - len(b64_string) % 4) % 4) print(b64_string) print(force_text(base64.urlsafe_b64decode(b64_string))) and the result still None: Tm9uZQ== None I don't understand how the default decode doesn't work. -
Django Slug Number Issues
When updating an existing topic in the admin panel, the slug value changes. An example in the first update is: post / testpost. The next update appears as: post / testpost-1 Because the value changes when I return to my site and refresh my page; For this reason, I get a Page not found error (404) How do I fix this problem? models.py class Post(models.Model): slug = models.SlugField(unique=True, editable=False, max_length=130, null=True, blank=True, allow_unicode=True) def get_unique_slug(self): slug = slugify(self.title.replace('ı', 'i')) unique_slug = slug counter = 1 while Post.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(Post, self).save(*args, **kwargs) views.py def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) def post_update(request, slug): if not request.user.is_superuser: return HttpResponse ("Lütfen giriş yapınız") post = get_object_or_404(Post, slug=slug) form = PostForm(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): form.save() messages.success(request, 'Başarılı bir şekilde güncellediniz.') return HttpResponseRedirect(post.get_absolute_url()) context = { 'form': form, } return render(request, 'post/form.html', context) def post_delete(request, slug): if not request.user.is_superuser: raise Http404() post = get_object_or_404(Post, slug=slug) post.delete() return redirect('post:index') url.py urlpatterns = [ path('index/',views.post_index, name='index'), path('create/',views.post_create, name='create'), path('<slug>',views.post_detail, name='detail'), path('<slug>/update/',views.post_update, name='update'), path('<slug>/delete/',views.post_delete, name='delete'), ] -
How to Change Values of Serialized Data in RetrieveUpdateDestroyAPIView
First, I would like to present how my managers, models, serializers and views look like upfront. class PublishedManager(models.Manager): """ Only published articles. `due_date` is past. """ def get_queryset(self): now = timezone.now() return super().get_queryset().filter(due_date__lt=now) class UnpublishedManager(models.Manager): """ Only unpublished articles. `due_date` is future. """ def announced(self): return self.get_queryset().filter(announced=True) def get_queryset(self): now = timezone.now() return super().get_queryset().filter(due_date__gt=now) class Article(models.Model): content = models.TextField() due_date = models.DateTimeField() announced = models.BooleanField() # managers objects = models.Manager() # standard manager published = PublishedManager() unpublished = UnpublishedManager() class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ("content", "due_date") class ArticleRUDView(generics.RetrieveUpdateDestroyAPIView): serializer_class = ArticleSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = Article.objects.all() In this code, ArticleRUDView naturally responds with all Article because of Article.objects.all(), yet this is not what I want to do. What I want to do is: If the user is authenticated, then Article.objects.all(). If the user is anonymous, If the entry is published (which means its due_date is less than now), then serialize all fields. If the entry is not published (which means its due_date is greater than now), then still serialize, but content should be null in JSON. Or, in short, how do I alter the serializer's data in a view? Troubleshooting This section might get updated … -
form does not submit, nothing happens when submit button is clicked
My form just does not want to submit. My form looks like this: <form id="courseform" name="courseform" class="fs-form fs-form-full" autocomplete="off" method="POST" action="{% url 'checkout' %}"> {% csrf_token %} <input type="hidden" name="useremail" value="{{useremail}}"> <button id-"fs-submit-button"="" class="fs-submit" type="submit">Continue to payment</button> </form> At the very end of the page I have my javascript: $(".fs-submit").click(function(e) { $('#courseform').submit(); }); In my base project urls.py: from users import views as user_views urlpatterns = [ path('checkout/', user_views.checkout, name='checkout'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Absolutely nothing happens when the button is clicked. No javascript error in the console, nothing. -
Django rest framework show or hide API objects with checkbox in admin
I need to understand how show or hide objects in API serialize by django rest framework. I set a checkbox in my admin model to set active or inactive the object (true or false) class Video(models.Model): ... status = models.BooleanField('Activate video', default=False, help_text='If is checked show the video in the API') ... in my urls.py i set class VideoAPI(serializers.HyperlinkedModelSerializer): class Meta: model = Video fields = [...] class API_Video(viewsets.ModelViewSet): queryset = Video.objects.all() serializer_class = VideoAPI Now how can i show or hide objects in the API Json with the checkbox in my model? -
Python Many to Many Save() Causes an Operational Error - Django
I have two models using Django, trying to relate Notes and Hashtags. The models are as follows. class Hashtag(models.Model): title = models.CharField(max_length=200, default="") class Note(models.Model): title = models.CharField(max_length=200) body = models.TextField() created_at = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.DO_NOTHING) hashtags = models.ManyToManyField(Hashtag) Suppose I create a new note and want to associate it with some hashtags. When I do the following I get an operational error despite saving the items. In views.py: testHashtag = Hashtag(title="hello") testHashtag.save() tweet = Note.objects.create(title="foo", body="bar", author=request.user) tweet.save() tweet.hashtags.add(testHashtag) tweet.save() return redirect("/") The operational error is as follows. Django Version: 2.2.7 Exception Type: OperationalError Exception Value: no such column: core_note_hashtags.note_id I have also made sure all migrations have been performed. Any help would be appreciated. Thanks! -
Django case sensitive search
I have problem. I have model like this: class Teams(models.Model): Name = models.CharField(max_length=200) Short_name = models.CharField(max_length=200, default = "-") When I search team by short name, like "Har": models.Teams.objects.filter(SHort_name = "Har") I get results with "HAR" and "Har". Even if I try like this: models.Teams.objects.filter(SHort_name__exact = "Har"): I get same results ("HAR" and Har") The Short_name column is in utf8mb4_general_ci format, so it should be ok and database connection has this options: 'OPTIONS': {'charset': 'utf8mb4', 'use_unicode': True}, I don't know what is wrong or how to get exact one result. -
UnboundLocalError local variable 'context' referenced before assignment
I am stuck at this error(UnboundLocalError local variable 'context' referenced before assignment) while saving form of almost same type other are working fine but this one is not and showing error def clutchDetail(request): clutchDetail = ClutchDetail.objects.all() context = {'title': 'Clutch Detail', 'active': 'active', 'clutchDetail': clutchDetail, } return render(request, 'breedingRecApp/clutch_detail.html', context) def clutchDetail_add(request): if request.method == "POST": form = ClutchDetail_AddModelForm(request.POST or None) if form.is_valid(): try: form.save() return redirect('breedingRecApp:clutch_detail') except: pass else: form = ClutchDetail_AddModelForm() context = {'title': 'Species Detail Add', 'active': 'active', 'model': ClutchDetail, 'form': form, } return render(request, 'breedingRecApp/clutch_detail_add.html', context) Please help me to fix this error I am newbie to Django. I've an other form code which 100% same that is working fine but this one gives me an error I am stuck at it:( -
I get this error:Could not parse the remainder:
I was using for loop in HTML file and I get this error Could not parse the remainder: '(product)' from 'enumerate(product)' and my code is {%for count, Oneproduct in enumerate(product)%} <div class="col-xs-3 col-sm-3 col-md-3" > <div class="card" style="width: 18rem;"> <img src="(/media/{{product.i.image}})" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{product[count+1].product_name}}</h5> <p class="card-text">{{product[count+1].desc}}</p> <a href="#" class="btn btn-primary">Add to cart</a> </div> </div> </div> {%if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last%} </div> <div class="carousel-item "> {%if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last%} </div> <div class="carousel-item "> {%endif%} {%endfor%} -
How to have multiple choices in Django model retrieved from a csv file
i am looking a sipmple way to have django model field which generates a form where field choices can be selected from a csv file.. how to do it? As an alternative, how to retrieve data from an external API (instead of downloading it into a csv file?) -
How to pass optional parameters in url, via path () function?
I'm confused about passing optional parameter via url in Django with path() instead of url(). I found that I should use kwargs, so I added it to path: path('all/<str:category>/<int:page_num>/', views.show_all_objects, name="show-all-objects"), to path('all/<str:category>/<int:page_num>/', views.show_all_objects, kwargs={'city': None}, name="show-all-objects"), Ok but now how to pass additional parameter from template, I tried with: <a href="{% url 'show-all-objects' category='restaurants' page_num=1 city=1 %}" which returns me common error for NoReverseMatch at / So I added it to url: path('all/<str:category>/<int:page_num>/<int:city>/', views.show_all_objects, kwargs={'city': None}, name="show-all-objects"), But error is the same, I'm pretty sure, that this is not the proper way to do it, but I cannot find info about passing optional parameter via path(), all info is with url() Is it possible ? -
how to use Ckeditor in template (Html) in django?
I want to show the content that have written in the RichTextField from admin site. and i want them to show in the front end also but my code isn't working. Please help me with this. The code that i have written is not showing the content i have written in that field. help me with it..! I have setup Urls, views and other things also...! models.py from django.db import models from ckeditor.fields import RichTextField class Test(models.Model): content = RichTextField(blank=True,null=True) base.html #where I want to show that content in Homepage <!DOCTYPE html> <html> <head> <title>Base</title> </head> <body> {{test.content|safe}} </body> </html> -
django admin site customization change_list.html
Is it possible to change the viewi of change_list in Django admin site? just like on the picture this is my model.py class gradingPeriod(models.Model): Grade_Scales_Setting= models.ForeignKey(gradeScalesSetting, related_name='+', on_delete=models.CASCADE,null=True) Description = models.CharField(max_length=500,blank=True) Display_Sequence = models.IntegerField() Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) StartDate=models.DateField(null=True,blank=True) EndDate=models.DateField(null=True,blank=True) class gradingPeriodsSetting(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) NumberOfGradingPeriods = models.IntegerField(blank=True, null=True) class gradingPeriodsSummary(models.Model): Grading_Periods_Setting= models.ForeignKey(gradingPeriodsSetting, related_name='+', on_delete=models.CASCADE,null=True) Description = models.CharField(max_length=500,blank=True) Display_Sequence = models.IntegerField() Start_Grading_Period= models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,null=True) End_Grading_Period= models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,null=True) I don't know how to code it on the admin.py what I desire design in my change_list -
Migrate a model file with a deep hierarchy. django
This is my folder structure. And model is written in account.py. from .. class User(AbstractBaseUser, PermissionsMixin): ... After that, when makemigration is performed, accounts.py is not recognized. But the model of test.py was recognized. How can I recognize accounts.py? models/init.py from .commons import __init__ from . import test models/commons/init.py from . import accounts -
VS Code > Preferences > User Settings > Extensions > Python > Linting > Flake8 Args Added Item stopped working
Please don't treat this as an "asked and answered" question. I sincerely have been clobbering to try to figure out why this has stopped working, if it's a VS Code problem, or a Flake8 one, or if I'm just crazy and should find another way around this. Looking for a way to stop the Flake8 linter's "file is too long" and "not used" warnings, I found a solution listed as one of the hottest on StackFlow. I copied and pasted it exactly and it worked! Great, but while following Django Project tutorial on this code in admin.py file: from django.contrib import admin from .models import Choice, Question class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) suddenly, (the setting had been working fine for days), I got this Problem warning: line too long(80 > 79 characters) flake8(E501) (13,80) I know I may be too picky on this but it is really annoying. I've also read that I can break the line up using a backslash without breaking the continuity of the code, but I also tried that and got a message … -
Django Import Export Validation
I am trying to show the validation errors on the upload page. This is what I have : import.html <form class="importform" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> {{ form.errors }} </form> views.py def upload(request): if request.method == 'POST': chart_resource = ChartResource() dataset = Dataset() new_chart_data = request.FILES['myfile'] imported_data = dataset.load(new_chart_data.read()) result = chart_resource.import_data(dataset, dry_run=True) if not result.has_errors(): chart_resource.import_data(dataset, dry_run=False) else: print(errors) return render(request,'import.html') class WOForm(forms.ModelForm): class Meta: model = Workorder fields = ('series', 'start','end') def clean_label(self): return self.cleaned_data['series'].upper() def clean_price(self): return self.cleaned_data['start'].int() def clean_ctype(self): return self.cleaned_data['end'].lower() Also I need to translate the log to something that is understandable for normal users. Thank you for any help -
Using external database for user logins in Django
I have a Django application where, in development, I was using the default database (sqlite3, I believe) to store user login info. I had a line in my Dockerfile (which would spin up my app) that would add a user and it would automatically just be stored in the default database. Now that it's moving to production, it would be a colossal pain to add each user one at a time every time we need to update. From what I read in the documentation, it looked like I just needed to modify my settings.py from DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } to DATABASES = { 'default': { 'NAME': 'name_of_user_table', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'username', 'PASSWORD': 'password' } } I don't use the login info anywhere else in my code, and I can't find any reference to the database aside from in settings.py. Have I done enough to ensure that it can be connected to the external postgreSQL database of user logins, or is there more I need to do? This is my first Django application and I'm still learning how all of this stuff works. -
How to use django-filter on JSONField
django-filter works good on all the default fields of Model, but problem comes when we want to work it on postgres fields such as JSONField I have the following model: from django.contrib.postgres.fields import JSONField,ArrayField class MyModel(models.Model): j_field = JSONField(blank=True,null=True,default=dict) j_field has data in the following structure: [{"name":"john","work":"developer"},{"name":"cena","work":"teacher"}] How do I filter the results based on name or work from j_field using django-filter? import django_filters class MyModelFilter(django_filters.FilterSet) class Meta: model = MyModel ... ... what's next? -
Unable to access Django site from browser though there are url patterns
I'm trying to setup a Django site. I was able to add path in urls.py file. I was able to run the project using python manage.py runserver and see it running in console. But when I hit the url 127.0.0.1:8000 in the browser, it's giving me 404 error. I tried adding "*" to ALLOWED_HOSTS. But no use. When I tried adding "*.*", it's throwing error: DisallowedHost at / Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS. I'm getting the same error even after adding ["127.0.0.1", "localhost"]. I don't have any issue with firewall too. Is there anything that I'm missing that's causing this issue? -
By Django, how do I put datas which are from different html pages in one model?
I am a django baby. I am making movie reservation web site. I want to put datas which are from different html pages in one model. For example, in select_movie.html I want to get movie name(Avengers), in select_date I want to get date(2019-04-24) my client wants to see a movie, in select_time.html I want to get time(13:00) my client wants to see a movie, and in select_seat.html I want to get seat(A07) my client chooses. Like this. id / user_name / movie_name / data / time / seats 1 / koozzi / Avengers /2019-04-24 / 13:00 / A07 2 / koozzi2 / Avengers /2019-04-24 / 13:00 / A06 Could you please tell me which skill do I have to use?? I want to use "only" django and HTML! -
Monitor php changes in Django database
I have Django SQL database that is changed by php program. Is there a way to monitor this changes from Django? If not then what are the possibilities? -
How can to insert one html code from one field into another and to render it?
Hello I have model with content and additional fields. Example of content field: <div> <p>text</p> </div> Example of additional field: <p> <span> some text</span> <p> Also I render content on the page: detail_base.html {% include object.content_template with object_content=object.html_content %} entry_detail.html {{ block.super }} base_entry_detail.html {{ object_content|safe }} How can I paste code from additional field to code from content field. I need to get, for example: <div> <p>text</p> <p> <span> some text</span> <p> </div> I can to change only entry_detail.html and detail_base.html and code in the field. Thanx. -
What's the best way to get popular posts with Django?
What is here is more for discussion than code questions. I want to know how you guys do to get the popular posts. For example, once I did the following: I added a related template, and that template contained only one field, which is the post preview date, and every time a request was made, it was incremented, so I did some work to get the posts that only filter views from the last 7 days, and then I would rank the posts based on which one had the most related instances, ie, with the most views in the last week. But I don't know if this is the best way. How would you do that? -
Django, How to move from s3 to CDN?
Our media image files are stored under http://s3.ap-northeast-2.amazonaws.com/{bucket_nmae}/media/ I want to change the url to http://static.example.com/media/ and serve them through cloudflare / cloudfront if possible I've seen tutorials which describe the steps for using s3 as your endpoint or CDN as your endpoint. (https://ruddra.com/posts/aws-boto3-useful-functions/) But I haven't found one that describes the steps to move from s3 to CDN .