Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelForm exclude data saving
Trying to save data with login user. Tried as below. models.py class MyModel(TimeStamped): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=250) forms.py class MyForm(forms.ModelForm): class Meta: model = MyModel exclude = ['user'] views.py def add(request): if request.method == 'GET': form = MyForm() else: form = MyForm(request.POST, request.FILES) if form.is_valid(): form.save(commit=False) form.save() messages.success(request, 'Message Sent Successfully') redirect('home') return render(request, "add.html", {'form': form}) It saved data. But problem is user is not setting to login user. Tried adding in view form.user = request.user. still is not saving. -
Django REST Framework - How to use signal post_save to have a simple create_user method
I am new to Django and want to extend my user model with OneToOne field (seems its mostly recommended), also I have a ManyToManyField which is mandatory. Below is my models.py : from django.db import models from django.contrib.auth.models import User from django.contrib.postgres.fields import ArrayField from django.db.models.signals import post_save from django.dispatch import receiver class Config_Table(models.Model): entity_name = models.TextField(primary_key=True) category = models.TextField() description = models.TextField(blank=True,default='') class Profile(models.Model): "The Profile of a user with details are stored in this model." user = models.OneToOneField(User, on_delete=models.CASCADE, max_length=11) # The default username is phone number (Ver. 1.0) phone_number = models.TextField(max_length=11,default=user) avatar = models.ImageField(default='../Static/1.jpeg') GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ) gender = models.CharField(max_length=1,choices=GENDER_CHOICES) city = models.TextField(max_length=25) description = models.TextField(max_length=2000, blank=True, default='') interests = models.ManyToManyField(Config_Table) date_of_birth = models.DateField(auto_now_add=True) USER_TYPES = ( ('User','Normal User'), ('Leader','Tour Leader'), ('Admin','Administrator'), ) user_type = models.TextField(choices=USER_TYPES, default='User') join_date = models.DateTimeField(auto_now_add=True) official_docs = models.ImageField(default='../Static/1.jpeg') group_name = models.TextField(blank=True,default='') debit_card_number = models.IntegerField(blank=True, default=0) MUSIC_CHOICES = ( ('Rock','Rock Music'), ('Trad','Traditional Music'), ('Elec','Electronic Music'), ('Clas','Classical Music') ) favorite_music = ArrayField(models.TextField(null=True,default=''),size=2) Using shell, I can successfully create a user and assign a profile like below. The table "Config_table" has been populated with some initial data : >>> user = User.objects.create_user(username='12345678900') >>> test = Profile.objects.create(user=user,gender='M',city='NY',user_type='User',favorite_music=['Trad']) >>> test.save <bound method Model.save of … -
Non-breaking space with Django template code and Bootstrap 4 badges
I am trying to keep text generated with Django template language which is contained within a Bootstrap 4 badge together with some additional text that is not contained in the badge. Here is my code: <span>Submitted&nbsp;by:&nbsp;<span class="badge badge-primary">{{ user.username }}</span></span> I want all the words in the phrase "Submitted by USER" to always be on the same line, but the code above does not achieve that. Any idea what is wrong? Thank you. -
DRF: a way to default UserProfile field in serializer?
Using current User model in your serializers is easy: user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) but what if I have my own UserProfile model and I want to use current UserProfile in a serializer. Just doing CurrentUserDefault().profile does not work of course because at this point this is an empty object. -
Django: TemplateDoesNotExist at /login/ (Source Does Not Exist)
I'm trying to get into Django and I'm following tutorials here and there. I'm trying to add a login page to the polling app from the official Django tutorial but even though I'm following this simple tutorial to the letter I get the TemplateDoesNotExist error. From what I can tell though, Django is looking for login.html in the correct directory and gives the message Source doesn't exist. My file structure: ├── db.sqlite3 ├── manage.py ├── secvot │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── templates │ │ ├── admin │ │ │ └── base_site.html │ │ └── registration │ │ ├── login.html │ │ └── logout.html │ ├── urls.py │ ├── urls.pyc │ ├── wsgi.py │ └── wsgi.pyc └── voting ├── admin.py ├── admin.pyc ├── apps.py ├── apps.pyc ├── __init__.py ├── __init__.pyc ├── migrations │ ├── 0001_initial.py │ ├── 0001_initial.pyc │ ├── 0002_auto_20180301_2354.py │ ├── 0002_auto_20180301_2354.pyc │ ├── __init__.py │ └── __init__.pyc ├── models.py ├── models.pyc ├── static │ └── voting │ ├── images │ │ └── background.gif │ └── style.css ├── templates │ └── voting │ ├── detail.html │ ├── index.html │ └── results.html ├── tests.py ├── tests.pyc ├── urls.py ├── urls.pyc ├── … -
django createviw- create another model object and use it in current model
I have two models as given below. class Account(models.Model): ASSET='A' LIABILITY='L' INCOME='I' EXPENSE='E' ACCOUNT_TYPE=((ASSET,'Asset'), (LIABILITY,'Liability'), (INCOME,'Income'), (EXPENSE,'Expense')) name=models.CharField(unique=True,db_index=True,max_length=70) type=models.CharField(choices=ACCOUNT_TYPE,max_length=1) class Person(models.Model): first_name=models.CharField(max_length=30,) last_name=models.CharField(max_length=30,) account=models.OneToOneField(Account,on_delete=models.CASCADE) The Person model has the following CreateView and a model form. class CreatePerson(CreateView): model=Person form_class=CreatePersonForm class CreatePersonForm(forms.ModelForm): display_name=forms.CharField() class Meta: model= Person fields = ['first_name','last_name','display_name'] When creating a new Person, I need to create an Account object first (with name=display_name, type='A') and need to assign it to the Person object. render the form again if the Account with same display_name already exists, with a validation error. Could someone please point the right direction to proceed here? Thanks. -
Django model foreign key or onetoone?
I have 3 table in my project, the first one is the default user table od django with username password, firstname and last name fild the second one is the userprofile and third is stocks the user could be seller or buyer. class Stocks(models.Model): user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(blank=True,null=True,max_length=64,verbose_name=_('number')) brand=models.CharField(max_length=64, validators=[ RegexValidator(regex='^[A-Z]*$',message=_(u'brand must be in Capital letter'),)] ,verbose_name=_('brand')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) checking= ((_('pending'),_('pending')), (_('reject'),_('reject')), (_('approved'),_('approved')), (_('expired'),_('expired')), ) confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending')) def __str__(self): return str(self.name) class Meta: verbose_name=_('Stock') verbose_name_plural=_('Stocks') def get_absolute_url(self): return reverse('BallbearingSite:mystocks' ) class UserProfileInfo(models.Model): user=models.OneToOneField(User,related_name='profile') phone_regex = RegexValidator(regex=r'^\d{11,11}$', message=_(u"Phone number must be 11 digit.")) cellphone = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('cellphone')) tel = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('tel')) state=models.CharField(validators=[farsi_regex],max_length=128,verbose_name=_('state')) city=models.CharField(validators=[farsi_regex],max_length=128,verbose_name=_('city')) address=models.CharField(validators=[farsi_regex],max_length=264,verbose_name=_('address')) def __str__ (self): return self.user.username class Meta: verbose_name=_('UserProfileInfo') verbose_name_plural=_('UserProfileInfos') the buyer should be able to select stocks to buy which the seller has defined .so i should have seller id, buyer id and stock id in my fourth table which refers to the user table and the stock table . i want to know which field should be defined as onetoone and which one as foreign key ? and how can i define that it refer to id of the user and id of the stock in their table ? is it correct : … -
How to limit field access on a model based on user type on Graphene/Django?
Let's say I have a model: class Employee(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=60) salary = models.DecimalField(decimal_places=2) I want anyone to be able to access first_name and last_name but only want certain users to be able to read salary because this is confidential data. And then I want to restrict write/update for salary to an even different kind of user. How do I restrict field read/write/update depending on the request user? -
Json on django template
I am making a website ran into a problem. I am sending a json data from views.py to my template to print each attribute value from json data but the data showing is empty. data= { "philip":{"age":20,"salary":10000}, "jerry":{"age":27,"salary":30000} } names = ["philip","jerry"] return render(request, 'profiler/livetransaction.html',{'data':data,'names':names}) I store the names from json data in list and sending both data and names to template. <div class="col-sm-3"> {% for name in names %} {{ data.name }} {% endfor %} </div> -
Display multiple chart.js charts using for loop in Django template
I have a Django template in which I want to display: some data 1 a chart of data 1 some data 2 a chart of data 2 some data 3 a chart of data 2 I have a Django template loop in my HTML which displays the data, and then a canvas for displaying each chart. The data displays correctly, and I can get it to display the first chart. What I can't figure out is: How do I get it to display more than one chart? At the moment it displays the first chart but not subsequent charts - I think maybe because the canvas id is always the same in each iteration? Template {% for session_data in ratings_by_theme %} {{ session_data }} <div class="myChart"> <canvas id="myChart" width="600" height="400"></canvas> <script> var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for label in chart_session_labels %} '{{ label }}', {% endfor %}], datasets: [{ label: "Teacher", data: {{ teacher_chart_data }}[{{ forloop.counter0 }}], backgroundColor: 'rgba(255, 99, 132, 0.4)', borderColor: 'rgba(255,99,132,1)', borderWidth: 1 }, { label: "Parent", data: {{ parent_chart_data }}[{{ forloop.counter0 }}], backgroundColor: 'rgba(255, 206, 86, 0.4)', borderColor: 'rgba(255, 206, 86, 1)', borderWidth: 1 }, … -
Fetch data "with Elasticsearch dsl" Vs "with Django Rest Framework"
I'm working on a Django Rest Framework project. I successfully implemented Elasticsearch 5.5 with my prject. I indexed and synced all my models with Elasticsearch. Now I can fetch my data with Elasticsearch (and make search on it) and with Django rest framework. I want to know what is better to fetch data. Thx -
How add follow button to profile in django getstream
I try to add follow button in django with Getstream.io app. Following the getstream tutorial, django twitter, I managed to create a list of users with a functioning follow button as well as active activity feed. But when i try add follow button on user profile page, form send POST but nothing happends later. I spend lot of time trying resolve this, but i'm still begginer in Django. Code: Follow model: class Follow(models.Model): user = models.ForeignKey('auth.User', related_name = 'follow', on_delete = models.CASCADE) target = models.ForeignKey('auth.User', related_name ='followers', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add = True) class Meta: unique_together = ('user', 'target') def unfollow_feed(sender, instance, **kwargs): feed_manager.unfollow_user(instance.user_id, instance.target_id) def follow_feed(sender, instance, **kwargs): feed_manager.follow_user(instance.user_id, instance.target_id) signals.post_delete.connect(unfollow_feed, sender=Follow) signals.post_save.connect(follow_feed, sender=Follow) Views: def user(request, username): user = get_object_or_404(User, username=username) feeds = feed_manager.get_user_feed(user.id) activities = feeds.get()['results'] activities = enricher.enrich_activities(activities) context = { 'user': user, 'form': FollowForm(), 'login_user': request.user, 'activities': activities, } return render(request, 'profile/user.html', context) Forms: class FollowForm(ModelForm): class Meta: exclude = set() model = Follow Urls: path('follow/', login_required(views.follow), name='follow'), path('unfollow/<target_id>/', login_required(views.unfollow), name='unfollow'), And user.html <form action="{% if request.user in User.followers.all %}{% url 'unfollow' target.id %}{% else %}{% url 'follow' %}{% endif %}" method="post"> {% csrf_token %} <input type="hidden" id="id_target" name="target" value="{{target.id}}"> <input type="hidden" id="id_user" name="user" value="{{user.id}}"> … -
DjangoCMS - how do i match my html projects templates to DjangoCMS pages?
i'm trying to integrate djangoCMS to my django website but after selecting a page on the DjangoCMS templates down, the rendered page does not show the placeholders in the structure view, it just displays an empty sidebar, can someone help me please? -
Can't send post request from vue to django app server
i can send get request to my server and get results , but when i send post request it give me error 400 (Bad Request) -
I need to store media and static files for my Django project... Can I store these on Google drive?
Very weird question but a club in my college has requested a website/ portal for their members... And they don't want to pay for hosting or data storage. Heroku solves my hosting issues but there's the user-uploaded media files like avatars and images that I need to store. I have 10 gigs of storage on my Google Drive, is there any way I can use this space for media and static files? -
Django Rest Framwork: Best way to override model creat() method
I want to override the create () method of my model. I use the django-restframework. What is the best way to override the method? I thought it's a good idea to overwrite parts of the model.manager, but this does not seem to work. When I create an object through a POST request, my create () method is not called. The reason I want to override the method is that the model should only be an API endpoint. There should never be an db-instance created by the model. Instead, a file with the data should be createde, which is stored in another model. This is my code: The Model: class StudentEditorUpload(models.Model): student_solution = models.ForeignKey(StudentSolution, on_delete=models.CASCADE) file_name = models.CharField(max_length=30) file_content = models.CharField(max_length=5000) objects = StudentEditorUploadManager The Manager: class StudentEditorUploadManager(models.Manager): def create(self, *args, **kwargs): print('CREATE CALLED') if not 'student_solution' in kwargs: raise ValueError('Upload must hava a valid StudentSolution') if not ('file_name' in kwargs or isinstance(kwargs['file_name'], str)): raise ValueError('File must have a valid name') if not ('file_content' in kwargs or isinstance(kwargs['file_content'], str) or (len(kwargs['file_content']) > 0)): raise ValueError('File must have a valid content a not empty') sfu = StudentFileUpload(student_solution=kwargs['student_solution']) sfu.file_upload.save(kwargs['file_name'], ContentFile(kwargs['file_content'])) sfu.save() return The Serializer: class StudentEditorUploadViewSet(viewsets.ModelViewSet): queryset = StudentEditorUpload.objects.all() serializer_class = StudentEditorUploadSerializer def … -
How to get and save the initial value of a property before its subsequent changes
I have a shopping cart and there is a method of adding and updating the quantity of goods in it def add(self, item, quantity=1, update_quantity=False): item_id = str(item.id) if item.discount > 0 : price_in_cart = item.get_price_with_discount() else: price_in_cart = item.price z = int(item.quantity) # ???? if item_id not in self.cart: self.cart[item_id] = {'quantity': 1, 'counter' : 0, 'price': str(price_in_cart)} if update_quantity: self.cart[item_id]['quantity'] = quantity item.quantity = z - self.cart[item_id]['quantity'] else: self.cart[item_id]['quantity'] = 1 item.quantity = z - self.cart[item_id]['quantity'] item.save() self.save() I, on the one hand, need to subtract from the warehouse the amount of goods in the basket and store the result. On the other hand, at the moment, this works incorrectly, because As with each update of the quantity, the value decreases. If in z comes the values of the quantity of goods one pa and will not change, then everything works. But this is a link. How can I freeze it? Probably my question is too stupid and simple, but I still do not get it. Thanks! -
How allow HTMLField in Django Admin and reflect that on the template?
I have a Django app with this model: class Dorm(models.Model): dorm_name = models.CharField(max_length=50, help_text="Enter dorm name") dorm_description = models.TextField(max_length=1000, help_text="Enter dorm description") This model has been added to the Django Admin: class DormAdmin(admin.ModelAdmin): list_display = ('dorm_name','dorm_room_count','dorm_caretaker','dorm_contact_no','dorm_availability') list_filter = ('dorm_room_count','dorm_caretaker','dorm_availability','dorm_date_added') fieldsets = ( (None, {'fields': ('dorm_name', 'dorm_description', 'dorm_primary_picture', 'dorm_room_count')}), ('Contact Details', {'fields': ('dorm_address','dorm_caretaker','dorm_contact_no','dorm_contact_email')}), ('Date',{'fields': ('dorm_date_added','dorm_availability','dorm_date_updated')}), ('Others',{'fields': ('dorm_house_rules',)}), ) I pulled that dorm_description using this in the template: <div class="amenities"> <div class="titlediv">About this dorm</div> <h5 class="padding-bottom">{{ dorm.dorm_description }}</h5> </div> However, in the template it is not displaying the line breaks as I have done in the Django Admin. It is wrapping everything up and ignoring the linebreaks. Can anyone help? Here are the screenshots: Django App Display: enter image description here Django Admin Display: enter image description here -
Form boolean attribute won't change value after submission
I was building a form for file uploads that is only visible to a student type of account. And I wanted that after the student submits the form, it will not show a second time, so in my Student model I used a boolean for that. After submission it will become true and the form should not appear again. Problem is, the boolean doesn't change value, so I think there is something wrong with the view. class StudentFileUpload(models.Model): course = models.ForeignKey("Course", related_name='files', on_delete=None, default=None) files = models.FileField(upload_to='student_files', null=True, blank=True) comment = models.CharField(max_length=100, blank=True) user = models.OneToOneField('courses.User', on_delete=models.CASCADE, primary_key=True, blank=True, default=None) def __str__(self): return str(self.files) def file_link(self): if self.files: return "<a href='%s'>download</a>" % (self.files.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')], null=True, blank=True, default=None) photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None) phone = models.CharField(max_length=15, null=True, blank=True, default=None, validators=[RegexValidator(regex='^[a-zA-Z0-9+]+$', message='Not a valid phone number.')], ) file_status = models.BooleanField(default=False) {% if user.is_student %} {{ … -
URL to a Map that is created with MapFile in MapServer?
I have installed MapServer, I have followed the whole introduction on MapServer site, I have created a Map file for a shapefile that I want to show, BUT: HOW DO I FIND URL WHERE MY MAP IS BEING SHOWN? I have watched some tutorials, but no one explains how to open web page where a map defined in mapfile is being shown. Could anyone explain this to me? -
Django prefetch_related cache not reflecting the changes
I have a model "Banks". and I have 6 entities in it. This is my prefetch code. `queryset = Banks.objects.all().prefetch_related('field1','field2')` when I enter new entity into my Banks model and get the data, I still get only the old data. The newly added entity is not getting reflected when I download the data. -
Communication models of different applications
As when adding the model object of the first application, make it added as another model in the second application with the properties of the first object. # firstApp.models class itemInShop(models.Model): name = models.CharField(blank=True, null=True, max_length=100) slug = models.SlugField(blank=True, null=True) url = models.CharField(blank=True, null=True, max_length=100,editable=False) descr = models.TextField(blank=True, null=True, max_length=5000) title = models.CharField(blank=True, null=True, max_length=100) text = models.TextField(blank=True, null=True, max_length=5000) propertiesManufacturer = models.BooleanField(default=False) propertiesType = models.BooleanField(default=False) propertiesPrice = models.BooleanField(default=False) propertiesPower = models.BooleanField(default=False) propertiesAmount = models.BooleanField(default=False) The output should be about this code. Is it possible? class Pech(models.Model): name = models.CharField(blank=True, null=True, max_length=100) manufacturer = models.CharField(max_length=100, choices=CHOICES_PECHI_MANUFACTURER, blank=True, null=True) type = models.CharField(blank=True, null=True, max_length=100, choices=CHOICES_PECHI_TYPE) price = models.PositiveIntegerField(blank=True, null=True) power = models.FloatField(blank=True, null=True) -
ModuleNotFoundError: No module named 'blogdjango'
I am getting this error when trying to run server: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001FD20F4F510> Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blogdjango' I do not have a module named 'blogdjango' anywhere. This is getting out of my hands. Please help me out here. -
Getting Value of Selected Nav Pill
I'm trying to make a pair of nav pills to choose between a graphical and a tabular output for a set of data and I can't seem to figure out how to grab the value of the nav pill. I defined the nav pills as follows: <div class="col-md-2"> <ul class="nav nav-pills nav-stacked"> <li {% if type_display == 'charts' %}class="active"{% endif %}><a href="charts" class="text-primary"><i class="fa fa-fw fa-bolt"></i> Charts</a></li> <li {% if type_display == 'tables' %}class="active"{% endif %}><a href="tables" class="text-primary"><i class="fa fa-fw fa-calendar"></i> Tables</a></li> </ul> and they render like this: How do I pass the selected nav pill back to django? I tried: display_type = request.GET.getlist('charts') I have next to no experience in HTML so any info would be awesome. Thank you! -
Django "dirty-edit" file manager issue
I need something simple to edit files on my server from the admin interface. I found this application https://github.com/synw/django-dirtyedit and followed all the stes to install it and it seemed fine at first sight but when I try to add any file I get this error: What could I do to make it work? Or maybe there is something better? Thanks.