Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use functions from a custom module in Python Django shell
I have a python file called my_functions.py in which I have the following code: from core.models import Blog def news() b = Blog(name='New Blog', tagline='All the latest news.') b.save() My main app folder in django is called core and I have put my python file in there. In the shell I am able to do the import: from core import my_functions However I get an error AttributeError: module 'core.my_functions' has no attribute 'news' when I try to run the code my_functions.news(). How can I run the news function in the shell? -
Building openid provider and client in django, django session gets flushed
I'm building an open-id provider and client apps using django for the provider app I use django-oidc-provider and for the client app I use mozilla-django-oidc. I got the provider to work and verified it using this open-id debug tool however when I get redirected to the provider website I get automatically logged out and asked to login again before authorization process so that's issue number one. The Mozilla client library does not work, dappling through the source code I figured out that it's also a session related issue They create a random state value and add it to the session data in the authorization view request.session['oidc_state'] = state then check that state value returned in the callback view against the session value and that's where it fails if 'oidc_state' not in request.session: return self.login_failure() Printing the session objects, turned out to be different objects in memory. <django.contrib.sessions.backends.db.SessionStore object at 0x7fd34c8b22b0> <django.contrib.sessions.backends.db.SessionStore object at 0x7fd34c5b70f0> How can I fix this issue ? Is there a way to prevent that session behavior ? -
How to plot my data dinamically in FusionCharts, Read-Only DB
I'm new in django and FusionCharts, I'd like your help to plot my chart dynamically by django, The problem is: I'm loading my data by direct raw query (read-only db), not models. Is it possible to plot my chart by this way? It's occuring an error when I trie to call an instance of my data in DB. models.py def repairMonitoringSum(self): with connection.cursor()as cursor: import time, datetime date1 = datetime.date.fromordinal(datetime.date.today().toordinal() - 5).strftime('%Y%m%d') date = time.strftime('%Y%m%d') cursor.execute(""" --ALL select A.DEFT_CRE_YMD, SUM(A.DEFT_QTY) AS IN_QTY, B.DEFT_QTY AS OUT_QTY, SUM(A.DEFT_QTY) - B.DEFT_QTY as Pending from TBM_QM_PROC_DEFT A /*DEFECT OUTS*/ left join (select DEFT_CRE_YMD, sum (DEFT_QTY) AS DEFT_QTY from TBM_QM_PROC_DEFT where DEFT_CRE_YMD between %s and %s and PROC_CODE IN ('2660','2680') and PLANT_CODE NOT IN ('P81L','P81J') and FB_IN_NO IS NULL and DEFT_TYPE_DECI_CODE <> 'T' and DEFT_CAUSE_CODE is not null group by DEFT_CRE_YMD) B ON (A.DEFT_CRE_YMD = B.DEFT_CRE_YMD ) where A.DEFT_CRE_YMD between %s and %s and A.PROC_CODE IN ('2660','2680') and A.DEFT_TYPE_DECI_CODE <> 'T' and PLANT_CODE NOT IN ('P81L','P81J') and FB_IN_NO IS NULL group by A.DEFT_CRE_YMD, B.DEFT_QTY order by A.DEFT_CRE_YMD asc """, [date1, date,date1,date]) row = dictfetchall(cursor) cursor.close() return row Views.py def repairMonitoringCause(request): query10 = repairMonitoring(self='repairMonitoring') queryRepair = repairMonitoringSum(self='repairMonitoringSum') myDate = datetime.now() dataSource = {} dataSource['chart'] = { … -
Django create dynamic txt file and download with special file name
I'm trying create dynamic text file and download it when my method called.I used steps at here.But when i change the file name, file isn't downloaded,displayed on browser.What can i do?My code is below.Thanks for advice. def view_method(request): file_name = 'students.txt lines = [] data = Student.objects.all() for d in data: lines.append('{0};{1};{2}'.format(d.name,d.surname,d.amount)) response_content = '\n'.join(lines) response = HttpResponse(response_content, content_type="text/plain,charset=utf8") response['Content-Disposition'] = 'attachment; filename={0}'.format(file_name) return response -
django form: error message with aware datetime
I'm trying to get add a datetime to my form error message. Unfortunately it is rendered in UTC (my TIME_ZONE), but should be in the current timezone. def clean(self): # print(get_current_timezone()) > Europe/Berlin cleaned_data = super(LegForm, self).clean() departure_scheduled = cleaned_data.get('departure_scheduled') # check departure in journey if departure_scheduled < self.instance.journey.start: journey_start = localize(self.instance.journey.start) # print(self.instance.journey.start.tzinfo) > UTC self.add_error( 'departure_scheduled', _('Error Message (%(start)s).') % {'start': journey_start} ) print(get_current_timezone()) returns Europe/Berlin print(self.instance.journey.start.tzinfo) returns UTC The current timezone is activated. Is there any equal to localize() to convert the datetime object to the current timezone? -
Filters in django
I am new to Django actually I want to implement a function in my Django app. For example, when a user visit website "127.0.0.1:8000/shop/women" then I want to show all product from gender women by hard-coded I can define a view for it but when it gets to more completed queries like visit the webpage "https://www.bewakoof.com/top-wear-for-women/color-yellow--design-chest---printed--sizes-XS--sizes-M--sizes-XL?sort=high" The upper link generates clothes for women with size xs,m, and xl, and sorting is high to low. I can do the sorting part with the get function I am using class-based views. To list all template I use a listview. -
How can i Edit/Change the value of a model field from views.py
Good-day everyone. I want to know how i can change the value of a model-field through the number of items in a defined sessions list I have already made a profile model (which is OneToOne Field to the user model) with a 'level' field as shown below in my models.py; And in view.py, I have created a session called 'answer_list' which is a list that stores all correct answers provided by the user. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') level = models.CharField(max_length=1, choices=[('Newbie', 'N'), ('Regular', 'R'), ('Expert', 'E')], default='Newbie') views.py def index(request): if 'answer_list' in request.session: #answer_list has been created previously #request.session['answer_list'] = [] ok = request.session['answer_list'] print (ok) #just to check the content of 'answer_list' which is correct if len(ok) == 4: user=request.user user.profile.level = 'R' return render(request, 'index.html', {}) I want the value of the user.profile.level to change from 'Newbie' to 'Regular' once the number of items in the session 'answer_list' gets to 4. Please how can i go about it -
Django Heroku H10 error method=GET path="/favicon.ico"
I am fighting with this error while trying to get Django app to Heroku. Below some details: WSGI: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "folder.settings") application = get_wsgi_application() Procfile tried (below are options i used in separate files/deployment): web: python 4_Django/manage.py runserver 0.0.0.0:8000 web: gunicorn 4_Django/folder/wsgi.py 0.0.0.0:$PORT web: python 4_Django/manage.py runserver 0.0.0.0:$PORT LOGs: Procfile #1 logs: 2019-01-29T13:08:54.000000+00:00 app[api]: Build succeeded 2019-01-29T13:09:52.503085+00:00 heroku[web.1]: State changed from starting to crashed 2019-01-29T13:09:52.376451+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch 2019-01-29T13:09:52.376818+00:00 heroku[web.1]: Stopping process with SIGKILL 2019-01-29T13:09:52.480738+00:00 heroku[web.1]: Process exited with status 137 2019-01-29T13:09:55.746947+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=djangozadanie.herokuapp.com request_id=93f2ced0-c6f3-490e-9b78- ae3ed0e94641 fwd="89.78.65.77" dyno= connect= service= status=503 bytes= protocol=https 2019-01-29T13:09:55.947313+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=djangozadanie.herokuapp.com request_id=6361d948-d9e8-46de-b33a- 84db7b683095 fwd="89.78.65.77" dyno= connect= service= status=503 bytes= protocol=https Procfile #2 logs: State changed from crashed to starting 2019-01-29T12:56:56.428244+00:00 heroku[web.1]: Starting process with command `gunicorn 4_Django/coderslab/wsgi.py 0.0.0.0:22303` 2019-01-29T12:57:07.386160+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=djangozadanie.herokuapp.com request_id=aaa29775-d25d-4091-8b89- 485a3d294c16 fwd="89.78.65.77" dyno= connect= service= status=503 bytes= protocol=https 2019-01-29T12:57:07.491358+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=djangozadanie.herokuapp.com request_id=ed4a02de-4d57-466b-af03- 4085be10b6ce fwd="89.78.65.77" dyno= connect= service= status=503 bytes= protocol=https Procfile #3 logs: 2019-01-29T13:41:04.711401+00:00 app[web.1]: connection = Database.connect(**conn_params) 2019-01-29T13:41:04.711484+00:00 … -
Django template loop over filter result
I have a filter that returns a python list ['tlc', 'lbh', ...] I want to iterate over the results in a template such as {% for dc in settings_value "MULTIPLE_DATACENTERS_TEST_LIST" %} <option value="{{dc}}">{{dc}}</option> {% endfor %} but I get an error how can i get this to work, thanks? -
Python method argument named * (just the asterisk symbol, just one char long)
I was looking for something in Djangos source code when I came upon the definition of django.forms.fields.Field.__init__(): class Field: def __init__(self, *, required=True, ...): The method has more arguments, but I was surprised by the second argument, which is only the asterisk symbol. I had not seen this before. I could not find an explanation with a few quick google searches. It is not a valid argument name, meaning I cannot use the passed value in print(*). It is also different from the *args and **kwargs arguments (I know how to use these 2). Any explanations for this? Or any links where I can read about this usage? -
How to upload "mutiple images" using "postman in django rest api"
I'm creating a django rest api for uploading multiple images or files using FileField as a model field. I'm able to get two images from the postman application but after serialization, only one image is uploaded into the database. I'm trying in ubuntu, running PostgreSQL 9.5.14 and Django 2.1.5 permission_classes = (AllowAny,) parser_classes=((MultiPartParser,FormParser,FileUploadParser)) renderer_classes=((JSONRenderer,JSONParser,)) def post(self,request,*args,**kwargs): serializer = FinalSerializer(data=request.data) 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) Only one image is uploaded -
Cannot use self in method while working with Django
I am developing a application in Django, and Django passes request as first parameter and i cannot use self as first parameter as Django sets self to request object. I need self reference for the super class calls, how to overcome this situation? -
Django parse to the method in APIVIEW
This is my view.py and url.py class Jiratest(APIView): def get_incident(self, request, id): temp = JiraRequestHandler() open_tickets = temp.retrive_ticket_status() open_tickets = json.dumps(open_tickets) return HttpResponse(open_tickets, content_type='application/json') def get(self, request, id = None, format = None): temp = JiraRequestHandler() open_tickets = temp.retrieve_all_open_tickets() open_tickets = json.dumps(open_tickets) return HttpResponse(open_tickets, content_type='application/json') urlpatterns = [ path('jira/', views.Jiratest.as_view(), name = "jira"), re_path(r'^jira/(?P\w+)/$', views.Jiratest.as_view(), name='jira'), path('v1/', include(router.urls)), ] -
Django: sorting objects by distance
I have this model class Company(models.Model): name = models.CharField(max_length = 50) description = models.TextField() latitude = models.FloatField() longitude = models.FloatField() owner = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "company_owner") category = models.ForeignKey(Category, on_delete = models.CASCADE) def __str__(self): return self.name class Meta: verbose_name_plural = "Companies" def get_absolute_url(self): return reverse('category_list') #if want to redirect to its detail page then # return reverse('company_detail' ,kwargs = {'pk' : self.pk}) def get_distance(self): ip = get('https://api.ipify.org').text reader = geoip2.database.Reader('categories/GeoLite2-City.mmdb') response = reader.city(ip) current_lat = response.location.latitude current_lon = response.location.longitude comp_lat = self.latitude comp_lon = self.longitude R = 6373.0 lat1 = radians(current_lat) lon1 = radians(current_lon) lat2 = radians(comp_lat) lon2 = radians(comp_lon) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return(distance) I have got the distance between the user location and company location from get_distance() function. But how do I sort the distance in ascending order? Since the distance differs from various location of the user I can't store the distance in database. I want to print the objects sorted in ascending order by distance -
How to change default extracted data by Provider?
I've set up Facebook provide via django-allauth. I want to change default extracted data. By default it's ['email', 'username', 'first_name', 'last_name', 'name']. I also need user's birthday and his profile photo. I've tried to override DefaultSocialAccountAdapter, but I didn't find there useful methods. Also I tried to set: SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'FIELDS': [ 'id', 'email', 'name', 'birthday', 'locale', 'timezone', 'gender', ], } } But nothing happend. class SocialAccountAdapter(DefaultSocialAccountAdapter): def populate_user(self, request, sociallogin, data): print(data) super().populate_user(request, sociallogin, data) data still returns only 5 default fields -
django res framework http post method promblems
I have created an api in django rest_framework and i am testing it with postman GET ,DELETE methods have't any problem but in PUT ,POST methods it gives some errors. Here is my Book_list view in views.py : class Book_detail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): queryset = Book.objects.all() serializer_class = Bookserializer def get(self,*args,**kwargs): return self.retrieve(self,*args,**kwargs) def put(self,*args,**kwargs): return self.update(self,*args,**kwargs) def delete(self,*args,**kwargs): return self.destroy(self,*args,**kwargs) and here is my Bookserializer in serializers.py` : class Bookserializer(serializers.ModelSerializer): class Meta(): model = Book fields = ('id','name','publisher', 'author','isbn','genere') but when i want post following json with POSTMAN : { "id": 3, "name": "biganeh", "publisher": "ghoghnoos", "author": 2, "isbn": 4, "genere": "Horror" } this error occures : AttributeError at /api2/Books 'Book_list' object has no attribute 'data' what should i do? -
Source argument for list in serializer DRF
For example I have dict like this: { "first": { "second": "value" } } And serializer like that: class MySerializer(serializers.Serializer): value = serializers.CharField(source="first.second") I can fill the source argument to get my value by my path But what can I do with that example? { "first": [ { "second": "value" } ] } Is there any possibility in DRF to get list first element in source? I need something like that: class MySerializer(serializers.Serializer): value = serializers.CharField(source="first[0]second") -
Something wrong with videoplayer
Well i tried to made my own videoplayer(add my buttons scrollbar and etc) here main html file <!DOCTYPE html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> {% load staticfiles %} <link rel = "stylesheet" type = "text / CSS" href = "video-player.css"> </head> <body> <div id="video-player"> <video poster="image/127.jpg" width="1280" height="720" controls> <source src="{% static 'accounts/vid/1224.mp4' %}" type="video/mp4"> </video> <div id="progress-tree"> <div id="progress"></div> </div> <div id="button-tree"> <img id="play-button" src="{% static 'accounts/image/2712.png' %}" width="100" height="100"> <div id="time-factor"> 0:00 / 0:00 </div> <img id="backward-button" src="{% static 'accounts/image/backward.png' %}" width="100" height="100"> <div id="soundbar-tree"> <div id="soundbar" width="100" height="100"></div> </div> <img id="forward-button" src="{% static 'accounts/image/forward.png' %}" width="100" height="100"> </div> </div> </body> here is css file #video-player{ background-color: aquamarine; display: inline-block; } img{ background-color: Aqua; } #video-tree{ width: 640px; height: 640px; } video{ height: 100%; width: 100% } #progress-tree{ background-color: CadetBlue; } #progress{ height: 5px; width; 50%; background-color: Black; } #button-tree{ height: 50px; } #button-tree > * { display: inline-block; height: 50px; width: 50px; vertical-align: middle; } i put that css file where was html file please help me it like c/mysite/site/templates/site/html … -
Python 3 calling super class method
I am developing a application in Django. I am new to python and facing a issue while calling a super call method from a subclass. I am using Python 3. This is my sunclass : class TestClass(BaseController): def try_base(request: HttpRequest): return super().send_response(200, "", "", model1()) And this is my super class class BaseController: def convert_to_dict(obj): return obj.__dict__ def send_response(self, http_status, error_code, error_message, response_object): obj = BaseResponse(http_status, error_code, error_message, response_object) data = json.dumps(obj, default=convert_to_dict, indent=4) return HttpResponse(data) I don't know what exactly the problem. It always gives me an error super(type, obj): obj must be an instance or subtype of type Please help me in resolving this. -
Class Based View form not working from modal
I have the following Class Based View: class CreateCategory(LoginRequiredMixin, PassRequestUserMixin, PermissionRequiredMixin, generic.CreateView): permission_required = "register.can_create_category" model = ItemCategory form_class = ItemCategoryForm template_name = 'create_category_form.html' context_object_name = 'object_name' def get_success_url(self, **kwargs): if kwargs: return reverse_lazy('item_list', kwargs={'establishment_id': self.object.est.id}) return reverse_lazy('item_list', args=(self.object.est.id,)) and the following form definition for that form's template: <form action="{% url 'category_create' %}" method="POST"> the way I load this form, is via AJAX on another template, the script is as follows: var create_category_url = "{% url 'category_create' %}"; $("#activate_cat").click(function(){ $.get(create_category_url, function(){ console.log("Fetching data"); }) .done(function(data){ console.log("Data fetched succesfully :)"); $(".modal.category > .modal-content").html(data); }) .fail(function(xhr){ console.log("Error: ", xhr); }); $(".modal.category").addClass("is-active"); }); My problem is that when I submit this form, I get sent to the link of the form (category_create) instead of saving the object to the DB. I don't need to receive the data back via AJAX, so I'm ok with the page refreshing but that is not happening. Am I missing something or Class Based Views can't do this? -
Wagtail Admin Multi Class Model
So, I'm trying to add extra fields in from a separate class in my model into a wagtail_hook that extends ModelAdmin. You can see in my model that there are two classes, one is Report this is the main class, and the other is Sender. In the Wagtail admin I would like to add the Sender content to the report page. Is there a way to do this with wagtail? Here is my model.py class Report(models.Model): # Django will set the ID Pay_Period_Start_Date = models.DateTimeField('Pay Period Start Date') Pay_Period_End_Date = models.DateTimeField('Pay Period End Date') def __str__(self): return "Report for:" + str(self.Pay_Period_Start_Date) + " to " + str(self.Pay_Period_End_Date) class Sender(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE, default=None, null=True) Family_Name = models.CharField(('Family_Name'), max_length=30, blank=True) Given_Name = models.CharField(('Given_Name'), max_length=30, blank=True) Email_Address = models.CharField(('Email_Address'), max_length=30, blank=True) Telephone_Number = models.CharField(('Telephone_Number'), max_length=30, blank=True) here is my wagtail_hook.py from wagtail.contrib.modeladmin.options import ( ModelAdmin, modeladmin_register) from .models import Report, Sender class CHModelAdmin(ModelAdmin): model = Report menu_label = 'Clearing House' # ditch this to use verbose_name_plural from model menu_icon = 'form' # change as required menu_order = 300 # will put in 3rd place (000 being 1st, 100 2nd) add_to_settings_menu = False # or True to add your model to the … -
How to submit Django form in the background by clicking a button?
I am building an event registration website using django==2.1 . I have created views such that the admin can create events and the students can view these created events and click a button to participate in them. I have all the details of the logged in student. If a student clicks on the participate button, I want his roll and the event name (in whose detail page he clicked the button ) to be saved in the EventParticipants model given below: class EventParticipants(models.Model): event_name = models.ForeignKey(Event, on_delete=models.CASCADE) participant_roll = models.ForeignKey( Student, on_delete=models.CASCADE, to_field='roll') def get_absolute_url(self): return reverse('dashboard') The current implementation I have takes the student to another page where he has to click another button to confirm his registration and submit the form. How can I store the data in the model without redirecting the user? -
Is there any one who can help me to integrate the django-app with scrapy spider
I am new to Django, I want to run my scrappy spider form Django view. So anyone can help me with this, currently, I am getting "no active project found" error. Can anyone suggest me how can I integrate scrappy script with Django? -
how to fix redis connection error in django channels?
When starting the django server I get "Future exception was never retrieved future: aioredis.errors.ConnectionForcedCloseError" error and redis server shows connection closed by client. versions used are - django 2.1.5 channels 2.1.6 redis 2.2.0 aioredis 1.2 -
What kind of queries do I need to apply to retrieve data while excluding some according to what topic the question have?
I am receiving this Error: ImproperlyConfigured at /home/ QuizView is missing a QuerySet. Define QuizView.model, QuizView.queryset, or override QuizView.get_queryset(). And I don't know how to fix my queries in the way that I would like the results to be. I have been checking online and learning about queries but still confused about what kind of queries I need to try. This is the model.py from django.db import models from home.choices import * # Create your models here. class Topic(models.Model): topic_name = models.IntegerField( choices = question_topic_name_choices, default = 1) def __unicode(self): return u'%s' % self.topic_name class Image (models.Model): image_file = models.ImageField() def __unicode(self): return u'%s' % self.image_file class Question(models.Model): questions_type = models. IntegerField( choices = questions_type_choices, default = 1) question_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) question_description = models.TextField() question_answer = models.ForeignKey( 'Answer', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __unicode(self): return u'%s' % self.question_description class Answer(models.Model): answer_description = models.TextField() answer_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __unicode(self): return u'%s' % self.answer_description This is the forms.py from django import forms from betterforms.multiform import MultiModelForm from .models import Topic, Image, Question, Answer class TopicForm(forms.ModelForm): topic_name = forms.ModelMultipleChoiceField( queryset = Topic.objects.all(), widget = forms.SelectMultiple( attrs = {'class': ''} …