Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch all data with one SQL django?
I have some problems when I fetching the data from database. I have models class Product(CreationModificationDateMixin, MetaTagsMixin, ImageThumbnailMixin): ... brand = models.ForeignKey( Brand, null=True, blank=True, related_name='products', verbose_name='Производитель', on_delete=models.SET_NULL ) material = models.ForeignKey( Material, verbose_name='Материал', blank=True, null=True, related_name='products', on_delete=models.SET_NULL ) class Material(models.Model): name = models.CharField( 'Название', max_length=100 ) class Brand(CreationModificationDateMixin, MetaTagsMixin): country = models.ForeignKey( Country, blank=True, null=True, verbose_name='Страна производителя', related_name='brands', on_delete=models.SET_NULL ) name = models.CharField( 'Название бренда', max_length=100, ) class Country(models.Model): name = models.CharField( 'Название', max_length=200 ) I am trying to fetch brands group by materials and countries, where products have field material set. Now my code is like that countries = Country.objects.all() materials = Material.objects.all() country_materials = [] for country in countries: dc = {'country': country, 'materials': []} for material in materials: brands = Brand.objects.filter( products__material=material, country=country).distinct() if brands.exists(): dc['materials'].append({'material': material, 'brands': brands}) if dc['materials']: country_materials.append(dc) I have been trying to use prefetch_related('products__material') but this did not help. How can I optimise that query? -
Python Django How display information of logged user contained in another class in my template ?
I'am developing a website in Python Django. I have CustomUser class for logging and another class coach where I have information of my users. Every user are linked to coach class. I'am trying to display in my template information of my user contained in class coach. I have logged user and can display their username on my template with {{ user.username }} My problem is that I am not able to display for example Adresse with {{ coach.Adresse }}. Can you please help me with this issue ? My models.py class coach(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) Adresse = models.TextField(max_length=140, default='DEFAULT VALUE') Telephone = models.IntegerField(null=True, max_length=140, default='111') My profile.html <body> {% if user.is_authenticated %} Welcome {{ user.username }} !!! {{coach.Adresse}} !!! {% else %} Not logged {% endif %} </body> -
How do I check if a user is in a many to many relationship
This is the model: class Set(models.Model): name = CharField(max_length = 25) teacher = ForeignKey(get_user_model(), null = False, on_delete = models.CASCADE) students = ManyToManyField(get_user_model(), related_name= 'set_students') def __str__(self): name = self.name teacher = self.teacher.get_full_name() return '{} | {}'.format(name, teacher) def amount_of_students(self): students = self.students return students.count() def view_set(self): return reverse("view_set", kwargs = {'set_id': self.id}) I am trying to see if request.user is in the manytomany relationship students. How do I do this? -
Uisng Custom Queryset as manager, filter again after a custom filtered method
I have a custom QuerySet: class EntityModelQuerySet(models.query.QuerySet): def active(self): return self.filter(is_active=True) In the model, I sent the QuerySet to work as manager: class Entity(models.Model): is_active = models.BooleanField(default=False) objects = EntityModelQuerySet.as_manager() In View I try: Entity.objects.active.filter(is_home=True) It gives me an error: 'function' object has no attribute 'filter' Why, how to fix it ? -
No image in django template with javascript
In my django app I am trying to get images from backend and display it on webpage.The data for which image to display is coming from json.There can be multiple images on a widget.I am reading the json for multiple images and displaying it accordingly. My JS: for(var index=0;index<json.length;index++) { var images = json[index].html.split(','); var imageOutput = ""; for(var j = 0; j < images.length; j++) { imageOutput += '<div class="imagewrap"><img src="{% get_static_prefix %}images/'+ images[j] +'><input type="button" class="removediv" value="X" /></div></div>'; } gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button>'+imageOutput+'<textarea>'+json[index].html+'</textarea></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row); } JSON: var json = [{ "html": "car1.png,car2.png", //2 Images "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "car2.png", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "car1.png", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "car1.png", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "car3.png", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "car2.png", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; There are two problems: I am not getting images at all when I run the above code I do not get multiple images on widgets(Even when the JSON's HTML key has 2 images) … -
Django: Apps aren't loaded yet
Strange error, think I must be missing something obvious. I've created a services.py file in my app which will populate my database when the file is run. So it isn't run every time the server boots/queries the file I've added: if __name__ == '__main__': import ... from models import Authority, Rating <logic to populate database> However, when I run the file, Django is throwing the exception: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Am I running this file from the wrong place? Would it be better suited to my models file? If so, how do I stop it running every time the server boots? -
Django call @classmethod create from SystemCreateView
I want to call the @classmethod create of the System model by the SystemCreateView. However currently the create classmethod is not called and therefore the z-property of the System model is not calculated but remains at it's default value of 4. The simplified version of the model Class is: class System(models.Model): project = models.ForeignKey('solgeo.Project', related_name='systems', on_delete=models.CASCADE) x = models.IntegerField(default=1) y = models.IntegerField(default=4) # calculated properties z = models.IntegerField(default=4) @classmethod def create( cls, project, x, y): system = cls(project=project, x=x, y=y) # Calculated properties system.z = x*y return system The SystemForm is defined as: class SystemForm(forms.ModelForm): class Meta: model = System fields = [ 'x', 'y' ] The CreateView is currently as follows: class SystemCreateView(LoginRequiredMixin, CreateView): model = System template_name = 'system/create.html' form_class = SystemForm def form_valid(self, form): obj = form.save(commit=False) project_id = self.kwargs['pk'] project = get_object_or_404(Project, pk=project_id) obj.project = project return super(SystemCreateView, self).form_valid(form) def get_context_data(self, *args, **kwargs): context = super(SystemCreateView, self).get_context_data(*args, **kwargs) context['project_id'] = self.kwargs['pk'] return context -
py.test and Django DB access except for one test class
To me it's clear "How can I give database access to all my tests without the django_db marker?" But I would prefer/need to have several class tests without the DB access. How can I exclude classes or methods when enable_db_access_for_all_tests is active for all tests? Is there a decorator like @pytest.mark.no_django_db or other possible solutions? Thanks! D -
How to remove registered admin class from menu under Django and xadmin
Thanks a lot for your time for reading my questions. I am using Python 3 / Django 2.0 / xadmin to build my website. I have 3 models defined in the model file, such as A, B and C. class C(models.Model): product = models.ForeignKey(A, on_delete=models.CASCADE, verbose_name="TestA") product_module = models.ForeignKey(B, on_delete=models.CASCADE, verbose_name="TestB") I would like to add A and B from C's add or update page, but I do not want to have specific menus to handle A and B information in the website. If I register the model as xadmin class it will bring add function in C's page but new menus for A and B at the same time. Is there anyway to keep add function but remove the menus? Thanks a lot for your help and wish you a good day. -
Add related record
I'm trying to add a related record, without selecting the foreign key. Effectively, I have a patient (main) record with many-to-one child records (visits). I just want the form to open, creating a related record. I'm sure that there is a simple function i.e. get_object_or_404, initial, get_initial, get_absolute_url(self)? Perhaps some ideas about the framework around this? I imagine there are multiple ways of doing this, any which is the most efficient? Basically I have a list of patients names, with an "add new visit" and I want to open up a form and subsequently add the details of the visit. I'd like the visit foreign key to be autopopulated with the patient primary key. Its the "add related record" function seen in other database management systems. views.py class VisitCreate(CreateView): model = Visit fields = ['fk_visit_main', 'visit_date', 'visit_progress_notes'] success_url = reverse_lazy('clincher:main') def get_initial(self): return self.request.GET models.py class Visit(models.Model): fk_visit_main = models.ForeignKey(Main, on_delete=models.CASCADE, verbose_name=('Patient Name')) visit_date = models.DateField() visit_label = models.CharField(max_length=256, blank=True, null=True) visit_types_list = ( (str(1), 'Consultation'), (str(2), 'Procedure'), (str(3), 'Administrative'),) visit_type = models.CharField( max_length=256, choices=visit_types_list, default=1,) visit_progress_notes = models.TextField(max_length=10000, blank=True) outcomes = models.BooleanField(default=False) def __str__(self): return str(self.visit_label) def get_absolute_url(self): return reverse('clincher:main-detail', kwargs={'pk': self.pk}) -
How to send e-mail using custom connection settings in Django?
I want to use custom connection settings while activating user after registration. This is my snippet that is working: from django.core.mail.backends.smtp import EmailBackend mail_connection_kwargs = dict( host=getattr(settings, 'EMAIL_REGISTRATION_HOST', None), port=getattr(settings, 'EMAIL_REGISTRATION_PORT', None), username=getattr(settings, 'EMAIL_REGISTRATION_USER', None), password=getattr(settings, 'EMAIL_REGISTRATION_PASSWORD', None), use_tls=getattr(settings, 'EMAIL_REGISTRATION_USE_TLS', None), fail_silently=getattr(settings, 'EMAIL_REGISTRATION_FAIL_SILENTLY', False), use_ssl=getattr(settings, 'EMAIL_REGISTRATION_USE_SSL', None), timeout=getattr(settings, 'EMAIL_REGISTRATION_TIMEOUT', None), ssl_keyfile=getattr(settings, 'EMAIL_REGISTRATION_SSL_KEYFILE', None), ssl_certfile=getattr(settings, 'EMAIL_REGISTRATION_SSL_CERTFILE', None), ) class EmailRegistrationBackend(EmailBackend): def __init__(self): super(EmailRegistrationBackend, self).__init__(**mail_connection_kwargs) user.email_user( subject=subject, message=message, from_email=settings.EMAIL_REGISTRATION_FROM_USER, connection=EmailRegistrationBackend()) When this is not working: with get_connection(**mail_connection_kwargs) as connection: user.email_user( subject=subject, message=message, from_email=settings.EMAIL_REGISTRATION_FROM_USER, connection=connection) How should initialize the connection to make it safe for the application? Can i initialize the connection at the top of my views.py like: connection = EmailBackend(**mail_connection_kwargs) And then in my view classes just use: user.email_user( subject=subject, message=message, from_email=settings.EMAIL_REGISTRATION_FROM_USER, connection=connection) -
Django pre-filling data in form from URL
So i have a button on my detailView page for my model 'patient', and that takes you to a createView for my other model 'appointment'. What i want is the foreign key field of the appointment to be pre-filled depending on what detailView i come from. Here is my code so far: urls.py: # /patients/appointment/add url(r'appointment/add/$', views.appointmentCreate.as_view(), name='appointment-create'), models.py: class patient(models.Model): TITLE_CHOICES = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Ms', 'Ms'), ('Miss', 'Miss'), ) Title = models.CharField(max_length=100, blank=True, choices=TITLE_CHOICES) First_Name = models.CharField(max_length=250, default='') Surname = models.CharField(max_length=250, default='') DOB = models.DateField() class appointment(models.Model): Patient = models.ForeignKey(patient, on_delete=models.CASCADE) views.py: class appointmentCreate(LoginRequiredMixin, CreateView): model = appointment fields = ['Patient', 'Date', 'Time', 'Duration', 'Location', 'Clinician', 'AppointmentType'] For example, the url might be /appname/appointment/add/?Patient=pk , where the end part determines what the value of Patient will be. I have looked into the get_initial function but do not understand how it can help me achieve this. Any help is appreciated. I am relatively new to django so please nothing too complex. -
Error installing pillow in vagrant virtualenv
Error install Pillow in virtual env using vagrant. I get this error Command /home/vagrant/venv/bin/python3.4 -c "import setuptools, tokenize;file='/home/vagrant/venv/build/pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-0chezg5z-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/vagrant/venv/include/site/python3.4 failed with error code 1 in /home/vagrant/venv/build/pillow Storing debug log for failure in /home/vagrant/.pip/pip.log I already tried the "pip install pillow==3.4.0 still the same result. I got this result also ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting please help. Thanks -
Django: Make the server continue to run without using runserver
I have started using django_channels on my server. But if I want the websocket to work, I have to use: python manage.py runserver 0.0.0.0:8080 And the server runs and I can connect ws://myip:8080 But, as soon as I do ctrl + c. It quits i.e, I am unable to connect on ws://myip:8080 anymore. I want to be running continuously. -
Django - issue with APPEND_SLASH and POST requests
I am using Django 1.10, and my goal now is to make urls available both with and without trailing slash. To do this, I added slash to all my URLs in the URLConf files, and then set APPEND_SLASH variable value to True (well, this is the default value). Now the problem is that external POST requests (which I can't control) yield the following error: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/Calendar/AddAccounts/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. They mention this in Django doc, and yet after hours of surfing the net, I can't figure out how to address this issue. -
Django1.1 AttributeError at /login/ 'NoneType' object has no attribute 'is_active'
I am writing a login page with Django 1.1. Somehow I received this message AttributeError at /login/ 'NoneType' object has no attribute 'is_active' My code is as below def login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is None and user.is_active: auth.login(request, user) return HttpResponseRedirect('/index/') else: return render_to_response('login.html', RequestContext(request, locals())) And here is my template <!doctype html> <body> <form action="" method="post"> <label for="username">用戶名稱:</label>{% csrf_token %} <input type="text" name="username" value="{{username}}" id="username"><br /> <label for="password">用戶密碼:</label> <input type="password" name="password" value="" id="password"><br /> <input type="submit" value="登入" /> </form> </body> -
No module named 'django.urls' django 1.8
views.py from nba.models import News from nba.serializers import NewsSerializers from rest_framework import viewsets # Create your views here. class NewsViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerializers urls.py from django.conf.urls import url, include from django.contrib import admin from rest_framework.routers import DefaultRouter from nba import views router = DefaultRouter() router.register(r'news', views.NewsViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('router.urls')), ] my django version is 1.8. When I visited http://127.0.0.1:8000/api I got No module named 'django.urls' what should i do -
Django one time initializer
Is it possible to make one time initializer? I have some python code, and want to initialize it one time after Django server is up. And after requesting some page class variable of that code will be used. Is it possible to make that? Please don’t be harsh on me. I’m new in Django and python -
I changed the primary_key of a model and now it's `ForeignKey` model doesn't work
I have a Post model: class Post(models.Model): id = models.CharField(max_length=18, primary_key=True, default=random_string) has_upvoted = models.ManyToManyField(User, related_name="has_upvoted") has_downvoted = models.ManyToManyField(User, related_name="has_downvoted") and a PostScore model: class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') Because I recently changed the id on my Post model from the default id = models.AutoField(primary_key=True) to the current CharField, it's causing this error when I run migrate: django.db.utils.ProgrammingError: foreign key constraint "post_post_has_downvoted_post_id_3b2ec618_fk_post_post_id" cannot be implemented DETAIL: Key columns "post_id" and "id" are of incompatible types: integer and character varying. Any idea how I can fix this? -
Why am I getting this error in django project ?`
So I am working on user authentication, login, logout. I am getting the error when I am opening the registration portal. AttributeError at /profile/ 'User' object has no attribute 'get_profile' Following is my views.py def Registration(request): if request.user.is_authenticated: return HttpResponseRedirect('/profile/') if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user(username = form.cleaned_data['username'],email = form.cleaned_data['email'] , password = form.cleaned_data['password']) user.save() UserProfile= UserProfile(user=user, birth_date=form.cleaned_data['birth_date',]) UserProfile.save() return HttpResponseRedirect('/profile/') else: return render('visit/registration/register.html', {'form': form},) else: form= LoginForm() context = {'form': form} return render(request, 'visit/registration/register.html', context ) @login_required def Profile(request): if not request.user.is_authenticated: return HttpResponseRedirect('/login/') UserProfile = request.user.get_profile() context ={'UserProfile': UserProfile} return render(request,'visit/profile.html', context) def LoginRequest(request): if request.user.is_authenticated: return HttpResponseRedirect('/profile') if request.method == 'POST': form = LoginRequest(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] UserProfile = authenticate(username=username, password=password) if UserProfile is not None: login(request, UserProfile) return HttpResponseRedirect('/profile/') else: return render(request,'visit/registration/login.html',{'form':form}) else: return render(request, 'visit/registration/login.html', {'form': form}) else: form= LoginForm() context = {'form': form} return render(request, 'visit/registration/login.html', context, ) def logoutRequest(request): logout(request) return render(request, 'visit/login.html') def index(request): return render(request, 'visit/index.html', context=None) I am not sure what/where the error is. I am using the Django 2.0.2. I know there are similar questions but I am not getting the proper solution. Help would be appricated. … -
Why NoReverseMatch at occurred on django 2.0
Error says : Reverse for 'list' not found. 'list' is not a valid view function or pattern name. My code are on below. html template where error is in: {% block more_posts %}<button type="button" href="{% url 'website:list' %}">more posts</button>{% endblock %} my_project/urls.py: urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^', include('website.urls')), ] website/urls.py: app_name = 'website' urlpatterns = [ re_path(r'^about/$', TemplateView.as_view(template_name='website/about.html'), name='list'), re_path(r'^$', views.main, name='main'), ] Is there are something wrong with my url namespace settings? -
Adding a Non-Primary Key AutoField or a 'serial' field in a Django Model which uses a UUID field as a Primary Field
I am building a Model with a UUIDField as the Primary Key. But my use case requires. having an Auto Increment field as well. Django provides an AutoField. But it is required to have primary_key=True which in my case something I don't want as I am using the UUIDField as primary_key. I tried creating a field and giving db_type of 'serial' and adding a migration which alters the sequence to restart at 100000.. Adding an object to the database using the Admin will always store the number field as null value. and if I remove null=True. Then the save will fail as it will require a value for the number field. How can I make the number field incremental while keeping the UUIDField as a primary key ? fields.py class SerialField(models.Field): description = _("BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE") empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value must be an integer."), } def __init__(self, *args, **kwargs): kwargs['blank'] = True super().__init__(*args, **kwargs) def db_type(self, connection): return 'serial' models.py from .fields import SerialField class MyModel(models.Model): uuid = models.UUIDField( verbose_name=_("UUID Identifier"), primary_key=True, default=uuid.uuid4, editable=False, help_text=_("Requried, PrimaryKey none-editable"), db_index=True, ) number = SerialField( primary_key=False, editable=False, help_text=_("Auto Increment Number"), verbose_name=_("Number"), #null=True ) 0002_auto_20180202.py from … -
NameError: name 'hello_world' is not defined
Using pycharm community python3.6.2 Django 2.0.3enter image description here enter image description here i Tried to figure it out but missing something. #helpneed -
how to hide password using asterisks while giving a response to api request in django?
I know that some may say that there is no need to provide password in api-response if i have to hide it. but the point is, even if i go to admin section, i can see the password hash value, that's why i'm doing this. Note: I have a custom model for my data. i just need a function and where to put it to work. models.py from django.db import models from django.contrib.auth.hashers import make_password class MyUser(models.Model): full_name = models.CharField(max_length=128) profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True) username = models.CharField(max_length=128, unique=True) birth_date = models.DateField(blank=True) gender = models.CharField(max_length=10, blank=True) password = models.CharField(max_length=255) contact = models.CharField(max_length=15, blank=True) email = models.CharField(max_length=100, unique=True) time_stamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.username def save(self, *args, **kwargs): if not self.pk: self.password = make_password(self.password) super(MyUser, self).save() -
Django-Paypal IPNs flagged Duplicate txn_id in Django admin
I have implemented Paypal integration in my Django app using Django-paypal and along with that, I have setup signal receivers according to the documentation. But the problem is: everytime when someone makes a payment it is flagged as duplicate even I'm passing a random invoice id along with paypal dictionary. Here's what I have tried: From views.py: def generate_cid(): chars = "".join([random.choice(string.ascii_lowercase) for i in range(5)]) digits = "".join([random.choice(string.digits) for i in range(4)]) cid = digits + chars return cid def payment_process(request): minutes = int(request.user.tagging.count()) * 5 testhours = minutes / 60 hours = '' if request.user.tagging.count() > 11: # hours = str(round(testhours, 3)) hours = 5 # invoice = generate_cid() user_info = { "name": str(request.user.first_name + ' ' + request.user.last_name), "hours": str(hours), "taggedArticles": str(request.user.tagging.count()), "email": str(request.user.email), "date": str(datetime.date.today()), } paypal_dict = { "business": settings.PAYPAL_RECEIVER_EMAIL, "item_name": "Certificate of Completion", "custom": json.dumps(user_info), "invoice": str(generate_cid()), "amount": "95.00", "currency_code": "USD", "notify_url": settings.host + '/users/paypal', "return_url": settings.host + "/users/done/", "cancel_return": settings.host + "/users/cancel/", } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "users/generateCert.html", context) From signals.py: def show_me_the_money(sender, **kwargs): ipn_obj = sender # Undertake some action depending upon `ipn_obj`. if ipn_obj.payment_status == ST_PP_COMPLETED: print('Payment is completed') user_infor = ast.literal_eval(ipn_obj.custom) …