Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to render html form template in class based views in django
I have an HTML page with a link to redirect to another HTML template which has a form. I have used the class based view in rendering it. But it simply does not load. My views.py look something like : def startup(request): return render(request, 'main/startup.html') class AddStartup(CreateView): model = Startup template_name = 'startup_form.html' fields = ['startup_name', 'startup_product', 'startup_date', 'startup_sector', 'startup_team_size', 'startup_desc', 'startup_team_condition', 'startup_team'] urls.py # I have posted only the relevant code url(r'startup/$', views.startup, name = 'startup'), url(r'startup/add-startup/$', views.AddStartup.as_view(), name = 'add-startup'), My HTML page which has a link to navigate to the field is below {% extends "main/base.html" %} {%block content%} pass<br> <a href = "{%url "main:add-startup"%}" target="_parent" method = "post"> Add Startup </a> {%endblock%} I am a bit confused in Class based views so that is why I choose to mix them. Help would be appriciated -
Getting a error in django. Please help me resolve it
NoReverseMatch at /music/ Reverse for 'audios' with arguments '(u'all',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: GET Request URL: http://127.0.0.1:8000/music/ Django Version: 1.9.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'audios' with arguments '(u'all',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Exception Location: C:\Python27\lib\site-packages\django\core\urlresolvers.py in _reverse_with_prefix, line 508 Python Executable: C:\Python27\python.exe Python Version: 2.7.14 Python Path: ['C:\Users\dell\Desktop\test kar ra hu', 'C:\Windows\SYSTEM32\python27.zip', 'C:\Python27\DLLs', 'C:\Python27\lib', 'C:\Python27\lib\plat-win', 'C:\Python27\lib\lib-tk', 'C:\Python27', 'C:\Python27\lib\site-packages'] Server time: Tue, 20 Mar 2018 09:43:30 +0530 Error during template rendering In template C:\Users\dell\Desktop\test kar ra hu\music\templates\music\index.html, error at line 38 38 {% cycle '' '' '' '' '' '' %} -
Django, cannot receive paypal ipn notification
i am trying to integrate django app with paypal payment gateway, but i am not getting my signals fired, as well as i am not able to receive paypal ipn notifications, models.py class Pr_request(models.Model): number = models.CharField(max_length=20) subject = models.TextField(max_length=500) date_posted = models.DateTimeField(auto_now_add=True) class Purchase(models.Model): resourse = models.ForeignKey(Pr_request, related_name='purchase') purchaser = models.ForeignKey(User) purchased_at = models.DateTimeField(auto_now_add=True) views.py ti create payment_dic def payment_proccess(request, id): pr = get_object_or_404(Pr_request, id=id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '%.2f' % pr.fees.quantize(Decimal('.01')), 'item_name': 'purchase Req {}'.format(pr.number), 'invoice': '2', 'currency_code': 'USD', 'notifiy_url' : 'http://da...879.ngrok.io',#also i tried localhost 'return_url' : 'http://{}{}'.format(host, reverse('payment:done')), 'cancel_return': 'http://{}{}'.format(host, reverse('payment:canceled')), } form = PayPalPaymentsForm(initial=paypal_dict) print (" iam pyament process function") return render(request, 'payment/process.html', {'pr':pr, 'form':form}) signals.py def payment_notification(request, sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: print ("successful payment was done Lol") pr = get_object_or_404(Pr_request, id=ipn_obj.invoice) pur = Purchase.objects.get_or_create(resourse=pr, purchaser=request.user, tx='some text') pur.save() #mark the pr as paid else: print (" not able to pay") # payment was successful valid_ipn_received.connect(payment_notification) print ("signal is fired") init.py default_app_config = 'payment.apps.PaymentConfig' note that i am getting my signals fired whenever i reload my local server, so any idea about my mistake,thanks .. -
Django object copy issues
I've got a DRF API that I'm working on at the moment, using Django 2.0.2. https://docs.djangoproject.com/en/2.0/topics/db/queries/#copying-model-instances According to the docs, the Django way to copy an object is the following: blog = Blog(name='My blog', tagline='Blogging is easy') blog.save() # blog.pk == 1 blog.pk = None blog.save() # blog.pk == 2 However, my experience with this is not the same. I am using MySQL 5.6 with unmanaged tables, but apart from that just a generic basic setup. thing = Thing.objects.get(pk=100) thing.pk # thing.pk == 100 thing.pk = None thing.save # thing.pk == None The new record is inserted into the database as expected, but the object I'm working with is not retrieving the new primary key for some reason. <Thing: Thing object (None)> It still contains all the previous data of the initial instance that I pulled from the database but no pk/id. The same happens when overriding the explicit pk (id) at the same time, or on its own without overriding thing.pk Has anyone experienced this? I can't for the life of me figure it out. -
How can I setup celery to put tasks in a queue that will scale?
I run a video hosting site. Users upload videos and those videos are then processed. The video processing tasks are currently run as background tasks in celery. How can I make it so that when a user needs a video processed when my celery worker(s) are already processing the max number of tasks (also, how can I figure out how much work a worker can do? trial and error?) the user's task is put in a queue and I can display a message "You are 5th in the queue for your video to be processed" ? -
getting an error: ModuleNotFoundError: No module named 'bootstrap3'
I followed https://pypi.python.org/pypi/django-bootstrap3 regarding a bootstrap support in my Django projects. I installed bootstrap in my virtual environment pip install django-bootstrap3 My settings.py INSTALLED_APPS = [ 'django.contrib.staticfiles', 'bootstrap3', ] Error: ModuleNotFoundError: No module named 'bootstrap3' -
I want to use http://xxxxxx/{id} and http://xxxxxx/{md5} together
I want to use http://xxxxxx/{id} and http://xxxxxx/{md5} I think it work like this class ItemViewSEt(viewsets.ModelVieSet): queryset = item.objects.all() serializer_class = ItemSerializer permission_classes = [AllowAny] lookup_field = 'id' @detail_route(methods=['GET'], permission_classes=[AllowAny]) def test(self, request): self.lookup_field = 'md5' but it doesn't work with following error check() got an unexpected keyword argument 'pk' how can i solve that problem? Do I seperate viewset? or make method view and include url? -
Django filter multiple foreign key relationships
I want to list all of a teacher's students that have commented on each genre of blog posts. Below is my best effort, but I duplicate student names for each genre, so if they comment on multiple scary blog posts, their names are listed multiple times. How can I list each student name once next to each genre on the teacher profile page? Models.py class Genre(models.Model): name = models.CharField(max_length=200, unique=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile') username = models.CharField(max_length=128, unique=True) teacher = models.ForeignKey('Teacher', blank=True, null=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='teacher_profile') name = models.CharField(max_length=128, blank=True, unique=True) class BlogPost(models.Model): genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True) class Comment(models.Model): blogpost = models.ForeignKey(BlogPost, related_name='comments', on_delete = models.CASCADE, null=True) message = CharField(max_length=1000, blank=True) commenter = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE, null=True) Views.py def teacher_profile(request): student_list = Student.objects.filter(teacher__user=request.user) student_blogpost_list = BlogPost.objects.filter(comments__commenter__student_profile__teacher__user=request.user).distinct() student_genre_list = Genre.objects.filter(blogpost__in=student_blogpost_list).distinct() return render( request, 'myapp/teacher_profile.html', context= {'student_list':student_list, 'student_blogpost_list':student_blogpost_list, 'student_genre_list':student_genre_list}, ) teacher_profile.html {% if student_genre_list %} <h4>Genres</h4> {% for genre in student_genre_list %} Genre: {{ genre.name }} - Students: {% for blogpost in genre.blogpost_set.all %} {% for comment in blogpost.comments.all %} {% if comment.commenter.student_profile in student_list %} {{ comment.commenter.student_profile.username }} {% endif %} {% endfor %} {% endfor %} <br> {% endfor %} {% endif … -
can't get test to pass on view that takes a POST form with a manytomany field
My github files are located here https://github.com/cbaldwin20/project_9/blob/master/menu/tests.py I cannot get this test to pass (note that 'Menu' already has one object in its database, so I am trying to add another to make it 2. Thanks for any advice. def test_create_new_menu_view(self): self.client.post('/menu/new', data={ 'expiration_date': timezone.now() + timezone.timedelta(days=2), 'season': 'Spring 2018', 'created_date': timezone.now(), 'items': ['1'] }) self.assertEqual(Menu.objects.count(), 2) on this view def create_new_menu(request): if request.method == "POST": form = MenuForm(request.POST) if form.is_valid(): menu = form.save() return redirect('mysite:menu_detail', pk=menu.pk) form = MenuForm() return render(request, 'menu/new_menu.html', {'form': form}) using this form class MenuForm(forms.ModelForm): expiration_date = forms.DateField(widget=forms.SelectDateWidget()) items = forms.ModelMultipleChoiceField(queryset=Item.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = Menu exclude = ('created_date',) and this model that the form uses class Menu(models.Model): season = models.CharField(max_length=20) items = models.ManyToManyField('Item', related_name='items') created_date = models.DateTimeField( default=timezone.now) expiration_date = models.DateTimeField( blank=True, null=True) -
Django Model with (single) ForeignKey to Model A *OR* Model B
I have two models (A and B) with identical fields - they differ in that one *A) is a unmanaged model pointing to a table in a legacy DB and and the other (B) is typical Django model - the PK of the unmanaged legacy table (id) is multiplied by -1 to ensure that and records in the table generated by the typical Django Model will not conflict. Realizing that true RI is not possible due to split and esp the unmanaged table, is there a good way to 'fake' a ForeignKey in a third model that references either A OR B for the purposed of the Admin Pages functionality? Thanks - this Django stuff is getting fun.... -
Issue setting up django-crontab
I am having some issues setting up django-crontab in my django project. I have followed the instructions given on the official documentation :- https://pypi.python.org/pypi/django-crontab I have defined my cron.py under an app named ciscoaci. So its location is project/ciscoaci(which is the app)/cron.py. Inside cron.py, is a function named sshpostGetMACIP_scheduler(). I have defined 'django_crontab' under my settings.py in INSTALLED_APPS. CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'ciscoaci.cron.sshpostGetMACIP_scheduler', '>> /axphome/sganguly/netadc/ciscoaci/tmp/scheduled_job.log'), ] Nothing shows up in my logs. I have also tried changing /axphome/sganguly/netadc/ciscoaci/tmp/scheduled_job.log to ciscoaci/tmp/scheduled_job.log and it doesn't work. Also when I do crontab -l, the cron shows up. */1 * * * * /root/.venvs/netadc/bin/python /home/sganguly/netadc/manage.py crontab run 4a2a96ea204eb26917961a9946493f0d >> /axphome/sganguly/netadc/ciscoaci/tmp/scheduled_job.log 2>&1 # django-cronjobs for netadc But nothing shows up in my logs. Any help would be appreciated. I do not want to use celery at this point as this is used for a temporary feature in my project. -
How to get CSRF when Android calls API of Django
I'm going to use Django API for Android development use,But I met some of the following questions. 1.Android is just giving me post form data through a URL, how can Android get csrftoken? 2.If post data is modified, for example, we originally need to delete the a information, but a is changed to B, which will cause the background to delete B information, and how to prevent this happening? 3.Where is the csrftoken of Django being stored, I looked at my database, but I didn't find it? I'm just beginning to learn Django, so my question may look ridiculous, but I really want someone to help me. -
accessn form field of a class A in another class B
I have two classes- A and B in my forms.py using predefined models. Cannot change the models that A and B are referring to, but I need to modify the form B. class A(forms.ModelForm): file = forms.FileField(label='Select a file') class Meta: model = Files fields = ('file',) class B(forms.ModelForm): helper = FormHelper() helper.form_tag = False helper.form_class = 'form-horizontal' helper.label_class = 'col-lg-4' helper.field_class = 'col-lg-8' helper.layout = Layout( Div( Div( 'stuff', ), Div( 'stuff', ), css_class='row'), ) class Meta: model = Cont fields = ('stuff',) I want the 'file' field of class A to be there on the form that will be rendered using class B. Any suggestions how I might be able to achieve this? -
Django Model inheritance and DRY templating
I'm building a simple gear site in Django, similar to a shop site but very much simplified. I'd like to have have a default /gear url and then be able to load the subclassed items into things like /gear/tents and /gear/sleeping-bags. I'm just not sure that I've set this up correctly because I'm getting some unwanted url behavior. Whether I'm on /gear/tents or /gear/sleeping-bags, the template tag {% url 'gear:detail' gear.slug %} uses the final urlpattern named 'detail'. I'd like to know if there's a way to reuse one template file for this but pass in what model I'm looking for. Basically, I know something is wrong in what I'm doing, but I'm not sure how to do this right. Here's what I'm working with so far: models.py: class Gear(models.Model): name = models.CharField(max_length=200) ... class SleepingBag(Gear): pass class Tent(Gear): pass views.py: class TentList(ListView): context_object_name = 'list' model = Tent template_name="gear/list.html" class TentDetail(DetailView): context_object_name="gear" template_name="gear/detail.html" queryset = Tent.objects.all() class SleepingBagList(ListView): context_object_name = 'list' model = SleepingBag template_name="gear/list.html" class SleepingBagDetail(DetailView): context_object_name="gear" template_name="gear/detail.html" queryset = SleepingBag.objects.all() urls.py: urlpatterns = [ path('tents/', TentList.as_view()), path('tents/<slug:slug>/', TentDetail.as_view(), name="detail"), path('sleeping-bags/', SleepingBagList.as_view()), path('sleeping-bags/<slug:slug>/', SleepingBagDetail.as_view(), name="detail"), ] templates/gear.list.html: {% for gear in list %} <a href="{% url 'gear:detail' gear.slug … -
Django cache arbitrary query results
In a certain Django view, I query a large amount of complex data. I make no changes to any data in this view. If the query were fully optimized, I suspect it would take less 300ms. As a result, it would be convenient if Django simply cached all database queries to reduce duplication. I can cache intermediate results by hand, but due to the complexity of the project this would be painstaking and require significant restructuring. Is there simply a way—like a function decorator—to tell Django to cache all database queries during a specific context? -
No Reverse Match When Resetting Password in Django
I'm trying to implement the built in Django authentication views in my site to help with the password resets for users. I've set the root urls to include the provided URLconf in django.contrib.auth.urls like so: path('', include('django.contrib.auth.urls')) I've set all the templates in a registration folder in my templates directory. So, if i go to /password_reset, i get the correct page to change my password If i enter an email, i DO receive the change password email. If i click the link in the email, i get to the reset/***/set-password page But if i try to enter a new password it submits and goes to reset/done but i get following error: NoReverseMatch at /reset/done/ Reverse for 'sign_in' not found. 'sign_in' is not a valid view function or pattern name. I do also have an 'accounts' app in my project which includes a custom 'sign_in' url. Could this be the issue? Is this overriding some sort of prebuilt sign_in page from Django? app_name = "accounts" urlpatterns = [ url(r'sign_in/$', views.sign_in, name='sign_in'), url(r'sign_up/$', views.sign_up, name='sign_up'), url(r'sign_out/$', views.sign_out, name='sign_out'), url(r'profile/$', views.view_profile, name='profile'), url(r'profile/edit/$', views.edit_profile, name='edit_profile'), url(r'profile/change_password/$', views.change_password, name='change_password'), url(r'favorites/$', views.view_favorites, name='favorites'), url(r'^subscribe/', views.subscribe, name = "subscribe"), -
How to get/read the current object list in graphene-django pagination?
i want to get the objects ids of the current objects being sent through graphql page ? i want to make modifications before sending the objects ? pseudocode class objectQuery(django object graphene): meta: model = objectModel serializer = objectSerializer class Query(Node): list = connectionfield(objectQuery) def some kind of resolver or custom connection(self, *args, **kwargs): currentObjectlistOn3rdPage.update(field=somethingnew) -
Add custom button to link to another model DjangoAdmin
I would like to add custom button next to the buttons save or save and continue in DjangoAdmin. When I click on it I would like to show another registered model in django admin. In submit_line.html I have add my custom button and then I display it in my modelAdmin definition in changeform_view. How could I make link to another model? How could I override function in submit_line.html (f.e. _save)? Thanks. {% load i18n admin_urls %} <div class="submit-row"> {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %} {% if show_custom %}<input type="submit" value="{% trans 'Custom button' %}" class="default" name="_custom" />{% endif %} ... </div> -
Keeping a Persistent Class Instance in Django
Is there any way to keep an object instance persistent between serving pages in django and running a django management command? My code looks something like this: # api.py pseudo code import requests def RateLimited(maxPerMinute): minInterval = 60.0 / float(maxPerMinute) def decorate(func): global lastTimeCalled lastTimeCalled = [0.0] def rateLimitedFunction(*args,**kargs): elapsed = time.clock() - lastTimeCalled[0] leftToWait = minInterval - elapsed if leftToWait>0: time.sleep(leftToWait) ret = func(*args,**kargs) lastTimeCalled[0] = time.clock() return ret return rateLimitedFunction return decorate class MyAPI(): def __init__(self, api_key): self.api_key= api_key @RateLimited(30) def search_by_id(self, id): return requests.get("server.endpoint/users/?id={0}&=api_key={1}".format(id, self.api_key)) @RateLimited(30) def search_by_name(self, name): pass #similar to the above Now I have a cronjob that is calling a django management command every 10 minutes, which creates an instance of the above class, queries for existing user ids in my database and saves the results. At the same time it is possible that a user accesses my website and wants to search for a user (which in turn gets added to the database for later queries). I am wondering whether there is any way to keep one persistent and shared instance of this class to easier limit the calling rate (as there are rate limits per minute in place for the API). The … -
kombu.exceptions.EncodeError: User is not JSON serializable
I have django 1.11.5 app with celery 4.1.0 and I recived all the time: kombu.exceptions.EncodeError: <User: testuser> is not JSON serializable my settings.py: CELERY_BROKER_URL = 'amqp://localhost' CELERY_RESULT_BACKEND = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Makassar' CELERY_BEAT_SCHEDULE = {} tasks.py from __future__ import absolute_import, unicode_literals from celery import task from django.contrib.auth.models import User @task(serializer='json') def task_number_one(): user = User.objects.create(username="testuser", email="test@test.com", password="pass") return user I call task in the view: def form_valid(self, form): form.instance.user = self.request.user task_number_one.delay() return super().form_valid(form) -
Python GET Request Refresh
I built a Django application to pull sales data from a remote server with a GET request in Python. The data is then displayed in dashboard. Logically, the data only updates when I restart the server or Django application. How do I update the data at regular intervals, or on a page refresh? -
serialize return choices value django representation
I have models.py like this: class Tasks(models.Model): id = models.AutoField(primary_key=True) roles = ( (u'1', u'task1'), (u'2', u'task2'), ) role = models.CharField(max_length=1, choices=roles, default='1') Then I have serializers.py looking like this: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Member fields = '__all__' My viewset looks like this: class Tasks(viewsets.ModelViewSet): queryset = Tasks.objects.all() serializer_class = TaskSerializer So what I want to do is; say when I make a POSt request; I want to return saved data for tasks roles; if a I save it as 1, instead of returning roles field as 1, I want to return task1. How do I do this? -
form.cleaned_data not working in django
def kw(request): global form ans="this is the default value" form = NameForm(initial={'C': ans}) if form.is_valid(): print("helooo") d = (form.cleaned_data['C']) print("the value of d =",d) return render(request, 'keyword.html', {'form': form}) This is my code but dont know why the form is not taken as valid .. neither the print("helooo') cmd is working nor the next one . if condition is not satisfied.. from django import forms class NameForm(forms.Form): C = forms.CharField( widget=forms.Textarea) this is my form.py file -
How do I load custom template for password reset?
I'm setting up a Django project that will have a custom password reset form. My paths look like this: MY_PROJECT -myBlog -myBlog -urls.py -theme -templates -pages -password_reset_form.html My urls.py has this: from django.contrib.auth import views as auth_views urlpatterns += [ url("^reset-password/$", auth_views.password_reset, { "template_name": "pages/password_reset_form.html" }, name="reset_pw" ), ] When I go to http://127.0.0.1:8000/password_reset/, it loads Django's default password reset form. I want it to load my template. How do I set things up so my form loads instead? -
Getting stuck with a "502 Bad Gateway" error after I restart server
So I have a django 1.8.7 on 16.04 Ubuntu one click app hosted with DigitalOcean. Everytime I restart the server with the command 'service gunicorn restart' I get stuck with a "502 Bad Gateway" error afterwards, even without installing a single app in my django project. Not sharing any code since I'm having the same issue without even editing any of the default code...