Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I filter query range objects by id primary_key? Django
How I can filter 5 articles latest by slidenumber field.? class Article(models.Model): slidenumber = models.AutoField(primary_key=True) title = models.CharField(max_length=255) category = models.CharField(default='', max_length=30) description = models.TextField(default="Mo ta") bodyrichtext= RichTextField(default="", null=True) -
Is it possible to determine whether a Model's inlines have been changed during a save (update)?
class MyModel(models.Model): ... version = models.IntegerField( default=portal_settings.DEFAULT_MY_MODEL_VERSION ) ... class MyModelForm(forms.ModelForm): ... ... class MyModelQuestion(models.Model): my_model = models.ForeignKey(MyModel, on_delete=models.CASCADE) my_field = models.TextField() ... class MyModelQuestionForm(forms.ModelForm): class Meta: model = MyModelQuestion fields = ['my_field'] class MyModelQuestionInline(admin.TabularInline): model = MyModelQuestion fields = ['my_field'] can_delete = True can_edit = True extra = 0 class MyModelQuestionAdmin(admin.ModelAdmin): form = MyModelQuestionForm class MyModelAdmin(admin.ModelAdmin): form = MyModelForm inlines = (MyModelQuestionInline,) def bump_my_model_version_if_updated(sender, instance, created, **kwargs): if not created: if kwargs.get("update_fields") or <one or more of the inline objects is being updated>: <--- can't figure out how to do the second condition here instance.version += 1 instance.save() signals.post_save.connect(receiver=bump_my_model_version_if_updated, sender=MyModel) My problem is that at the moment in bump_my_model_version_if_updated() I can only tell if a direct field of the MyModel instance has been updated, but I cannot tell if any of the inline MyModelQuestion objects have been updated. The instance param of the signal is of course the MyModel instance. Is it at all possible to retrieve the MyModelAdmin (which should allow me to retrieve the inlines), or to retrieve the inlines directly from within the MyModel class? Can provide more code as requested if anything else is needed to help me out. Any suggestions appreciated! -
Getting an Error while running the python manage.py migrate
D:\Django Project\dataform>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, dataformapp, sessions Running migrations: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right sy ntax to use near '(6) NOT NULL)' at line 1") -
How to make a this output in a string in django?
I am working in a django project where my requirement is to create a string from this output [{'Jira_Column': 'Epic', 'RelationalOperators': '=', 'Jira_Value': 'DevOps', 'LogicalOperator': ''}, {'Jira_Column': 'Sprint', 'RelationalOperators': '=', 'Jira_Value': 'DX4C Sprint 18 (FY21-Q4)', 'LogicalOperator': 'AND'}] my string should be only the values not the column names string should be like this from the output I shared: Epic = Devops AND Sprint = DX4C Sprint 18 (FY21-Q4) Here's my view def rule_assignment(request): print("check") rules = list(assignmentRule.objects.values_list('id','Developer','Epic')) print(rules) for rule in rules: assignmentRules = list(assignmentRuleItem.objects.values('Jira_Column', 'RelationalOperators', 'Jira_Value', 'LogicalOperator').filter(Rule_No = rule[0])) print(assignmentRules) return render (request, 'hello/Dependency_Management.html') And here are my models class developer(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) def __str__(self): return self.Developer_Name class assignmentRule(models.Model): id = models.IntegerField(primary_key=True) Developer = models.ForeignKey(developer, on_delete=models.CASCADE) Epic = models.CharField(max_length=30) def __int__(self): return self.id class assignmentRuleItem(models.Model): Jira_Column = models.CharField(max_length=100, blank=True) RelationalOperators= models.CharField(max_length=100) Jira_Value = models.CharField(max_length=500) LogicalOperator = models.CharField(max_length=30, blank=True) Rule_No = models.ForeignKey(assignmentRule, on_delete=models.CASCADE) can someone please help me to create that string like I mentioned above? -
django form: erorr passing model foreign into a form choice field
I am working with a form and model containing two foreign keys from other models. The two fk fields need to be displayed as choices in the template. I was able to do this, the form gets rendered just fine, however, there is an error when trying to save it. A couple posts were informative but none did solve my issue. It seems that the issue is not where I searched for, or at least I am unable to locate and fix it. here is what I have for models.py class Sales(models.Model): SaleID = models.AutoField(max_length=100, primary_key=True) SaleProductName= models.ForeignKey(Products, on_delete=models.CASCADE) SalePartnersName = models.ForeignKey(Partners,on_delete=models.CASCADE) SalePartnerBusinessName = models.CharField(max_length=100,default="NA") SaleQuantity = models.FloatField(max_length=100,default="NA") SaleUnit = models.CharField(max_length=100,default="NA") SaleNetAmount = models.FloatField(max_length=100) SalePartnerCommission = models.FloatField(max_length=100) SaleDate = models.DateField(default=datetime.date.today) SaleStatus = models.CharField(max_length=100,default="Ongoing") And here is my views.py def RecordNewDealView(request): if request.method == 'POST': form = RecordNewDealForm(request.POST) if form.is_valid(): form.save() return redirect('my_deals.html') else: form = RecordNewDealForm() context = {'form': form,} return render(request, 'record_new_deal.html', context) and finally here is the forms.py file brokers_df = pd.DataFrame(list(Partners.objects.all().values())) brokers = brokers_df[brokers_df['PartnerCategory'] == 'Broker'] items_list1 = brokers['PartnerName'].tolist() items_list2 = brokers['PartnerName'].tolist() CHOICES_OF_BROKERS = [list(x) for x in zip(items_list1, items_list2)] CHOICES_OF_BROKERS.insert(0,('Not involved','Not involved')) class RecordNewDealForm(forms.ModelForm): SaleStatus = forms.CharField(widget=forms.Select(choices=SALE_STATUS_CHOICES)) SalesBroker = forms.CharField(widget=forms.Select(choices=CHOICES_OF_BROKERS)) SaleProductName = forms.ModelChoiceField(queryset=Products.objects.all().values_list('ProductName', flat=True)) SalePartnerName = … -
Foreign key relation for Rest framework -- Django
I am using Django and Restframework to create a API. The data is I want the API output in such a way that "MasterResource" models is Parent, under that it filter the "Section" with matching "MasterResource" and then all the related "Items" matching with "Section". My Models are currently look like this: class MasterResource(models.Model): route_name = models.CharField(max_length=100) resourceId = models.CharField(primary_key=True, max_length=100) class ResourceSection(models.Model): resourceId = models.ForeignKey(MasterResource, on_delete=models.CASCADE, default=1) resource_name = models.CharField(max_length=100) sectionId = models.CharField(primary_key=True, max_length=100) class SectionItem(models.Model): sectionId = models.ForeignKey(ResourceSection, on_delete=models.CASCADE,default=1) item_title = models.CharField(max_length=100) image = models.ImageField(blank=True) link = models.URLField() And my views looks like this: @csrf_exempt @api_view(['POST']) @permission_classes([IsAuthenticated]) def create_resource(request): if request.method == 'POST': try: resourceId = request.POST.get("resourceId") route_name = request.POST.get("route_name") result = {} result['resourceDetails'] = json.loads(serializers.serialize('json',[MasterResource.objects.get(resourceId=resourceId)])) result['sectionDetails'] = json.loads(serializers.serialize('json',ResourceSection.objects.filter(resourceId__resourceId = resourceId))) result['itemDetails'] = json.loads(serializers.serialize('json',SectionItem.objects.filter(sectionId__sectionId=sectionId))) return JsonResponse(result, safe=False) except Exception as e: return HttpResponseServerError(e) I have achieved to receive data of "MasterResource" and its related "Sections", but the related "Items" arenot giving output Current output { "resourceDetails": [ { "model": "userdata.masterresource", "pk": "1234", "fields": { "route_name": "Testing test" } } ], "sectionDetails": [ { "model": "userdata.resourcesection", "pk": "112233", "fields": { "resourceId": 1234, "resource_name": "Test section" } }, { "model": "userdata.resourcesection", "pk": "223344", "fields": { "resourceId": 1234, "resource_name": "Test section2" … -
Django filter form appears by default as dropdown; change to checkbox
I have a model defined like below in models.py class ImageGrab(models.Model): title = models.CharField(max_length=50) slug=models.CharField(max_length=200) age=models.ForeignKey(Age, on_delete=models.CASCADE) gender=models.ForeignKey(Gender, on_delete=models.CASCADE) masked=models.ForeignKey(Mask, on_delete=models.CASCADE) withBackpack=models.ForeignKey(Backpack, on_delete=models.CASCADE) Filters for which are defined as below in filters.py: class ImageFilterAge(django_filters.FilterSet): class Meta: model = ImageGrab fields = ['age'] ###others similar to this class ImageFilter(django_filters.FilterSet): class Meta: model = ImageGrab fields = ['age', 'gender', 'masked', 'withBackpack'] The view is like below defined in views.py def images(request): imagelist = ImageGrab.objects.all() imagefilter = ImageFilter(request.GET, queryset=imagelist) agefilter = ImageFilterAge(request.GET, queryset=imagelist) genderfilter=ImageFilterGender(request.GET, queryset=imagelist) maskedfilter= ImageFilterMask(request.GET, queryset=imagelist) backpackfilter = ImageFilterBackpack(request.GET, queryset=imagelist) return render(request, 'imglist.html', {'filter': imagefilter,'agefilter': agefilter.form, 'genderfilter':genderfilter.form, 'maskfilter':maskedfilter.form, 'backpackfilter':backpackfilter.form}) My template is like this, in imglist.html <form method="get" name="search" id="search"> {{ agefilter }} <br> {{ genderfilter }} <br> {{ maskfilter }} <br> {{ backpackfilter }} <br> </form> This is rendered by default as dropdown select form as given in image link below. I want to change this to say checkbox multiple select and/ or radio button for the filters. Filtering using dropdown How to go about doing this? Thanks in advance. -
Get the details of selected item
I have a part table and delivery instruction table (dins). To create a dins, I have to choose a part name. So what I want to do is, after choosing the part name from the dropdown that part's price will be visible in the form. In the Part table, I have the price value for the specific part name. So during the creation of dins, after choosing such an example part name is X, then the form should show what is the price of that chosen part (X part) price. Any idea how to make that happen? views.py def create_deliveryins(request): from django import forms form = DeliveryInsForm() if request.method == 'POST': forms = DeliveryInsForm(request.POST) if forms.is_valid(): product = forms.cleaned_data['product'] usage = forms.cleaned_data['usage'] part= forms.cleaned_data['part'] deliveryins = DeliveryIns.objects.create( usage=usage, product=product, part=part, ) return redirect('dins-list') context = { 'form': form } return render(request, 'store/addDins.html', context) HTML <form action="#" method="post" novalidate="novalidate"> {% csrf_token %} <div class="form-group"> <label for="product" class="control-label mb-1">Product</label> {{ form.product }} </div> <div class="form-group"> <label for="part" class="control-label mb-1">Part</label> {{ form.part}} </div> <div class="form-group"> <label for="usage" class="control-label mb-1">Usage</label> {{ form.usage }} </div> </form> -
the filename of pdf file doesnt work correctly with wkhtmltopdf
I have a button download in my Django project, where I can export the report for a certain date in a pdf format. Everything works fine on my laptop with Linux, but when I set the project in the local server of our company, the name of the file is showing without a date. Here is my code: template_name = 'pdf.html' template = get_template(template_name) html = template.render({"data": data, "date":date, "index":index}) if 'DYNO' in os.environ: print('loading wkhtmltopdf path on heroku') WKHTMLTOPDF_CMD = subprocess.Popen( ['which', os.environ.get('WKHTMLTOPDF_BINARY', 'wkhtmltopdf-pack')], stdout=subprocess.PIPE).communicate()[0].strip() else: print('loading wkhtmltopdf path on localhost') WKHTMLTOPDF_CMD = ('/usr/local/bin/wkhtmltopdf/bin/wkhtmltopdf') config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_CMD) options = { 'margin-bottom': '10mm', 'footer-center': '[page]' } pdf = pdfkit.from_string(html, False, configuration=config, options=options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="otchet-{}.pdf"'.format(date) return response when I download locally, the name of the file is - otchet-2021-06-30.pdf but on server, it looks like - otchet%20.pdf I have no idea, how to fix it... -
How to let AJAX read python render variable to HTML?
PLEASE HELP (T_T), I'm a new django learner. My question is how do I write Ajax to load my {{channel_mlx90614}} that I render from views.py ? I wanted to create a button to refresh the data from python, So I render the data from Views.py in Django, which is {{channel_mlx90614}}, but I wanted to button click refresh the data value when my firebase database data is changed, which in asynchronous way instead of refreshing the browser. **view.py** firebase = pyrebase.initialize_app(config) db = firebase.database() def index(request): channel_mlx90614 = db.child('mlx90614').child('1-set').child('ambient').get().val() if channel_mlx90614 >= 37.5: temperature_note = "High Temperature alert !" elif channel_mlx90614 <= 37.5: temperature_note = "Normal Temperature !" else: temperature_note = "No temperature detected !" return render(request, 'mysite1/index.html', { "channel_mlx90614":channel_mlx90614, "temperature_note":temperature_note }) **sample.html** <button id="myBtn">Try it</button> <p id="demo"></p> <script> document.getElementById("myBtn").addEventListener("click", displayDate); function displayDate() { document.getElementById("demo").innerHTML = "{{channel_mlx90614}}"; } <script language="javascript"> $(function(){ $(".myBtn").click(function(){ $("#demo").load( ????? ); // How to read {{channel_mlx90614}} render from python to html? }); }); </script> -
How to get active and inactive plans from M2M field in Django
I've three models named as E_Office, Plans and UserPlanSubscription. E_Office model have all the information about e-office and it is independent (not connected with any model like ForeignKey ), Plans models have all the plans information and it is connected with E_Office model using ManyToManyField and UserPlanSubscription model is stores Plans using ForeignKey. My problem is I want to separate active plans(which is stored in my UserPlanSubscription) and inactive plans (whole data from E_Office excluding active plans) and display it on page active plans will appear in white and inactive will appear in black I've tried like this given below but it's not scalable if data is more than thousand so please help me to improve my code. Plans model class Plans(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) plan_name = models.CharField(max_length=255, null=True) plan_price = models.CharField(max_length=255, null=True) access_to = models.ManyToManyField(Add_e_office) UserPlanSubscription model class UserPlanSubscription(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE,null=True,blank=True) plan = models.ForeignKey(Plans, on_delete=models.CASCADE,null=True,blank=True) paid = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False,null=True) views.py @login_required def my_eoffice(request): context = {} mydata = [] left_plans = [] context['plans'] = Plans.objects.all() if UserPlanSubscription.objects.filter(user=request.user,expiry_date__gte=datetime.datetime.now()).exists(): # Active Plans user_plans = UserPlanSubscription.objects.get(user=request.user) active_plan = user_plans.plan.access_to.all() mydata.append({'active_plan':active_plan}) myeoffice = E_Office.objects.all() # want to improve for i in … -
trying to get a Django 3.2 app recognized in python 3.9
I'm trying my hand at Django 3.2. I installed the app, and followed what I could from the guidance, and I seem to can't to get the app module to be recognized. Here's my steps to reproduce the problem: in terminal django-admin startproject research django-admin startapp landing Then I made the following file changes: landing\__init__.py default_app_config = 'landing.apps.LandingConfig' landing\apps.py from django.apps import AppConfig class LandingConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'landing' landing\models.py (trying to add stripe in future release) from django.db import models # Create your models here. class StripeSubscription(models.Model): start_date = models.DateTimeField(help_text="The start date of the subscription.") status = models.CharField(max_length=20, help_text="The status of this subscription.") # other data we need about the Subscription from Stripe goes here class MyStripeModel(models.Model): name = models.CharField(max_length=100) stripe_subscription = models.ForeignKey(StripeSubscription, on_delete=models.SET_NULL) landing\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] landing\views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello, world. You're at the landing index.") settings.py - Installed apps INSTALLED_APPS = [ 'landing.apps.LandingConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('landing/', include('landing.urls')), ] … -
Wouldn't login with email in Django
I'm trying to login with email and password in Django. This works with username and password. import requests from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt from .forms import PlayerCreationForm # REGISTER VIEW def register_view(request): if request.method != 'POST': form = PlayerCreationForm() else: form = PlayerCreationForm(request.POST) if form.is_valid(): form.save() requests.post('http://127.0.0.1:5000/credentials', json={'email': form.cleaned_data['email'], 'username': form.cleaned_data['username'], 'password': form.cleaned_data['password2']}) return redirect('/login') context = {'form': form} return render(request, "register.html", context) # LOGIN VIEW def login_view(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request, 'Incorrect email or password') return render(request, 'login.html') # LOGOUT VIEW def logout_view(request): logout(request) return redirect('/') # HOMEVIEW def home_view(request): return render(request, "base.html") Do I need a different configuration to make user login with email? I the old username and password with email and password. I also reconfigured login.html to make it work with email and password. Is there anything wrong here? -
Imagefield in Django doesn't upload image
I was trying to work in my blog project so i make a create-post page where i can create blog posts . but it seems that the imagefield doesn't upload image . though it works on if i upload image from admin panel. I have created MEDIA URL and MEDIA ROOT and connected them in url so my code should work according to me and also in html form I have perfectly written enctype attr so i made a Imagefield in Model and connected that with form and using view I tried to make create post related code : models.py enter image description here this is the model file form.py: enter image description here view.py: enter image description here create-post.html: enter image description here urls.py enter image description here from the website page : enter image description here in the admin panel: enter image description here -
Django Value Error "The view capstone.views.home didn't return an HttpResponse object. It returned None instead."
I'm taking data that the user puts into a form and saving it to the database in Django. When I submit the form, the value actually does save to the database. But I keep getting this error. Not sure how to fix it? views.py def home(request): if request.method == "GET": form_for_post = {'form': PostForm()} return render(request, "capstone/home2.html", form_for_post) else: if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): city = form.cleaned_data['city'] place = Location.objects.create(username=request.user, city=city,) place.save() else: return render(request, "capstone/home2.html") models.py class User(AbstractUser): pass class Location(models.Model): city = models.CharField(max_length=500) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) forms.py: class PostForm(forms.Form): city = forms.CharField(max_length=500) Form in html: <form method="POST"> {% csrf_token %} <label for="city">City:</label><br> <input type="text" id="city" name="city"><br> <input type="submit" value="Submit"> </form> -
Wagtail(Django) ModelAdmin Button view action
i want to put a button into wagtail admin for inspect in view mode, by default edit and delete are shown, but i don't know what need to do for call a view that contain only view of a model here is my code: products.models.py class CamisaOrder(models.Model): STATUS_CHOICES = ( ('PAYMENTVERFICATION','Verificacion Forma Pago'), ('PROCESSINGORDER','Procesando Orden'), ('MAKING','Elaboracion'), ('PROCESSINGSHIPING','Preparando Envio'), ('SHIPPED','Enviado'), ('DELIVERED','Recibido'), ('CANCELED','Cancelado'), ('RETURNED','Retornado'), ) camisa = models.ForeignKey('CamisetaProduct',related_name='+', on_delete= models.PROTECT) cantidad = models.IntegerField() status = models.CharField(max_length=20, null=False, blank=False, choices=STATUS_CHOICES, default="PROCESSINGORDER") panels = [ FieldPanel('camisa'), FieldPanel('cantidad'), FieldPanel('status') ] class Meta: verbose_name="Camisa Orden" verbose_name_plural="Camisas Ordenes" wagtail_hooks.py class ProductButtonHelper(ButtonHelper): view_button_classnames = ['button-small', 'icon', 'icon-site'] def view_button(self, obj): # Define a label for our button text = 'View {}'.format(self.verbose_name) logging.debug(obj) return { 'url': #url here for inspect model# 'label': text, 'classname': self.finalise_classname(self.view_button_classnames), 'title': text, } def get_buttons_for_obj(self, obj, exclude=None, classnames_add=None, classnames_exclude=None): btns = super().get_buttons_for_obj(obj, exclude, classnames_add, classnames_exclude) if 'view' not in (exclude or []): btns.append( self.view_button(obj) ) return btns class CamisetaOrderAdmin(ModelAdmin): model = CamisaOrder button_helper_class = ProductButtonHelper menu_label = 'Pedidos y Ordenes' menu_icon = 'mail' menu_order = 200 add_to_settings_menu = False exclude_from_explorer = False list_display = ('camisa', 'cantidad', 'status') list_filter = ('status',) search_fields = ( 'status',) modeladmin_register(CamisetaOrderAdmin) how i can achieve this approach? i need to … -
Problem with migrating my Database using Django
I currently have a database using Heroku and want to migrate it to AWS, where both use PostgresSQL. So, after some digging on how to get it done I followed the steps as on this youtube video. I initially ran python manage.py dumpdata > dumpdata.json with my Heroku database credentials in Django. Afterwards, I changed my database credentials in settings.py to the AWS database credentials, and ran python manage.py migrate --run-syncdb which worked successfully. And then I ran the code python manage.py loaddata dumpdata.json, when where I was thrown by an error. The following error came up... django.db.utils.IntegrityError: Problem installing fixture 'C:\Users\Acer\Desktop\Web Development\Proffesional\eblossom\eblossom\eblossom\dumpdata.json': Could not load contenttypes.ContentType(pk=9): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(user, profile) already exists. I don't understand what has gone wrong over here, the site is working perfectly fine all this time with no database compilation error, but now when I try to migrate it to AWS, I am thrown with this problem. Just in case my models.py.... class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile_number = models.CharField(max_length=12, null=True) guest = models.BooleanField(default=False) def __str__(self): return f"{self.user}" Any help would be greatly appreciated. Thanks! -
How to iterate over the matches in django?
I'm sending notifications to a user via Django notifications, and I have username regex working on the HTML so anyone posts with @username it will post and the HTML is linkable so click on the @username it will take anyone to the username profile page. Now I am using Django signals to match the username and print out the username. When I'm using two or three @usernames the notification goes to only for one @username other two @username do not get the notifications. Models.py- class post(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) video = models.FileField(upload_to='post_videos', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = postManager() def __str__(self): return self.title class Meta: ordering = ['-date_posted', 'title'] def get_absolute_url(self): return reverse ('blog-home') def total_likes(self): return self.likes.count() def post_save_receiver(sender, instance, created, *args,**kwargs): if created and not instance.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, instance.content) if m: username = m.group("username") notify.send(instance.author, recipient=m, actor=instance.author, verb='tagged you', nf_type='tagged_by_one_user') post_save.connect(post_save_receiver, sender=post) -
How to convert nav-pill to bootstrap pagination
I am trying to convert this nav-pills: <div class="col-auto"> <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index|add:'-tab' href='#evidence-form-'|add:index aria_controls='evidence-form-'|add:index %} <li class="nav-item"> {% if not current_tab and forloop.first or current_tab == index %} <a class="nav-link active" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> {% else %} <a class="nav-link" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="false">{{ forloop.counter }}</a> {% endif %} </li> {% endwith %} {% endwith %} {% endfor %} </ul> </div> <!-- .col --> To this pagination: <nav aria-label="Page navigation example"> <ul class="pagination" id="evidence-formset-tab" role="tablist"> <li class="page-item"><a class="page-link" href="#">Previous</a></li> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index|add:'-tab' href='#evidence-form-'|add:index aria_controls='evidence-form-'|add:index %} {% if not current_tab and forloop.first or current_tab == index %} <li class="page-item active"> <a class="page-link" id="{{ id }}" data-toggle="tab" href="{{ href }}" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" id="{{ id }}" data-toggle="tab" href="{{ href }}" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> </li> {% endif %} {% endwith %} {% endwith %} {% endfor %} <li class="page-item"><a class="page-link" href="#">Next</a></li> </ul> </nav> But for some … -
How can i delete item in django?
So can someone help me how can i delete the item in tech with tim django todo app project? I really need this one to understand how delete works and models in django. This is the source code for tech with tim django todo app -
Django Model Forms including Foreign Key Fields
I am trying to create a Model Form in Django that includes Foreign Key fields from the Athlete Table. Normally when referring to the Foreign Key fields I can use the field name 'athlete' then.followed by the field name. This does not seem to be working. I have tried using a queryset using the ModelChoiceField but think I am not setting this up correctly. Thanks in advance for any help. This is the main Model (ASP Bookings) including the Foreign Key Athlete class ASPBookings(models.Model): asp_booking_ref = models.CharField(max_length=10, default=1) program_type = models.CharField(max_length=120, default='asp') booking_date = models.DateField() booking_time = models.CharField(max_length=10, choices=booking_times) duration = models.CharField(max_length=10, choices=durations, default='0.5') street = models.CharField(max_length=120) suburb = models.CharField(max_length=120) region = models.CharField(max_length=120, choices=regions, default='Metro') post_code = models.CharField(max_length=40) organisation_type = models.CharField(max_length=120,choices=organisation_types, default='Government School') audience_number = models.CharField(max_length=10) presentation_form = models.CharField(max_length=120, choices=presentation_form_options, default='Face to Face') contact_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=120) comments = models.TextField() status = models.CharField(max_length=80, choices=statuses, default='TBC') email_sent = models.BooleanField(default=False) athlete = models.ForeignKey(Athlete, default= '1', on_delete=models.CASCADE) def __str__(self): return self.contact_name # return URL after the POST has been submitted. def get_absolute_url(self): return reverse('vistours:success') Athlete Model class Athlete(models.Model): athlete_ref = models.CharField(max_length=10, default=1) athlete_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=120) home = models.CharField(max_length=120) education = models.CharField(max_length=120) sport … -
What's up? You didn't select a choice. Django Pull apps
I am testing Django apps. In part 4, I am done creating from. There must be a radio button. <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> as the code suggests. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>James-Cameron-Teaches-Filmmaking</title> </head> <body> <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> </form> </body> </html> this is the HTML I am using. This is the code for my view: from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes … -
Django find logged in user
I am trying to send data from sensor connected to an ESP8266 to a Django webserver but I can't send which user those readings belong to. I already put user as a foreign key in sensor model but how can I get the user ID. the request.user part doesn't return anything as user isn't known by the ESP @csrf_exempt def index(request): # current_user = request.user print("\n") data = json.loads(request.body) type1 = data.get("sensorType1", None) heart_rate = data.get("reading", None) type2 = data.get("sensorType2", None) spo2 = data.get("SpO2", None) sensor = Sensor() # print(current_user) print(type1) print(heart_rate) print(type2) print(spo2) # sensor.user = current_user sensor.SensorType1 = type1 sensor.HeartRate = heart_rate sensor.SensorType2 = type2 sensor.SpO2 = spo2 sensor.save() return render( request, "reading.html", ) -
django celery beat periodic task admin page loading error
I am using django_celery_beat and mongodb as my database. I am able to make migrations for django_celery_beat but when I was trying get access to the admin page on my local, http://127.0.0.1:8000/admin/django_celery_beat/periodictask/. I am facing a DatabaseError at /admin/django_celery_beat/periodictask/. specfically: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/django_celery_beat/periodictask/ Django Version: 3.0.5 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'Reddit_app', 'crispy_forms', 'phonenumber_field', 'sorl.thumbnail', 'social_django', 'bootstrap4', 'ckeditor', 'ckeditor_uploader', 'django_celery_results', 'django_celery_beat'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware'] Template error: In template /Applications/anaconda3/lib/python3.8/site-packages/django/contrib/admin/templates/admin/base.html, error at line 0 (Could not get exception message) 1 : {% load i18n static %}<!DOCTYPE html> 2 : {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} 3 : <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> 4 : <head> 5 : <title>{% block title %}{% endblock %}</title> 6 : <link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}"> 7 : {% block extrastyle %}{% endblock %} 8 : {% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}">{% endif %} 9 : {% block extrahead %}{% endblock %} 10 : {% block responsive %} Traceback (most recent call last): File … -
Simplify Django database creating execution number by using some data structure or algorithm
I have used Django2 to develop a web app. I have some task, which is needed to be created into the database based on user input. I have 5 user type, say hop, hop2, executive, executive2, executive3. The mysql database of the task table is like this: task table: 1, task name, assignee_hop, assignee_hop2, assignee_executive, assignee_executive2, assignee_executive3 If user input only hop2 and executive2 name, I have to write if condition to check, or would get error for not existing item, I have to write a if condition or would get error: Cannot assign "''": "Task.assignee_hop3" must be a "User" instance. the django create function should be like this: if hop2 and executive2: Task.objects.create(assignee_hop2=hop2, assignee_executive2=executive2) if user input only hop2 and executive3 name, the django create function should be like this: Task.objects.create(assignee_hop2=hop2, assignee_executive3=executive3) if user input only hop and executive3 name, the django create function should be like this: Task.objects.create(assignee_hop=hop, assignee_executive3=executive3) if user input only hop2 and executive name, the django create function should be like this: Task.objects.create(assignee_hop2=hop2, assignee_executive=executive) if user input only hop2 , executive and executive2 name, the django create function should be like this: Task.objects.create(assignee_hop2=hop2, assignee_executive=executive, assignee_executive2=executive2) if user input only hop2 , executive, executive2 and executive3 …