Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have deleted my conda environment by mistake, how do i revert it back
I have deleted the conda environment accidently by giving the following command conda remove --name myenv --all is there anyway that i could revert it back or is there any other method in recreating the same environment files without disrupting the existing project -
Difference Between __str__ and __unicode__ in django?
what is the difference between the str and unicode in django -
Combine ~Q and F in Django?
Query Balance.objects.filter(~Q(fax_date=F('paused_date'))) returns empty qs even though I do have objects that fit the condition "fax date field not equal to paused date". Is it possible to use ~Q and F together like that? -
Display matplotlib image in html - Django
I have a wordcloud generator that I have working in a Juypeter notebook (not so much the actual generating part- that is a library, but I built my own way to count and stem the words.). I would like to build a front end for it so you can paste the text in a text box, click submit and it displays the wordcloud. Basically what this chap has done here: https://www.jasondavies.com/wordcloud/ This is the code I have which generates an image of my wordcloud in my Juypeter notebook. from wordcloud import WordCloud from PIL import Image import matplotlib.pyplot as plt import nltk # sun only once -> nltk.download('punkt') #nltk.download('wordnet') -> only do this once from nltk.stem.porter import PorterStemmer from nltk.stem import WordNetLemmatizer ps = PorterStemmer() wnl = WordNetLemmatizer() def stem(string): stemstring = "" nltk_tokens = nltk.word_tokenize(string) for word in nltk_tokens: if word in dontstem: p = word elif word == 'printing': p = 'print' elif word == 'e-mailing': p = 'email' elif word == 'e-mails': p = 'email' elif word == 'e-mail': p = 'email' elif word == 'installation': p = 'install' #If the lemmatized word ends in a 'e' then lemmatize instead of stem as stem cuts the 'e'. … -
django pagination not working with django filter
I have a ListView page that is working well with pagination. I also have django filter added to that page for filtering. Problem is pagination is working well but with django filter it stops working. When the page load paginate_by not working. when the pagination is clicked next page not working. what am i doing wrong views.py class JobsListView(ListView, FilterView): # model = JobPost queryset = JobPost.objects.all() template_name = 'jobpost_list.html' paginate_by = 3 # page_kwargs = 'page' filterset_class = JobPostFilter def get_queryset(self, *args, **kwargs): if self.kwargs: return JobPost.objects.filter(position=self.kwargs['position']).order_by('-created_at') else: query = JobPost.objects.all().order_by('-created_at') return query def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['todays'] = date.today() context['filter'] = JobPostFilter(self.request.GET, queryset=self.get_queryset()) return context template {% extends 'base.html' %} {% load bootstrap4 %} {% load fontawesome %} {% block content %} {% if messages %} <div class="alert alert-success alert-dismissible fade show"> {% for m in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ m }}</li> <button type="button" class="close" data-dismiss="alert" aria- label="Close"> <span aria-hidden="true">&times;</span> </button> {% endfor %} </div> {% endif %} <div class="col-12"> <h1 class="text-center">Vacancies</h1> </div> <div class="row"> <div class="col-4"> <form method="get"> {% bootstrap_form filter.form %} {% buttons %} <button class="btn btn-primary" type="submit">Search {% fontawesome_icon 'search' %}</button> {% endbuttons %} </form> </div> … -
Django is not a registered namespace
I am very new to Django and I have created two apps in my project one is login & server_status. when I tried to include Login apps URL in server_status I am getting this following error 'login' is not a registered namespace server_status URL from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('dashboard', views.dashboard, name='dashboard'), path('server_status', views.server_status, name='server_status'), path('request_access', views.request_access, name='request_access'), ] login app URL from django.urls import path from . import views urlpatterns = [ path('login', views.index, name='index') ] project URL from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('server_status.urls')), path('', include('login.urls')), path('admin/', admin.site.urls), ] In server_status/templates/server_status/index.html <a href="{% url 'login:login' %}" class="button primary centered-s">Login</a> I know this is very simple one, but it makes me very complicated. -
How do we completed stop tasks in celery periodic_task?
Revoking a task on @periodic_task sends Discarding revoked tasks & Due task to workers. celery-workers-screenshot [2018-09-17 12:23:50,864: INFO/MainProcess] Received task: cimexapp.tasks.add[xxxxxxx] [2018-09-17 12:23:50,864: INFO/MainProcess] Discarding revoked task: cimexapp.tasks.add[xxxxxxx] [2018-09-17 12:24:00,865: INFO/Beat] Scheduler: Sending due task cimexapp.tasks.add (cimexapp.tasks.add) [2018-09-17 12:24:00,869: INFO/MainProcess] Received task: cimexapp.tasks.add[xxxxxxx] [2018-09-17 12:24:00,869: INFO/MainProcess] Discarding revoked task: cimexapp.tasks.add[xxxxxxx] [2018-09-17 12:24:10,865: INFO/Beat] Scheduler: Sending due task cimexapp.tasks.add (cimexapp.tasks.add) [2018-09-17 12:24:10,868: INFO/MainProcess] Received task: cimexapp.tasks.add[xxxxxxx] [2018-09-17 12:24:10,869: INFO/MainProcess] Discarding revoked task: cimexapp.tasks.add[xxxxxxx] tasks.py @periodic_task(run_every=timedelta(seconds=10),options={"task_id":"xxxxxxx"}) def add(): call(["ping","-c10","google.com"]) def stop(): x = revoke("xxxxxxx",terminate=True,signal="KILL") print(x) print('DONE') I had created task_id with a name so that i could be easy for me to kill it by calling id. How do i complete stop it from sending tasks ?,I don't want to kill all workers with pkill -9 -f 'celery worker' celery -A PROJECTNAME control shutdown I just want to stop the tasks/workers for add() function. -
Django How to set cookies and sessions ?
I am Newbie in Django and i dont know about cookies and session please tell me how to use i had read the about cookies that its browser side client side. For my project i am having a problem i am sending mail with the driver id in it and after every page i am posting my driver id with it in forms . So someone suggest me use as cookies . So please tell me here is my some of the code of view and templates . please help me if any thing i didnt clear in my question please ask me because i am new in Web development. Views.py @csrf_protect def rentacar_list(request, page_number=1): print(Template) menu_config_list = MenuItemRentacarList.objects.all()[0] menu_config = MenuItemRentacarList.objects.get(id=menu_config_list.id) all_cars = Car.objects.all().order_by('-id') if menu_config.menu_item_rentacar_list_show_unavailable == 0: all_cars = all_cars.exclude(car_available=0) else: all_cars = all_cars cars_page = Paginator(all_cars, menu_config.menu_item_rentacar_list_pagination) args['cars'] = cars_page.page(page_number) template = Template.objects.get(template_default__exact=1) args['main_menu'] = MenuMenu.objects.get(id__exact=template.template_main_menu_id) args['menu_items'] = MenuItem.objects.filter( menu_item_menu=args['main_menu'], menu_item_published=1, ) template_page = template.template_alias + str("/rentacar/rentacar_cars_list.html") args['current_menu_item'] = menu_config.menu_item_rentacar_list_menu_item all_modules = Module.objects.filter( module_show_option__exact='all', module_published=1 ) selected_modules = Module.objects.filter( module_show_option__exact='selected', module_published=1, module_menu_item=args['current_menu_item'] ) excluded_modules = Module.objects.filter( module_show_option__exact='except', module_published=1, ).exclude( module_menu_item=args['current_menu_item'] ) args['modules'] = list(chain(all_modules, selected_modules, excluded_modules)) return render(request, template_page, args) @csrf_protect def rentacar_car(request, car_id, driver_id): menu_config_list = … -
Validating url in POST parameters in Django
I am trying to validate that the parameters in the POST request sent are valid URLs. This is my views.py views.py def post(self, request): if url_validator(request) == 400: return Jsonresponse(status=400) This is my utils.py. This file will contain all general methods and classes. def url_validator(request, ext): for key, value in request.data.items(): value = request.data[key] try: URLValidator(value) except ValidationError: return 400 When I call the function url_validator from views, it executes but doesn't return the exception when either of the request parameters doesn't contain URLs. For example, if I pass a parameter param1: "some string", it doesn't go through the ValidationError path. How do I go about getting the correct return from the function? -
Why is django-rest-frameworks reuqest.data sometimes immutable?
In my resful view I mutate my request.data dictionary. Occasionally I receive an error not caught by my tests: This QueryDict instance is immutable For a line e.g. like this: request.data['some_attr'] = float(something) request.data seems to be a normal dict in my tests. Why is it sometimes a QueryDict? How should this be dealt with? Should request.data not be mutated in general? How should you use the ModelSerializer class, when you need to populate some fields yourself? -
Clear all webapp session on server restart
I am facing problem with below scenario, where I need to clear all sessions on my django app with conditions applied. Cannot use cron Webapp's javascript is requesting server api per minute for health check wether server is active or not Upon sever status off webapp is automatically logging out and clearing the current user's session. Problem is I want to clear all users session There can be situation like only one user is logged in, others session are active but not on web browser( means they have recently closed the tab) Other situation is only one session is there but its idle ( closed tab) Now how can I thrash all sessions Two things I came up with is Read Last PID and store it in db, whenever any user hits url, it will cross check the PID and clear all sessions if PID mismatch occurs ( Not sure as PID can be same after restart) Server restart event should be listened and kill all sessions ( Not sure how to implement, SIGHUP kind of events) Project Architecture: Linux Python2.7 (Django) Nginx Any other suggestions please. -
how to insert a value from form in django arraymodelfield
this is my model class Product(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to='', blank=True) image1 =models.ArrayModelField( model_container=Images1, model_form_class=Images1Form ) this is my HTML code while submit it doesn't valid <div class="row"> <div class="col-sm-6"> <fieldset class="form-group"> <div class="form-group"> <label for="id_item_number-0-spec_id" class=" control-label" >Item Number 1(Required)</label> <input class="form-control" type="file" name="imag-0-small" step="any" placeholder="Spec ID"/> </div> </fieldset> </div> <div class="col-sm-6"> <fieldset class="form-group"> <div class="form-group"> <label for="id_item_number-1-spec_id" class=" control-label" >Item Number 2(Optional)</label> <input class="form-control" type="file" name="imag-1-small" step="any" placeholder="Spec ID"/> </div> <input type="hidden" name="imag-TOTAL_FORMS" value="1" id="id_imag-TOTAL_FORMS" /><input type="hidden" name="imag-INITIAL_FORMS" value="0" id="id_imag-INITIAL_FORMS" /><input type="hidden" name="imag-MIN_NUM_FORMS" value="0" id="imag-MIN_NUM_FORMS" /><input type="hidden" name="imag-MAX_NUM_FORMS" value="1000" id="id_imag-MAX_NUM_FORMS" /> </fieldset> </div> </div> Help me any suggestion when I am using array field it shows a value must be a list and I am using if condition to valid to save and else to return a field is missing -
Setting value of a hidden field in Django form
I'm using django-registration to manage my registrations. I'm trying to force my username and email to be the same in a Django application and I am trying to do it via the registration form as follows: class NoUsernameRegistrationForm(RegistrationForm): """ Form for registering a new user account. Requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual saving of collected user data is delegated to the active registration backend. """ username = forms.CharField( widget=forms.EmailInput(attrs=dict(attrs_dict, maxlength=75)), label=_("Email address")) password1 = forms.CharField( widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password")) password2 = forms.CharField( widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_("Password (again)")) email = forms.EmailField( widget=forms.HiddenInput(), required = False) def clean(self): """ Verify that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError(_("The two password fields didn't match.")) """ Validate that the email address is not already in use. """ try: user = User.objects.get(username__iexact=self.cleaned_data['username']) raise forms.ValidationError(_("A user with that email address already exists.")) except User.DoesNotExist: self.cleaned_data['email'] = self.cleaned_data['username'] self.cleaned_data['username'] … -
Django: ForeignKey linking 2 tables
In these lines of code, under the Bugs table, there's a line of code that reads Assigned_to = models.ForeignKey(User, on_delete=models.CASCADE) There are a total of 2 tables, the first one is the Project table, and the 2nd one is the Bugs table. How do I edit this line of code and make it in such a way that only the people who's names are mentioned in the Project table appears? I've tried this but how do I write all the related names and make sure all the names mentioned in the first table are shown on this table? Assigned_to = models.ForeignKey(Project, on_delete=models.CASCADE, related_name= ' ' | ' ' | ' ' ) Clearly, using '' | '' does not work. All suggestions will be appreciated. Also, for some reason, the lines of code I wrote for inline are not being displayed.` Suggestions for this issue will also be appreciated. Thanks in advance! from django.db import models # Create your models here. from django.contrib.auth.models import User, Group from django.db import models from django.core.mail import EmailMessage from django.contrib import admin # Create your models here. class Project(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( … -
Django model reference to self class
I have a model, like this (simplified): class Task(): name = models.CharField(max_length=256) parent = TreeForeignKey('self', on_delete=models.CASCADE, related_name='children') project = models.ForeignKey('prosystem.Project', related_name='tasks', on_delete=models.CASCADE) @property def current_budget(self): # this does not work now sumz = self.cls.objects.filter(project = self.project).aggregate(Sum('budget')) return sumz The question is - how can I filter all instances of Task model from its own current_budget property? I know there might be some meta.class reference, but can't find info about that. Thank you for any advices. -
Question about Django tutorial offical part3 html code
I have a question about the js code when I'am learning on Django official tutorial part3. In the "Raising a 404 error" section, the offical code use following code to display the "question_text" in object called "question": {{ quesion }} I don't understand why this code could work. The "question" is not a string but a object. It should be "question.question_text" . views.py def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('datepublished') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now()-datetime.timedelta(days=1) Besides, It works when I use the code {{ question.question_text }} So, I want to know why those two can have same output. -
Django-filters does not work with the Viewset
I have been trying to use django-filters but the objects are not getting filtered. Also, the permission is not working for the partial_update views I have a Viewset which has the basic actions like - list(), retrieve(), destroy(), partial_update() and few other actions, and trying to apply filter for the same. After some research I found that since I am creating the queryset via filters I will have to override the get_queryset() method. However, that also doesn't seem to be working. Does the filter works only with ModelViewSet or ListApiView? ViewSet - class PostViewSet(viewsets.ViewSet): """ The Endpoint to list, retrieve, create and delete Posts. """ filter_backends = (DjangoFilterBackend, ) # filterset_class = PostFilter filter_fields = ('pet_age', 'pet_gender', 'breed') def get_permissions(self): if self.action == 'partial_update' or self.action == 'update': permission_classes = [IsPostAuthor, ] elif self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated, ] else: permission_classes = [AllowAny, ] return[permission() for permission in permission_classes] def get_queryset(self): return Post.objects.active() # This is implemented via custom Manager def list(self, request, *args, **kwargs): """ Method for Post listing. It can be accessed by anyone. """ serializer = PostListSerializer(self.get_queryset(), many=True, context={"request": request}) return Response(serializer.data) # REST CODE TRUNCATED Permission - class IsPostAuthor(permissions.BasePermission): """ Object-level … -
Django form is not saving image file
In this webapp I have a question model and a question diagram model. Whenever the user uploads an image, it is supposed to be saved in media/question_image folder. It is working fine if I upload from the admin panel, but when I upload the image from webpage it is not getting saved. Fact is, the post request is working and I don't get any kind of error. The image is not getting saved at its desired place. Here is all my codes: model.py class QuestionDiagram(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='questionDiagrams') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) question_diagram = models.ImageField(upload_to='question_diagram/') question_diagram_text = models.CharField(max_length = 48) date = models.DateTimeField(auto_now_add=True, blank=True, null=True) forms.py class QuestionDiagramForm(forms.ModelForm): question_diagram = forms.CharField(widget = forms.FileInput(attrs={'class':'questionDiagram-questionDiagram'})) question_diagram_text = forms.CharField(widget = forms.Textarea(attrs={'class':'questionDiagram-questionDiagramText', 'placeholder':'Describe', 'maxlength':'48'})) class Meta: model = QuestionDiagram fields = ['question_diagram', 'question_diagram_text'] settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') in project urls.py (added mediaroot and mediaurl) ...... if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class QuestionDiagramView(View): form_class = QuestionDiagramForm template_name = 'mechinpy/question_diagram.html' def get(self, request, slug): form = self.form_class(None) return render(request, self.template_name, {'form':form}) def post(self, request, slug): question = get_object_or_404(Question, slug=slug) form = self.form_class(request.POST, request.FILES) if form.is_valid(): questiondiagram = form.save(commit=False) questiondiagram.user = self.request.user questiondiagram.question = question questiondiagram.save() return … -
How should I store shopping cart items in django session?
I know how to store cart objects in db using cart model but i dont understand how to save do such using session? how can i save clicked object in a session? -
Clean way to create or list related objects in API view
I've got the following view to create(list) comments that are related to specific Event. I'm trying to figure is there any cleaner way to create/fetch instances without overriding get_queryset() and get_object() methods as I do. The urls looks like this: /events/v1/events/{id}/comments/ So I've got only event id and each user can get comments for this event or user can create comment for this Event. class EventCommentsAPIView(generics.ListCreateAPIView): serializer_class = CommentSerializer pagination_class = BaseResultsSetPagination filter_class = TimeStampedFilter def __init__(self): super().__init__() self.content_type = self.get_contenttype() def get_queryset(self): return Comment.objects.filter( content_type=self.content_type, reply_on=None, object_id=self.get_object().id).prefetch_related( 'replies') def get_object(self): queryset = Event.objects.filter(id=self.kwargs.get('pk')) return get_object_or_404(queryset) @staticmethod def get_contenttype(): # TODO ADD Caching return ContentType.objects.get(model='event') def get_serializer_context(self): """ Extra context provided to the serializer class. """ return {'request': self.request, 'format': self.format_kwarg, 'view': self, 'content_type': self.content_type, 'pk': self.kwargs.get('pk')} And here is my serializer if it's necessary: class CommentSerializer(serializers.ModelSerializer, CreatorMixin): replies = ShortCommentSerializer(many=True, read_only=True) reply_on = serializers.PrimaryKeyRelatedField( queryset=Comment.objects.all(), write_only=True, allow_null=True, required=False ) class Meta: model = Comment fields = ('id', 'text', 'object_id', 'creator', 'replies', 'reply_on', 'created') extra_kwargs = { 'text': {'required': True}, 'object_id': {'read_only': True} } def create(self, validated_data): validated_data.update( { 'content_type': self.context['content_type'], 'object_id': self.context['pk'], 'creator': self.context['request'].user } ) return Comment.objects.create(**validated_data) -
Is there a way to make a db sync tool easily with frameworks such as Rails, Django or Laravel?
There are many dbs in some environment: staging qa production etc In order to find different data between every db, sometimes we should compare the records from them. All the db name, table name, table schema are the same but only not the data. Now want to make a feature that can get different records and can sync the different records from production to staging. Rails, Django or Laravel are well support database model, so if they can realize it will be very helpful. As I know until now, maybe Rails can't. But not sure Django or Laravel now. I found Django can operate multiple databases, so think maybe it has some good features to do something near it. -
Customizing Model Serializer for many to many fields in Django
I need some guidance to implement the serializers for models containing many to many fields in a generalized way. Suppose I have the following (hugely simplified) models: class Operative(models.Model): name = models.CharField(max_length=256, blank=False) email = models.EmailField(unique=True, null=True) desiganation = models.PositiveSmallIntegerField(default=0, choices=((0, 'Operative'), (1, 'Manager'), (2, 'Owner'))) class Task(models.Model): title = models.CharField(max_length=256, blank=False) manager = models.ForeignKey(User, null=True,on_delete=models.SET_NULL) operatives = models.ManyToManyField(Operative, blank=True) deadline = models.DateTimeField(null=True, blank=True) Now if I have a serializer like this: class TaskSerializer(ModelSerializer): class Meta: model = Task fields = ('id', 'title', 'manager', 'operatives', 'deadline') read_only_fields = ('id',) What would be the best approach to handle the update requests containing integer ids for manager and operatives? The update API will receive POST requests containing json data like this: { "id": 1002, "title": "Task1", "deadline": "2018-09-15T15:53:00+05:00", "manager": 55, "operatives": [102, 110, 324] } I would like to implement the customized logic for foreign keys and many to many fields inside the serializer. Currently, I am using some helper methods in the View to get/set the ids for operatives and manager and it seems a bit clumsy. -
override split method python
i have one class called DatabaseLogHandler and i want add functionally of str.split here is my class import logging import traceback class DatabaseLogHandler(logging.Handler): def emit(self, record): from .models import ErrorLog trace = None if record.exc_info: trace = traceback.format_exc() kwargs = { 'logger_name': record.name, 'level': record.levelno, 'msg': record.getMessage(), 'trace': trace } ErrorLog.objects.create(**kwargs) this is my ErrorLog class import logging from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ LOG_LEVELS = ( (logging.NOTSET, _('NotSet')), (logging.INFO, _('Info')), (logging.WARNING, _('Warning')), (logging.DEBUG, _('Debug')), (logging.ERROR, _('Error')), (logging.FATAL, _('Fatal')), ) class ErrorLog(models.Model): logger_name = models.CharField(max_length=100) level = models.PositiveSmallIntegerField(choices=LOG_LEVELS, default=logging.ERROR, db_index=True) msg = models.TextField() trace = models.TextField(blank=True, null=True) create_datetime = models.DateTimeField(auto_now_add=True) def __str__(self): return self.msg class Meta: ordering = ('-create_datetime',) app_label = 'django_db_logger' -
PDF generation fails in latex with certain Chinese characters
An error encountered while generating PDF if there is certain Chinese character. For example: 河北省涿州市松 Although I'm using CJK package in my class \RequirePackage{CJK} Following error shows in the log file: Unicode character 27827 = U+6CB3: Contained in range 'CJK Ideograph' Character available with following options: cjkbg5, cjkgb, cjkjis. ! ==> Fatal error occurred, no output PDF file produced! -
I want to get a string from MySQL db and modify it and save it back to the DB
The problem is the string in the db has '\' in it and i want to read this string , modify it and save it back to the DB. SQL automatically removes any escape characters . so \ from the string is removed and saved in the DB . eg: config = '{"Settings":"{\"On\"}"}' sql= "INSERT INTO file (configuration, id) VALUES('%s', '%s')" % (config, cursor.execute(sql) and in the db {"Settings":"{"On"}"} is saved.