Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Server is not running
The Server is started in pycharm but in browser its showing like above pictures I am new to Django Framework and I just installed pycharm now. Can any one please help me out from this?? -
How would I connect a react-native mobile app to Django
Suppose I wanted to make a simple react native app with just one button connect to a Django backend. For example, when a user presses the button, it should connect to the server and return “hello world”. I know you have to use a rest api, but how would the code look in the us and the .Py Also, when you combine them, is it possible to use the Django user model, or are some features blocked when you use a rest-api like a @login_required. Thank you for your time. -
Comment thread in Django
I am building up a simple Django app with blogs and comments on blogs. While ddveloping the comment thread, I am getting the error "no such table: blog_commentsonpost" when I try to enter a comment. Can someone help me to solve the issue. models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) def publish(self): self.published_date = timezone.now() self.save() def get_type(self): return "post" def get_absolute_url(self): return reverse("post_detail", kwargs={'pk': self.pk}) def __str__(self): return self.title class CommentsOnPost(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comment') post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) text = models.CharField(max_length=1000) @classmethod def create(cls, author, text, post): postcomment = cls(author=author, post_id=post, text=text, created_date=timezone.now, published_date=timezone.now) return postcomment views.py class PostDetailView(DetailView): model = Post redirect_field_name = 'post_detail' def post(self, request, *args, **kwargs): author = request.user text = request.POST['postcomment'] post = request.POST['post'] postcomment = CommentsOnPost() postcomment.text = text postcomment.author = author postcomment.save() return HttpResponseRedirect('/blog/post/{}'.format(post)) html <form method="POST" class="post-form" >{% csrf_token %} <div class="form-group"> <label for="postcomment">Comments:</label> <textarea class="form-control" name="postcomment" rows="5"></textarea> </div> <input type="hidden" name="post" value="{{ post.id }}"> <div> <input type="submit" class="btn btn-primary" style="color:blue;" value="Comment"/> -
Implement pagination and search filter in django
Please help I am trying to implement django pagination with search filter. I keep getting the following error: TypeError at / object of type 'method' has no len() The following is my code thus far: def product_list(request, category_slug=None): search_term = '' category = None categories = Category.objects.all() adds = AddBanner.objects.all() products_list = Product.objects.filter(available=True).order_by("-updated_at") productsImage = ProductImage.objects.all() print(product_list) query = request.GET.get("search") if query: products_list = products_list.filter( Q(name__icontains=query) | Q(description__icontains=query) ).distinct paginator = Paginator(products_list, 10) # Show 10 contacts per page page = request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context = { 'category': category, 'categories': categories, 'products': products, 'productsImages': productsImage, 'search_term': search_term, 'adds': adds } return render(request, 'shop/product/list.html', context) -
Apply unique constraint to columns on two separate tables (Django, postgres)
So I'm putting together a site which works a little like github, where both users and organisations have a handle: class User(AbstractUser): """ Using django's default user model, with its username field which looks like: username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) """ # Many users to many organisations organisations = ManyToManyField('Organisation', related_name='users', blank=True) class Organisation(models.Model): # ...other stuff, id etc handle = CharField(unique=True, max_length=36, null=False) I'll set up urls with endpoints like mydomain.com/username_or_handle/stuff. This creates conflict, since a user could have the same handle as an organisation. Current solution: I have a signal which, on pre-save of either a User or an Organisation, looks up BOTH the tables to ensure uniqueness, and raises a ValidationError if its violated. @receiver(pre_save, sender=User) @receiver(pre_save, sender=Organisation) def check_valid_handle(sender, instance, **kwargs): """ The abbreviated gist... """ if (Organisation.objects.filter(handle=instance.handle).count() > 0) or (User.objects.filter(username=instance.handle).count() > 0): raise ValidationError(detail='This handle is already taken, or prohibited. Please try another.'.format(type_str)) But strictly speaking, this could be subject to a race condition, as no lock is applied between the check time and the model creation / update time. Besides, … -
Correct way to extract values from Django Query
How do you set the results of a Django query to equal a new set of variables? for example, when I run this query on my Django shell: getDefaults = defaultParams.objects.filter(isDefault = True, device = 41) then run: for val in getDefaults.values(): print(val) It returns: {'id': 2, 'device_id': 41, 'customerTag': 'ABCD001', 'isDefault': True} I would like to use the values in this dictionary to save a new record into my database, but can't seem to extract the values from the dictionary? I thought it would be something like: device_id = getDefaults.device_id NewCustomerTag = getDefaults.customerTag -
django foreign key conditional
Below is my models. class DoneType (AbstractTimeStamp): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, primary_key=True) class Done (AbstractTimeStamp): user = models.ForeignKey(User, on_delete=models.CASCADE) contents = models.CharField(max_length=200) done_type = models.ForeignKey(DoneType, on_delete=models.SET_NULL, null=True) start_time = models.DateTimeField() > One user can have many DONE models. And DONE models can have many DONE_TYPE models. However, this is only possible if USER in the DONE model is the same as USER in the DONE_TYPE model. How do I implement this? -
Django Login/Signup With own users Model
I am using phpMyAdmin for the database. I am creating own user table and store user information in it without extending the Django User Model. Now, I have a problem in the login part. I can't get data from users table with objects and authenticate function is also not working. Here is my code:- View.py from django.shortcuts import render,redirect from django.http import HttpResponse from .form import SignUp,UserLogin from .models import users from django.contrib.auth import authenticate,get_user_model,login,logout from django.contrib.auth.models import User def Userlogin(request): form=UserLogin() if request.method == 'POST': user_login = UserLogin(request.POST or None) if user_login.is_valid(): username = request.POST.get('email', '') password = request.POST.get('password', '') getInfo=users.objects.get(email='example@mail.com') user=authenticate(email=username,password=password) if user is not None and user.is_active: login(request,user) return redirect('/') args={'form':form} return render(request,'html/login.html',args) form.py from django import forms from .models import users class UserLogin(forms.Form): email = forms.CharField(widget=forms.EmailInput(attrs= { 'value':'', 'class':'form-control'})) password = forms.CharField(widget=forms.TextInput(attrs= { 'type': '', 'value':"mukul", 'class':'form-control'})) model.py from django.db import models class users(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=100, blank=False) email=models.EmailField(max_length=100, blank=False, unique=True) password=models.CharField(max_length=500, blank=False) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now_add=True) def __str__(self): return self.email What I need:- Run authenticate().its not working, I don't know want is wrong. Should, i want to create new authenticate() in forms.py. if I call users.objects.get(email='example@mail.com'), it's also not working in view.py but if run in python shell … -
Django password plolices package for Django > 1.8?
This package works with Django v 1.7, maybe also 1.8 It forces users to change password after x seconds. Is there anything similar for more recent Django versions? http://tarak.github.io/django-password-policies/topics/force.password.change.html -
How to ignore second DB in Django unit test?
I am trying to run a simple unit test in Django where I verify the template used. It is very similar to the test in TDD with Django: from django.test import TestCase class HomePageTest(TestCase): def test_uses_home_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'home.html') The problem is that the view uses a second database and it fails with the error: django.db.utils.ProgrammingError: relation "public.secondary_db" does not exist Is it possible to run this test without hitting the database at all? I know that multiple databases in Django is a known issue, but is there a way to avoid this issue all together? -
how can use particular row and column cell to be merge using xlwt with Django
I want to need a particular row and column cell merge in excel download using xlwt with Django for example row =5 and column =7 to merge ie rowspan or columnspan of two rows or columns -
Django - Displaying users dropdown list in Template from ModelForm
i have a Model field called Followed_By which is a TextField, the thing i'm facing is when i try to to use Template from ModelForm, the Data is not being saved, i think the error i'm making is in the dropdown list of the template because when i replace the dropdown list with normal input tag of type text then all work fine, my template is: <div class="form-group col-md-12"> <label for="{{form.Followed_By.name}}">Follower</label> <select id="{{form.Followed_By.name}}" name="Followed_By" class="form control" value="{{form.Followed_By.value|default_if_none:""}}"> <option>{{John}}</option> <option>{{Bale}}</option> </select> </div> -
Getting the latest addition in a m2m_changed signal in Django
I'm trying to use the m2m_changed signal in Django to create a notification for when a post is 'liked'. Right now, I have a post_save signal functioning to create a notification for a comment. In my m2m_changed signal function, printing the queryset for likes on a post pre_add and post_add shows the addition of the user who liked the post when the signal is sent, ie pre = QuerySet [User: TestUser] and post = QuerySet [User: TestUser, User: test_user]. What method can I call on instance.likes to return the user associated with this m2m_changed signal? Or can I call a diff method on the pre and post query sets to return this one user? I'm looking to create the notification by Notification.objects.create(post=instance, user=?????, liked=True, date_posted=?????) And also, is there a way I can set date_posted for the notification to equal the datetime of when the signal is sent? class Notification(models.Model): post = models.ForeignKey('photo_blog.Post', on_delete=models.CASCADE, null=True, blank=True) comment = models.ForeignKey(Comment, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) liked = models.BooleanField(default=False) date_posted = models.DateTimeField(null=True, blank=True) @receiver(post_save, sender=Comment) def auto_create_comment_notification(sender, instance, created, **kwargs): if created: Notification.objects.create(post=instance.post, comment=instance, date_posted=instance.date_posted) @receiver(m2m_changed, sender=Post.likes.through) def auto_create_like_notification(sender, instance, action, **kwargs): if action == "pre_add": print(instance.likes.all()) if action … -
firebase-admin-python is slow when calling get_user with multiple requests
From an endpoint, we are retrieving the user data from firebase using the get_user method from the firebase-admin-python library. The problem is that, when calling the endpoint with high load, the requests to firebase degrade the endpoint's response time. The application is built on top of Django Rest Framework and deployed on gcloud Kubernetes cluster. We are using gunicorn, eventlet workers. -
Python List / JSONField data: Unable to get all occurrences of specific key
I have a json report that is stored in a pgsql db. I am storing the report as a JSONField data model. I am able to pull out a subset of the data I want to iterate over by using: assert_errors_list = specific_result.data.get('tests') this gives me a list. I am then trying [quite unsuccessfully] to iterate over that list and pull the value(s) associated with the key longrepr. I know in this data set there are 2. Without issue I can pull at least one instance of this data so long as I am specific: print(assert_errors_list[0]['call']['longrepr']) this as expected returns the first occurrence: self = <lib.tests.name.test_name.Class testMethod=test_general_search_go> @pytest.mark.smoke def test_general_search_go(self): test_info_here # store response as json query_resp_data = json.dumps(post_query_python.text) > assert post_query_python.status_code == 500 E AssertionError: assert 200 == 500 E + where 200 = <Response [200]>.status_code testarea/test_name.py:141: AssertionError Now I have made attempts to iterate over this list to get all occurrences but they have failed in various ways: stack_trace = [i for i, x in enumerate(assert_errors_list) if x == 'longrepr'] returns and empty list. If I do this: for i in assert_errors_list: for k, v in i.items(): if k == 'call': pprint(v['longrepr']) I get back the first instance: … -
Django graph_models doesn't show my classes
After running the manage.py graph_models -a -g -o myProject.png command my classes don't appear in the model graph even though the execution is successfull. -
Use serializer validated data in get_queryset()
I want to write custom get_queryset() method for serializer based on query params. Here is my serializer: class SearchRequestSerializer(serializers.Serializer): name = serializers.CharField(max_length=255, required=False) nickname = serializers.RegexField( r'^(?!(.*?\_){2})(?!(.*?\.){2})[A-Za-z0-9\._]{3,24}$', max_length=24, min_length=3, required=False, ) modelA_id = serializers.CharField(max_length=11, min_length=11, required=False) def validate_modelA_id(self, value): queryset = modelA.objects.filter(id=value) if queryset.exists(): return queryset.first() else: raise serializers.ValidationError(_('Not found')) If object of modelA exists - validation will return an instance. But I don't want to perform the same query in get_queryset() in my if branch. def get_queryset(self): name = self.request.query_params.get('name', None) nickname = self.request.query_params.get('nickname', None) queryset = User.objects.filter(Q(name__contains=name)|Q(nickname__contains=nickname)) if 'modelA_id' in self.request.query_params: # in this case will be annotated extra field to queryset # extra field will be based on 'modelA' instance which should be returned by serializer return queryset I found only one solution - add the following line in my GET method: self.serializer = self.get_serializer() Than it will be possible to get validated values in my get_queryset() method. But PyCharm don't like this solution -
Variables in template within template
I have a template that includes another one: <div>...</div> {% include 'other_template.html' %} <div>...</div> The main template is associated with a function view, and it has its own variables (in data): def main_view(request, *args, **kwargs): data = {...} return render_to_response('main_template.html', data) The other template also has its own variables: {% for item in items %} <div>{{ item.name }}</div> {% endfor %} And it is associated with a CBV: class OtherTemplateView(ListView): template_name = 'other_template.html' When browsing the URL bound to OtherTemplateView we get the expected result. However when the template is included in the main one, items are missing. What is the best way to deal with this situation without having to populate data in the main view with all the data necessary in the nested templates? Is there any way I could "instantiate" these views in the main view and pass it to the main template? -
Django Filter all objects that contain latest date
I'm performing two queries to obtain all of the latest matches as shown below. Is there a more efficient way to retrieve all match objects that have the same latest date? class Match(models.Model): team = models.CharField() round_date = models.DateField() date = Match.objects.latest('round_date').round_date matches = Match.objects.filter(round_date=date) -
Django Authentication on different databases
I want to create an App for Customers where every customer has its own DB. So as Login information they need to enter three different fields: customernumber, username, password. The username and password should do the normal authentication stuff and the customernumber is there to go to the right database user table for authentication i can go to other databases through the using() method but how do you authenticate a user through the right database? -
"Warning: We detected the use of uwsgi with disabled threads" when using Sentry/Raven with Django and PythonAnywhere
Using Django with Sentry/Raven, I am frequently getting the following error : /lib/python3.6/site-packages/raven/utils/compat.py:216: Warning: We detected the use of uwsgi with disabled threads. This will cause issues with the transport you are trying to use. Please enable threading for uwsgi. (Enable the "enable-threads" flag). So, ironically, it seems the error is coming from raven itself. It looks like I need to enable threading for uwsgi. However, to my knowledge, PythonAnywhere does not support threading (is this right ?). How can I prevent these errors from showing up ? Are they causing anything damaging apart from these reports ? They don't seem to be affecting the user experience at all. Note : I found this thread on the Sentry github that seems to reference the same issue, but I'm not sure how to go from here. -
execute eb command along with login from command line
I'm trying to execute .sh file in python using "os.system()" function in that i write command for login Elastic Beanstalk after that i try to create a directory but after login and show me Elastic Beanstalk prompt but it's not executing create directory command it execute when i write exit command from that Elastic Beanstalk logged-in prompt. What i need it should be logged in into Elastic Beanstalk and create an directory. Please help me i try a lot but not getting out from this. -
Provide form data via GET in Django Create View
I want to create a CreateView which allow user get a form where they click somethings and response a form with pre-filled fields which cannot not be change. By the way, I want to display these prefilled and uneditable fields in instead of . The code below contains the model which I want CreateView to create, and the form which I still have no idea how to do next. #models.py class Booking(Occurrence): TYPE_CHOICES = ( ('web', 'Web Application'), ('emb', 'Embedded Application'), ) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookings') room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='bookings') type = models.CharField(max_length=50, choices=TYPE_CHOICES, default='web') date = models.DateField() start= models.TimeField() end = models.TimeField() check_in = models.BooleanField(default=False) check_out = models.BooleanField(default=False) #views.py @method_decorator(login_required, name='dispatch') class BookingAddView(CreateView): model = Booking form_class = BookingForm template_name = 'booking/add_booking.html' def get_initial(self): pass def form_valid(self, form): form.instance.user = self.request.user super().form_valid(form) def form_invalid(self, form): pass #forms.py class BookingForm(forms.Model): class Meta: model = Booking fields = ['user', 'room', 'date', 'start', 'end'] def __init__(self): pass For example, I want room, date, end fields prefilled when rendering. I am thinking of GET but I want know the right way to do it with class CreateView. I want to something like: <form> <p>{room field value}</p> <p>{date field value} </p> <p>{start … -
Is django aggregate SUM cached? Or does it calculate every time?
Let's say I have a Transaction model: class Transaction(models.Model): receiver = models.CharField(unique=True) value = models.DecimalField(max_digits=10, decimal_places=5) date = models.DateField() Now, I have tens of thousands of transaction that go into the table. I need to show the receiver the transactions for each day, week, month, year, etc. I can do this by using the following statement: from django.db.models import Sum transactions = Transaction.objects.filter(receiver="name").aggregate(Sum('value')) and then filter depending on what date periods I need. Example: transactions.filter(date__gte=start_date, date__lte=end_date) How fast is this? What happens if the table grows to have millions of entries? How do I make sure that it is optimized? Does django cache the values from Sum? My naive way of thinking how to make this optimized was to create more models: DayTransaction, MonthTransaction, YearTransaction, etc. and when I update the Transaction model, I update all the others models. This way, when the users request the data, I get it from the models that "cached" the summed data and it doesn't have to do any operations, it just retrieves data from the respective tables, which are a lot smaller than the Transaction one. The problem with this approach is that it might not actually be faster, it's not that flexible … -
Django admin change field from text to combobox
In my models i have this class: class temp_main(models.Model): descr = models.CharField(max_length=200, verbose_name="Description") notes = models.TextField(null=True, blank=True, verbose_name="Note") dt = models.DateTimeField(auto_now=True, verbose_name="Created") owner = models.ForeignKey('auth.User', related_name='tmain_owner', on_delete=models.CASCADE, verbose_name="API Owner") class Meta: verbose_name = '1-Main Template' verbose_name_plural = '1-Main Templates' def __str__(self): return self.descr Then in my admin.py class temp_mainAdmin(admin.ModelAdmin): #list_filter = ('main_id__descr', 'l_type') list_display = ('descr', 'notes', 'dt') #ordering = ('-l_type',) def save_model(self, request, obj, form, change): obj.user = request.user super(temp_mainAdmin, self).save_model(request, obj, form, change) def changeform_view(self, request, obj_id, form_url, extra_context=None): l_mod = temp_main.objects.latest('id') extra_context = { 'lmod': l_mod, } return super(temp_mainAdmin, self).changeform_view(request, obj_id, form_url, extra_context=extra_context) all done but i would in add and edit form that my field descr (charfield) vas not displayed as a textbox but instead like a combobox with pre-defined key/val data like 1:'Descr1',2:Descr2' etc etc How can i achieve this result in django admin add and edit form? thanks in advance