Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to parse a list of sets
I am getting error :list indices must be integers or slices, not str after executing this piece of code: list1=[] list2=[] for key, items in groupby(inv, operator.itemgetter('user_id__name')): list1.append(list(items)) for key, items in groupby(list1, operator.itemgetter('inv_id__name')): list2.append(list(items)) Any suggestion as inwhy this error is coming ? And any solution for this will be helpful. -
make some model field conditionally visible in django
I have two field in my django model they should be editable only if user have selected 'type' as 'Dimention' otherwise they should not be visible to user. My model is look like this code from django.db import models class Configuration(models.Model): name = models.CharField(max_length=30) user_defined_name = models.CharField(max_length=50) FieldTypes = (('aD', 'Dimension'), ('aM', 'Measure')) type = models.CharField(max_length=11, choices=FieldTypes) is_key = models.BooleanField(default=False, editable=False) unit = models.CharField(max_length=30, null=True, blank=True, editable=False) def __str__(self): return self.name I know it is possible by using JavaScript but, I don't want to write html myself,Thus Can't use JavaScript for doing this. -
ValueError: Unable to configure filter 'suppress_deprecated': Cannot resolve 'project.settings.SuppressDeprecated': No module named project
while am trying to run python manage.py shell am facing this error ValueError: Unable to configure filter 'suppress_deprecated': Cannot resolve 'project.settings.SuppressDeprecated': No module named project thanks in advance -
what is the exact way to import in python and which is the best practise to import file there is lot of way to import so
you guys can import like this from . import * or like this from .models import * or like this from .models import Student or like this from . import views -
django not displaying image but inspector shows it
I am working with an html template and having trouble loading some of the images. I have my directory structured like used in this one. project /myapp //static ///assets ////images I have: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') And as you can see in the image, the inspector shows the image but it is not rendered. What is the proper debugging method here? <div class="image-wrapper"> <div class="image-inner"> <img class="image-sq" src="{% static 'leads/assets/images/hero/hero_big_31.jpg' %}" alt=""> </div> </div> -
Real-time Tweets Display on Django Website
I am working on a project where I need to display real-time Twitter feeds on Django website without refreshing the page at all. I have used Tweepy (Twitter API) for the live streaming but how should I get these real-time tweets displayed on my Django website. What I would like to have is something similar to this without page refreshing the page: Tweet 1 Tweet 2 On and On... -
automattically set up django instance from website
Ok, I have not found a specific answer that I am looking for online so here it is. I also do not have the highest ability in this. I have a multi tenant web app that has a custom subdomain. I have been able to let people know if the subdomain is available but I have not been able to automatically set up the user multi tenant app from the website. Have the new account subdomain.abc.com. What app do I need to do this with? If you know anything that may be useful let me know. Thank you -
GeoDjango make ValueError when migrate DataBase
I want use GeoDjango and make model and do makemigrations & migrate So GeometryField is made well in my table but show error message ValueError: String input unrecognized as WKT EWKT, and HEXEWKB. What is this message and how can i fix it? -
How to use UUID field in kwargs?
I am new to Django and I am working on unit tests. This is my model: class RandomModel(models.Model): title = models.CharField(max_length=64, null=False, blank=False) parent_user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) parent_course = models.ForeignKey(Course, on_delete=models.CASCADE, default=1) unique_id = models.UUIDField( default=uuid.uuid4, editable= False, unique=True) This is my urls.py path('myPath/retrieve/<uuid:unique_id>', views.RetrieveABCAPIView.as_view(), name = myPath_retrieve) I am trying the following in test.py class APIStatusCodeTests(APITestCase): def setUp(self): """ Sets up testing environment. Add all endpoints to be tested """ tbl = RandomModel.objects.create(title = 'rofl') tbl.save() self.retrieve_method_endpointsdeck = [ reverse('flashcards:flashcards_api:myPath_retrieve', kwargs = {'unique_id': RandomModel.objects.unique_id('unique_id')}) What changes should I make to the reverse function? I don't know how to get UUID in kwargs? Thank you! -
Django session is not generated using JWT and graphene
I'm new learning graphene with django, and as the documentation says, I have this class: import graphql_jwt class Mutations(graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() but calling the tockenAuth mutation, even when the token is correcty generates because the user and password are correct, I don't see anything saved in the session table: Session.objects.all() is always empty I'm checking the session for login out any user. So, how can I generate the Session entry from the authToken mutation call and what's the correct/better way to login/logout users using graphql_jwt? Regards -
how to manage websocket connection server side
this is simple websocket connection handler with django channels, how can i manage connection when host this code multiple server class TrackClient(WebsocketConsumer): #store all connection connection = {} def connect(self): self.connection[self.scope['user'].username] = self self.accept() #brodcast user-list to all user except me for user in self.connection: if self.connection[user] != self: self.connection[user].send(json.dumps({'type':'user-list', 'connection': list(self.connection)})) def disconnect(self, close_code): #remove user when user connection close del self.connection[self.scope['user'].username] #send updated user list to all user except me for user in self.connection: if self.connection[user] != self: self.connection[user].send(json.dumps({'type':'user-list', 'users': list(self.connection)})) print('removed user '+self.scope['user'].username) def receive(self, text_data): print(text_data) -
Django: How to use fetch from database and load in modal at same time?
So technically not at the same time. I have this code below doing 2 things: On the GET, views.py performs a query and renders a form pre-filled with an object instance Loads that form in a template on the modal accountModal <form method='get' action='#accountModal'> <input type='submit' class="btn btn-primary" data-toggle="modal" href="#accountModal" name='internal-id' value='{{rec.subscriber_fields.internal_id}}'> </form> The problem is the modal loads empty and closes and then I have to click the button again to view the account info - it fills the second time. I'm guessing I have to get the form and object first before calling the modal, but the button send's the account_id to be queried. How do I get this to work fluidly, being that I'm using the form and the GET to send the id to be queried? -
post profile information in django extended user model (user has no profile)
I know that this is a frequent topic, but however, with all the resources available on the web and stackoverflow, I couldn't get my form to work properly. I get this error : Exception Type: RelatedObjectDoesNotExist, Exception Value: User has no profile. Here is my setup in Django. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if kwargs.get('created', False): Profile.objects.create(user=kwargs['instance']) post_save.connect(create_user_profile,sender=User) @receiver(post_save, sender=User) def save_user_profile(sender, instance, created,**kwargs): if created: instance.profile.save() forms.py from django.contrib.auth.models import User from django import forms from django.contrib.auth.forms import UserCreationForm class SignUpForm(UserCreationForm): birth_date = forms.DateField() location = forms.CharField() password1 = forms.CharField(label=("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=("Confirm password"), widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'location','email', 'birth_date') widgets = { 'birth_date': forms.DateInput(attrs={'class':'datepicker'}), } labels = { 'username': ('Capser name'), } help_texts = { 'username' : None, 'birth_date': None, } views.py class UserFormView(View): form_class = SignUpForm template_name = 'home/registration_form.html' #display a blank form def get(self, request): form = self.form_class(None) return render (request, self.template_name, {'form': form}) #process form data def post(self, request): β¦ -
queryset filter according to only first line - Django
Tying to filter data using queryset.filter() in Django. but it returns not what I expecting. can someone correct me. single data cell looks like below.(each line separated by \n) γγ‘γγ―1θ‘γ§γγ(0.57)\n γγ‘γγ―2θ‘γ§γγ(0.67)\n γγ‘γγ―3θ‘γ§γγ(0.77)\n γγ‘γγ―4θ‘γ§γγ(0.87)\n γγ‘γγ―5θ‘γ§γγ(0.697) code like below queryset = queryset.filter(predicted_result__regex = r"\A.*", predicted_result__contains='(0.5') |\ queryset.filter(predicted_result__regex = r"\A.*", predicted_result__contains='(0.6') |\ queryset.filter(predicted_result__regex = r"\A.*", predicted_result__contains='(0.7') output: this will be considering all 5 lines not only the first line. target: only get values contains in first line between score (inside brackets)0.5 to 0.8. all the other lines should omit. -
Python Django Datetime objects and literal strings vs variables
I am transferring some legacy posts into a new Django blog. In my script, I have the following code: Entry.objects.create( title=['title'], slug=['slug'], chron_date=['chron_date'], clock='23:59:59', content=['content']) The problem is that the date, time, and datetime fields all refuse to take a variable, or, they all treat the intended variable as a literal string, which generates errors. The only solution Iβve found is the one you see for clock, where I have to hard code a literal string. This means I have to go back through the posts one at a time to manually correct the dates and times. Questions: Why do the date and time objects work this way? Is this the only workaround, or am I missing something that would allow me to use a variable and loop through all the actual dates and get them imported? Thanks. -
django==2.0.4 with MySQL, NoReverseMatch at /1/
I got this message whenever I try to open my blog article. my blog url is http://leonkong.com/ and post url is http://leonkong.com/1/ Error message: NoReverseMatch at /1/ Reverse for 'like_action' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)\\/like_action\\/$'] I use Django version 2.0.4 and recently created MySQL using AWS RDS. FYI, like_action function code(views.py): from django.contrib.auth.models import User from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import JsonResponse from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone from django.views.decorators.csrf import csrf_exempt def like_action(request, pk): """Like action: add +1 to post.like_button""" post = get_object_or_404(Post, pk=pk) post.like_button = post.like_button + 1 post.save() return redirect('post_detail', pk=post.pk) urls.py: from django.urls import path from . import views urlpatterns = [ path('keyboard', views.buttons, name='buttons'), path('message', views.message, name='message'), path('', views.post_list, name='post_list'), path('<int:pk>/', views.post_detail, name='post_detail'), path('post/new/', views.post_new, name='post_new'), path('post/<int:pk>/edit/', views.post_edit, name='post_edit'), path('about', views.about, name='about'), path('post/<int:pk>/remove/', views.post_remove, name='post_remove'), path('<str:category>', views.category_list, name='category_list'), path('<int:pk>/like_action/', views.like_action, name='like_action'), ] Here is html code for 'post_detail'. I always got error whenever I try to access 'post_detail' page. {% extends 'blog/base.html' %} {% load markdownify %} {% load static %} {% block content %} <div class="post"> {% if post.created_date %} <div class="date"> {{ post.created_date }} </div> {% endif %} <h1 class="detail">{{ β¦ -
Django Queryset absolute value of the annotated field
How do I get the absolute value of the annotated field? I tried the code below but it did't work. queryset.annotate(relevance=abs(F('capacity') - int( request.GET['capacity']) ) ).order_by('relevance') Error: TypeError: bad operand type for abs(): 'CombinedExpression' Thanks in advance! -
django test (nose) stuck after add package fixtures
I have django test run with nosetests. But after I add package fixtures, python manage.py test can't run as normal and get stuck. package fixtures (I had minimize it to debug failure reason): def setup_package(): pass def teardown_package(): pass And after I run test as normal, the shell get stucked: $ python manage.py test myapp -
AJAX updating database query as intended
I have pages that use both django context variables and json data. The first page is the "master page" that just displays all available data. The other pages however, are loaded upon submission of a dropdown form where the user can select a specific account to view. When the user selects an account and submits the dropdown form, two things are designed to happen: The form action goes to a django view function that makes several queries to the database, then passes context variables upon rendering the template. Next however Chart data is supposed to be loaded via Ajax from a certain url that returns a JSONResponse with the data. The chart data seems to load fine for the "master" page, since all data is shown when I visit the url where the data is sent. Upon selecting a specific account however, I want to pass a request to a url to filter the database based on the selection, thereby producing specific chart data. This is the part that doesn't seem to work, as when I select a specific account, I cant seem to get the chart data for only that specific account to show. Here is my code: urls.py β¦ -
Could not import 'project_name.schema.schema'
I am going through the official tutorial provided by graphene-python for their library. I, like a few others I have seen online, am having some serious issues trying to simply import the schema file within the project folder (project_name/schema.py). For reference, the project_name is cookbook as it is denoted within the tutorial. This is within my settings.py: GRAPHENE = { 'SCHEMA': 'cookbook.schema.schema' } and this is in the schema file tiself (project_name/schema.py): import graphene import cookbook.schema class Query(cookbook.schema.Query, graphene.ObjectType): # This class will inherit from multiple Queries # as we begin to add more apps to our project pass schema = graphene.Schema(query=Query) The error that I am getting is: Could not import 'cookbook.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: module 'cookbook' has no attribute 'schema'. I have also tried a few other tutorials as well, but haven't had any luck. My project is on django 2.0.2 and graphene 2.0.1. Any help would be much appreciated. -
how to create a model object that can handle a single foreign key for people and companies
I am creating an investor object. Investors can be people or companies. How can I create a model object that could represent either of these types in django? Here are a few ways I was thinking: Having two non required foreign keys: class Investor(models.Model): company = models.ForeignKey('companies.Company',on_delete=models.CASCADE, blank=True, null=True) customer = models.ForeignKey('accounts.Customer',on_delete=models.CASCADE, blank=True, null=True) investor_name = models.CharField(max_length=255) 2. Using a generic relation: class TaggedItem(models.Model): investor_name = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') Warchitecturally arhcitecturally sound route to go which will not cause me a lot of problems down the line? -
Wagtail CMS documents returning 404
I've got a Wagtail CMS site (running 1.13.1). It sits on two servers behind a load balancer and is using S3 for static and media assets which is managed by Django Storages. When I add a document to a page in the CMS, the document is uploaded to S3 but both the admin and the template can't find the document and return an error saying: ClientError: An error occurred (404) when calling the HeadObject operation: Not Found In the template I'm out putting the document's url using {{ item.url } (It I use item.file.url it works fine because it uses the CDN url.) In the 'documents' section of the CMS admin I'm getting an error saying: "The file could not be found. Please change the source or delete the document" I'm pretty baffled by it. To make matters worse, it does eventually show up. The document is accessible via both the S3 url and the CloudFront url but wagtail uses its own url. ie: https://mywebsite.com/documents/20/mypdffile.pdf rather than https://cloudfront.url/media/documents/mypdffile.pdf Config file highlights include: STATIC_URL = 'https://cloudfront.url/static/' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'project.custom_storages.StaticStorage' MEDIA_URL = 'https://cloudfront.url/media/' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'project.custom_storages.MediaStorage' AWS_STORAGE_BUCKET_NAME = 's3bucket.url' AWS_S3_REGION_NAME = 'ap-southeast-2' AWS_ACCESS_KEY_ID = 'ACCESS KEY' β¦ -
Exposing Django model method using TastyPie with Authentication
I'm trying to expose my Django model method using TastyPie and secure resulting endpoint by using BasicAuthentication, also I need to pass Django user authenticated with BasicAuthentication into my method: class TaskResource(ModelResource): class Meta: queryset = Task.objects.all() resource_name = 'jenkins_task' excludes = ['id', 'jenkins_job_name'] authentication = BasicAuthentication() def prepend_urls(self): """ Add the following array of urls to the TaskResource base urls """ return [ url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/run%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('run'), name="api_task_run"), ] def run(self, request, **kwargs): """ proxy for the Task.call_api method """ # create a basic bundle object for self.get_cached_obj_get. basic_bundle = self.build_bundle(request=request) print('User: %s' % basic_bundle.request.user) # using the primary key defined in the url, obtain the task task = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) # Return what the method output, tastypie will handle the serialization return self.create_response(request, task.call_api(basic_bundle.request)) I'm sending following POST request: Preparing request to http://127.0.0.1:8991/api/jenkins_task/7/run/ Using libcurl/7.54.0 LibreSSL/2.0.20 zlib/1.2.11 nghttp2/1.24.0 Connected to 127.0.0.1 (127.0.0.1) port 8991 (#48) Server auth using Basic with user 'integration' POST /api/jenkins_task/7/run/ HTTP/1.1 Host: 127.0.0.1:8991 Authorization: Basic aW50ZWdyYXRpb246aW50ZWdyYXRpb24= User-Agent: insomnia/5.15.0 Content-Type: application/json Accept: */* Content-Length: 67 { "snow_number": "INC000000", "Store": "0940", "Service": "RE" } However, I got code 500, basically because the internal logic inside task.call_api method is not able to find basic_bundle.request.user. So, β¦ -
How do I make Stripe email a customer who changes their subscription?
I'm using the Stripe's Python library to process subscriptions. Here's a snippet of my backend Django code. susbcriptionID = stripe.Subscription.retrieve("subID") stripe.Subscription.modify( susbcriptionID, items=[{ "id": subscription["items"]["data"][0].id, "plan": "planID", }] ) The Stripe docs states that Stripe emails customers upon successful charges. But I tested this out in live mode by having two subscription choices, one for 50 cents a day and the other for 51. When I signed up for the first choice, I inputted my email, and Stripe emailed me a receipt. But when I later switched to the more expensive plan, I got no email. When I check my Stripe dashboard, I go to Billing > Subscriptions. I click myself under the "Customer" column. When I scroll to "Events," it shows this (I made this pipe-delimited format for easier reading): my@email.com upgraded to Daily test 2 from Daily test | 2018/04/16 20:02:25 A proration adjustment for $0.51 USD was created for my@email.com | 2018/04/16 20:02:25 A proration adjustment for ($0.50 USD) was created for my@email.com | 2018/04/16 20:02:25 my@email.com subscribed to the Daily test plan | 2018/04/16 19:59:53 my@email.com's invoice for $0.50 USD was paid | 2018/04/16 19:59:53 my@email.com has a new invoice for $0.50 USD | 2018/04/16 19:59:53 β¦ -
Textfield Length Django
Good day, I am trying to get a len of a textfield in Django so I can manipulate it in my template since the name of the school is too long, it is overlapping in the PDF display. I found this old post here in SO How to get the length of a TextField in Django? I am trying to get the length of a school field which is related to another model. x = Recipient.objects.get(id='1234551') len(x.department.school) This gives me an error: object of type 'Recipient' has no len(). School is also a field and it seems to work on the old post. I just don't understand why it doesn't work in my end. Any suggestions will be highly appreciated