Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I integrate my ReactJs with django website to RazorPay?
I want to create a payment gateway for a competition but I don't know how to add a rozarpay payment gateway on my django+reactjs app? -
How should I return usernames instead of id inside Django Rest Framework API?
This is my model. class FollowerModelSerializer(ModelSerializer): user = CharField(source='slug') class Meta: model = Profile fields = ['user', 'followers'] This is the serializer. class FollowerModelViewSet(ModelViewSet): queryset = Profile.objects.all() serializer_class = FollowerModelSerializer allowed_methods = ('GET', 'HEAD', 'OPTIONS') def list(self, request, *args, **kwargs): self.queryset = self.queryset.filter(id=request.user.id) return super(FollowerModelViewSet, self).list(request, *args, **kwargs) And this is the API. This is the response : HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "user": "pop", "followers": [ 1, 4 ] } ] Problem: It's returning the IDs of the followers. How should I make it return the usernames of the followers instead? -
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'accounts.user', but app 'accounts' isn't installed version3.1.1
django version 3.1.1: hey there, I just created a new project, then I create a new app called "pages" then added to the installed apps. but when I run either makemigrations or migrate I got the error: I didn't do anything except adding the app to the installed app. maybe the error is b/c the Django version or maybe not. I didn't even create an app called accounts, so I really confuse about the error. no code, just a new project setup. The full error log is below Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Python37\lib\site-packages\django\core\management\commands\makemigrations.py", line 168, in handle migration_name=self.migration_name, File "C:\Python37\lib\site-packages\django\db\migrations\autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "C:\Python37\lib\site-packages\django\db\migrations\autodetector.py", line 128, in _detect_changes self.old_apps = self.from_state.concrete_apps File "C:\Python37\lib\site-packages\django\db\migrations\state.py", line 212, in concrete_apps self.apps = StateApps(self.real_apps, self.models, ignore_swappable=True) File "C:\Python37\lib\site-packages\django\db\migrations\state.py", line 278, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The … -
create a signal in django
Good afternoon, I must pass on to my method of creating the signal if I want to create a notification. from django.contrib.auth.models import User from django.db.models import signals from django.dispatch import receiver from .models import Notification, Follower def new_follower(sender, instance, created, **kwargs): if created: Notification.objects.create(notification__user = instance) signals.post_save.connect(new_follower, sender=Follower, dispatch_uid=" user_new_follower") -
Pass hits from django-hitcount to model serializer
I am using django-hitcount to track hits on my model. I would like to pass the data from the hits to an API through a serializer. This is how i am doing it currently on my serializer using serializer method field but i am getting nulls hotel_hits = serializers.SerializerMethodField() "policies", 'hotel_type_id', 'hotel_hits', def get_hotel_hits(self, obj): try: return obj.hit_count.hits except: pass What could i be doing wrong? -
Trying to Runserver (w/GDAL) and GDAL ERROR Preventing Site From RUNNING
I hope you all are having a good day. I have been doing this tutorial on RealPython https://realpython.com/courses/make-location-based-web-app-django-and-geodjango/ The TUtorial includes running a virtual environment and installing QGIS, as this app is 'location-based' I am at the 'Create the "nearby shops" App' section of the tutorial, and it asks for me to 'runserver' However when I runserver, I am getting in response<: PS C:\Users\Jamal Ford\desktop\geoshops> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Jamal Ford\AppData\Local\Programs\Python\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 955, in … -
send a email after user data is saved Django
i want to send email to user after data is saved how do i pass the data like "first_name" to the email function how do i pass the data without data i have able call the email function its working. from Email import views as em @api_view(['GET', 'POST']) @permission_classes((IsAuthenticated, )) def CustomerAPI(request): if request.method == 'GET': snippets = Customer.objects.all() serializer = CustomerSerializer(snippets, many=True) return Response({"Customer_List": serializer.data}) elif request.method == 'POST': serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() #em.email_send1(request, first_name='SOURABH', middle_name='k', last_name='SAIKIA') #response = em.email_send1(request=request._request).data response = em.email_send1(request=request._request.POST["first_name"]="sourabh").data return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django.db.utils.IntegrityError: UNIQUE constraint failed: main_produit.exposition_sante_id (Django)
Bonjour, j'essaie de creer un script qui charge des données d'un fichier csv vers mes modèles de Données sur Django. voici une partie de mes classes de données class Exposition_Sante(models.Model): Note_Sante = models.DecimalField(max_digits=4, decimal_places=2, null=True) Avis_Expert = models.TextField(null=True) class Exposition_Environement(models.Model): Note_Env = models.DecimalField(max_digits=4, decimal_places=2, null=True) Avis_Expert = models.TextField(null=True) class Produit(models.Model): Sans_NGS = models.CharField(max_length=50) Taux = models.CharField(max_length=50, null=True) Famille = models.CharField(max_length=50) Nom_Commercial_FDS = models.CharField(max_length=50) MPE = models.DecimalField(max_digits=5, decimal_places=2) Achete_sur_les_3_dernieres_années = models.CharField(max_length=50, null=True) NIP = models.CharField(max_length=50) NGS = models.CharField(max_length=5, null=True) CAS_des_ingredients_du_NGS = models.CharField(max_length=50, null=True) Nom_du_CAS = models.CharField(max_length=50, null=True) Substance_Impurete_ou_Produit_Degredation = models.CharField(max_length=50, null=True) danger_sante = models.OneToOneField(Danger_Sante, on_delete=models.CASCADE, null=True) danger_environement = models.OneToOneField(Danger_Environement, on_delete=models.CASCADE, null=True) exposition_sante = models.OneToOneField(Exposition_Sante, on_delete=models.CASCADE, null=True) exposition_environement = models.OneToOneField(Exposition_Environement, on_delete=models.CASCADE, null=True) et voici une partie de mon script: exposition_sante, _ = models.Exposition_Sante.objects.get_or_create( Note_Sante = row["santé 1"], Avis_Expert = row["Avis d'expert2"] ) exposition_environement, _ = models.Exposition_Environement.objects.get_or_create( Note_Env = row["santé 1"], Avis_Expert = row["Avis d'expert2"] ) produit, _ = models.Produit.objects.get_or_create( Sans_NGS = row["sans NGS"], Taux = row["taux"], Famille = row["Famille"], Nom_Commercial_FDS = row["nom commercial FDS"], MPE = row["MPE"], Achete_sur_les_3_dernieres_années = row["acheté sur les 3 dernières années"], NIP = row["NIP (avec 0)"], NGS = row["NGS"], CAS_des_ingredients_du_NGS = row["CAS des ingrédient du NGS"], Nom_du_CAS = row["nom du CAS"], Substance_Impurete_ou_Produit_Degredation = row["substance, impureté ou produit dégradation … -
connect django to mysql on shared hosting
I want to use mysql server in my django project and this was my database setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ... } } but this engine needs mysqlclient and i can't install it on shared host. because i need superuser access to fix some issues. So i decided to use: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', ... } } however, this engine has some bugs!! when i wanna get a row from database, it doesn't return boolean columns(return None instead). now i want to know if there is another engine for this or any other idea to solve it?? django==2.0 python==3.6 -
Form is not saving in database when submitted
I am working on a project on Django, where user can input values on form and submit using POST request. When form is submitted, datas are not saved in database. How do I implement save data when form is submitted. Models: class DataInfo(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) beneficiary_name = models.CharField(max_length=250, blank=True) beneficiary_bank_name = models.CharField(max_length=250, blank=True) beneficiary_account_no = models.CharField(max_length=250, blank=True) beneficiary_iban = models.CharField(max_length=250, blank=True) beneficiary_routing_no = models.CharField(max_length=250, blank=True) amount = models.IntegerField(blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'DataInfo' verbose_name_plural = 'DataInfo' ordering = ['-date'] '''Method to filter database results''' def __str__(self): return self.user.username Views: @login_required def TransferView(request): form = DataForm(request.POST) if request.method == "POST": if form.is_valid(): pp = form.save(commit=False) pp.user = request.user pp.save() return redirect('site:transfer_cot') else: form = DataForm() context = { 'form':form } return render(request, 'transfer.html', context) Forms: class DataForm(forms.ModelForm): class Meta: model = DataInfo fields = ('beneficiary_name', 'beneficiary_bank_name', 'beneficiary_account_no', 'beneficiary_iban', 'beneficiary_routing_no', 'amount') Template: <form method="POST" action="{% url 'site:transfer_cot' %}"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-secondary">Submit</button> </form> -
How to filter a form based on a DateTimeField using timedelta
I have the following model for Sessions: courses/models.py: class Session(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_date_start = models.DateTimeField() course_date_end = models.DateTimeField() is_in_session = True def session_id(self): new_session_date = self.course_date_start.strftime('%Y') return f'{new_session_date}{self.course.number}{self.pk}' def __str__(self): return f'{self.course.number} - {self.course.title} - {self.session_id()}' And in my users/forms.py: class EnrollStudentInCourseForm(forms.Form): global roster_limit student = forms.ModelChoiceField(queryset=Student.objects.all()) courses=SessionRemainingSlotsForm(queryset=Session.objects.annotate(num_students=Count('student')).filter(num_students__lt=roster_limit)) I'd like to filter out the fields so that it only shows sessions where course_date_start plus a week, to cover a student joining the class a little late. -
can't log_in in the django admin panel with custom user model
I have created a custom user model in django. Everything is working fine, just can't login at the admin panel. here is my code. models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone class User_Manager(BaseUserManager): def create_user(self,username, email, password=None): if not email or not username: raise ValueError("Users must provide username & email address") user = self.model( username = username, email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,username, email, password=None): user = self.create_user( username, email, None ) user.isSuperuser = True user.isStaff = True user.save(using=self._db) return user class User_Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=50, unique=True, ) first_name = models.CharField( max_length=20, ) last_name = models.CharField( max_length=10, ) username = models.CharField( max_length=20, unique=True ) isStaff = models.BooleanField( default=False, null=True, ) isActive = models.BooleanField( default=True ) isSuperuser = models.BooleanField( default=False ) date_joined = models.DateTimeField( default=timezone.now ) objects = User_Manager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [ "email", ] def __str__(self): return self.username def get_full_name(self): return " ".join([self.first_name, self.last_name]) def has_perm(self, perm, obj = None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.isStaff @property def is_active(self): return self.isActive @property def is_superuser(self): return self.isSuperuser admin.py: from django.contrib import admin from django import forms from django.contrib.auth.models import Group from … -
Issue using Django api for bulk creating and updating records by csv
New to django and working on bulk creating and updating rows in my database using csv. I am using this: Https://pypi.org/project/django-bulk-update-or-create/#description I can get the first option: bulk_update_or_create working fine but when I use the bulk option: bulk_update_or_create_context it uploads data into my database but as numbers only (example below) - I am missing something really obvious here but I cannot figure it out. I would be expecting data like this for example (and its what I get using the first option bulk_update_or_create: vsim_iccid - 8997103118112597732F (pk) country_or_region - AE_UNITED ARAB EMIRATES operator - DU vsim_imsi - 424030246932624 online_country - AE sim_status - Enable, plmn_set - 42403 package1 - UAE 50 package2 - blank instead I get this when I use the bulk option bulk_update_or_create_context: vsim_iccid - 1 country_or_region - 21 vsim_imsi - 21 online_country - 21 sim_status - 21 plmn_set - 21 package1 - 21 package2 - 21 code: def upload_vsim_mgmt(request): form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm() obj = Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: df = pd.read_csv(f, encoding='latin1', error_bad_lines=False, index_col=False, dtype='unicode', sep=',').replace(np.nan, '', regex=True).replace("\t", '', regex=True) #print(df) row_iter = df.iterrows() items = [ VSIMData( country_or_region=row['Country or Region '], operator=row['Operator '], … -
How can I parse a field parameter using taggit custom tags?
Having in my project two apps that use tags, I wanted in my admin area to have these two groups of tags separated, so I followed the instructions of this thread. However I get a FieldError and a message: Cannot resolve keyword 'None' into field. Choices are: blogtags, id, name, post, slug. As it seems I have to parse 'blogtags' field as a parameter, but my poor experience in Django doesn't allow me to understand in which method do I have to do that. Any help is greatly appreciated. my models.py for the one of the two apps: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField from django.utils.text import slugify from taggit.managers import TaggableManager from taggit.models import TagBase, GenericTaggedItemBase class Category(models.Model): name = models.CharField(max_length=100, unique=True, primary_key=True) def __str__(self): return self.name class BlTagged(TagBase): class Meta: verbose_name = "Blog Tag" verbose_name_plural = "Blog Tags" class BlogTags(GenericTaggedItemBase): tag = models.ForeignKey(BlTagged, on_delete=models.CASCADE ) class Post(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField(blank=True, null=True, external_plugin_resources=[( 'youtube', '/static/vendor/ckeditor_plugins/youtube/youtube/', 'plugin.js', )]) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) is_published = models.BooleanField(default=True) slug = models.SlugField(unique=True, max_length=100, allow_unicode=True) category = models.ForeignKey('Category', default='uncategorized', on_delete=models.SET_DEFAULT, null=True) blogtags = TaggableManager(blank=True, through=BlogTags) … -
ValueError at /admin/login/ samesite must be "lax" or "strict"
Help, i'm new doing this :( i don't know how to solve this Error. I don't know how to solve this error that it throws at me in the browser. In Terminal, my project runs fine, but I don't know why that error appears in the browser :(. P.S. The project is already "working", it is in the process of improvements and I just cloned it from github to start adding changes. -
Getting UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte in Django unit test
I have a unit test where I want to test the post method of my view (which is a GenericViewSet) I want to be able to up load files in this post request. So I have this code: photo2 = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg') data = { 'foo_uid': foo_uid, 'bazz': 'bazz', 'photos': [{'photo': photo2, 'comment': 'pic of cats'}] } response = self.client.post(path=url, data=data, format="json") When the code runs the self.client.post() raises this error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I have seen a lot of answers for this question and they say to use open(..., 'rb') to read the file as binary. Well I am doing that but I still get this error. Thanks -
Can you please explain what is happening in this simple django function? formset=OrderFormSet(request.POST,instance=customer)
I am a beginner to django so I am trying to grasp the basic concepts...what happens at the formset=OrderFormSet(request.POST,instance=customer)? Does the formset get filled with some request.POST data? Does it get sent to server?Why is there the request.POST? def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields = ('product','status'), extra=10) customer=Customer.objects.get(id=pk) formset=OrderFormSet(queryset=Order.objects.none(),instance=customer) if request.method=='POST': formset=OrderFormSet(request.POST,instance=customer) if formset.is_valid(): formset.save() return redirect('/') context={'formset':formset} return render(request, 'accounts/order_form2.html',context) -
Redirect User After Login in Django
I am trying to implement my login page, so it can redirect to specific page in the websites. When the user click on the Login, it check if the user is staff, then send the user to admin page, not user then stay at login, if regular user, then send to regular user page. I haven't completed the LoginView yet because I just want to see if it can direct to admin page after login. I have researched online and tried many different way, but I couldn't figure out how to do so. What should I change or add in the urls.py or LOGIN_URL/LOGIN_REDIRECT_URL. Thank you! url.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('output/', views.output, name="output"), path('default_crawler/', views.default_page, name="default_page"), path('admin_page/', views.admin_page, name="admin_page"), path('regular_page/', views.regular_page, name="regular_page"), path('pass_forgot/', views.pass_forgot, name="pass_forgot"), path('pass_change/', views.pass_change, name="pass_change"), path('pass_change_success/', views.pass_change_success, name="pass_change_success"), path('pass_found/', views.pass_found, name="pass_found"), path('register/', user_views.register, name="register"), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py def LoginView(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user.is_staff: login(request, user) return redirect('admin_page') else: messages.error(request, "Invalid username or password") else: messages.error(request, "Invalid username or password") form = AuthenticationForm() return render(request, 'users/login.html', {'form': form}) settings.py LOGIN_URL … -
Displaying cards inside a responsive container with a grid of 3x3 initially
I'm trying with bootstrap and django to list cards inside a responsive container which in xl screen displays as a 3x3 grid container, has a scrollable overflow, and decreases according to device width. I tried to achieve this at first by wrapping the cards with a flex container with column-layout, but that's only a temporary and undesired solution, also i thought about rearranging cards through javascript upon window-resizing (but that's not optimal), or ... in other way using other techs like css-grid (which i don't know anything about how it works right now). So, what would be the best approach for this... Here i leave you guys a model i drew for this ocassion and serves as an explanatory to the main problem. CODE HERE JUST SERVES AS A TOOL FOR BETTER UNDERSTANDING... BUT IT'S NOT CRUCIAL: i have here one card.... let's say i put 12 instead. HTML <div class="card"> <div class="card-body"> <div class="card-img"> <img src="{% static 'library/img/attention.jpg' %}" class="history-img" alt=""> </div> <h6 class="card-subtitle"> Lorem ipsum dolor sit amet, co </h6> </div> <div class="card-footer"> <span class=""><i class="fas fa-eye"></i>4093</span> <span class=""><i class="fas fa-thumbs-up"></i>1234</span> <span class="badge bg-primary rounded-pill px-2">#hello_there</span> </div> </div> </div> </div> CSS body * { box-sizing: border-box !important; } … -
Django 3.0.7 - No Changes Detected after making Changes to Model
I am making changes to a model AppContactCnt to add new fields to handle deleting of records. Here is that models.py class AppContactCnt(models.Model): id_cnt = models.AutoField(primary_key=True) # idcst_cnt = models.IntegerField() idcst_cnt = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_cnt') idctp_cnt = models.ForeignKey(AppContactTypeCtp, models.DO_NOTHING, db_column='idctp_cnt') idtrp_cnt = models.IntegerField() name_cnt = models.CharField(max_length=50) phone_cnt = models.CharField(max_length=50, blank=True, null=True) email_cnt = models.CharField(max_length=100, blank=True, null=True) note_cnt = models.CharField(max_length=100, blank=True, null=True) receives_emails_cnt = models.BooleanField(blank=True, null=True) deleted_cnt = models.BooleanField(blank=True, null=True) # date_deleted_cnt = models.DateTimeField(blank=True, null=True) # deleted_by_cnt = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'app_contact_cnt' app_label = 'easytrade20' I tried to add in managed = True no change. Also tried the following: Delete all previous migration files and pycache files except init. python manage.py migrate --fake-initial python manage.py makemigrations python manage.py migrate I am still getting No changes detected I am not sure how to proceed, any assistance is apprecaited. -
ManagementForm data is missing or has been tampered with though management_form has been included and all the errors for formset have been handled
I am trying to submit formset in django but it is giving me this error: ManagementForm data is missing or has been tampered with Though I have included management_form and have handled all the errors for formset. So, what will be the solution here?Any help will be highly appreciated. I have provided model class, form class, formset, view class and form.html. class GovernmentHoliday(models.Model): day = models.CharField(max_length=128, blank=False) date = models.DateField() holiday_name = models.CharField(max_length=128, blank=False) type = models.CharField(max_length=128, blank=False) comments = models.CharField(max_length=128, blank=False) from django import forms from django.forms import modelformset_factory class GovernmentHolidayForm(forms.ModelForm): """ """ class Meta: model = GovernmentHoliday fields = [ 'day', 'date', 'holiday_name', 'type', 'comments', ] widgets = { 'day': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal3'}, format='%m/%d/%Y'), 'holiday_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'type': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'comments': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Edit label # Non required fields # Remove help suggestion for fieldname in ['day', 'date', 'holiday_name', 'type', 'comments']: self.fields[fieldname].help_text = None GovernmentHolidayFormset = modelformset_factory(GovernmentHoliday, fields=('day', 'date', 'holiday_name', 'type', 'comments'), form=GovernmentHolidayForm, extra=0, min_num=1, can_delete = True, can_order = True, ) class GovernmentHolidayAddView(LoginRequiredMixin, CreateView): login_url = '/authentication/login/' template_name = 'leave/government_holiday_add_form.html' government_holiday_formset_class = GovernmentHolidayFormset # Override default get method … -
Prevent react router from pinging Django server
so I have app in React with Router and Django on backend. I have Dashboard component, where I send request to Django for getting posts. But when I go on /dashboard, via Link or URL in browser, I get two requests on server: GET /dashboard GET /posts Why I'm having this /dashboard request and how to stop react for pinging django with this request? Router look like this: <Router history={history}> <Switch> <Route exact path={urls.get('dashboard')}> <Dashboard/> </Route> ... </Switch> -
Django - Pivoting Data without using pivot function
I need to transform rows into columns adding up 'amount' in MONTH/YEAR. My models: class Category(models.Model): title = models.CharField(max_length=25) *Data from model:* {'id': 1, 'title': 'HOUSING'} {'id': 2, 'title': 'FOOD'} class ExpenseType(models.Model): title = models.CharField(max_length=25) category = models.ForeignKey(Category, on_delete=models.CASCADE) *Data from model:* {'id': 1, 'title': 'RENT', 'category_id': 1} {'id': 2, 'title': 'MEALS', 'category_id': 2} class Expense(models.Model): expenseType = models.ForeignKey(ExpenseType, on_delete=models.CASCADE) amount = models.FloatField() date = models.DateField() *Data from model:* {'id': 1, 'expenseType_id': 1, 'amount': 1000.0, 'date': datetime.date(2020, 5, 1)} {'id': 2, 'expenseType_id': 1, 'amount': 1000.0, 'date': datetime.date(2020, 6, 1)} {'id': 3, 'expenseType_id': 2, 'amount': 100.0, 'date': datetime.date(2020, 4, 1)} {'id': 4, 'expenseType_id': 2, 'amount': 200.0, 'date': datetime.date(2020, 4, 1)} The output I need to render: CATEGORY | 04/2020 | 05/2020 | 06/2020 HOUSING | None | 1000.0 | 1000.0 FOOD | 300.0 | None | None Extracting month/year from date Aggregating categorie's amounts by month/year I'm looking for a solution other than pivot or pandas so I can render as for loops and use it with bootstraps dataTables. -
What is 'instance=' and 'queryset=' in django?
what does it do in this function, what does it mean generally? def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields = ('product','status'), extra=10) customer=Customer.objects.get(id=pk) formset=OrderFormSet(queryset=Order.objects.none(),instance=customer) if request.method=='POST': formset=OrderFormSet(request.POST,instance=customer) if formset.is_valid(): formset.save() return redirect('/') context={'formset':formset} return render(request, 'accounts/order_form2.html',context) -
In django, is it possible to sort the admin page using a function (cannot be written with query expressions) without using raw SQL?
I have this admin page class: class UserAdmin(admin.ModelAdmin): levelfunc = lambda usr: dox_user(usr).rank.level list_display = ('name', levelfunc) My ultimate goal is to be able to sort the admin page using the levelfunc column, sadly django won't allow that. I tried googling a lot and most of the times it said to use a query expression which I cant in this situation because the dox_user function which returns data about the user cannot be simplified to an SQL expression and I can't move the dox_user function to anywhere else because I'll need to rewrite a lot of code if I do that. Is there even a simple way to just sort it by the user's level?