Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is wrong with my logic in for loops - django templates
This is my home.html, problem is with the if block: {% for menu in menus %} <div class="dropdown show"> <a class="btn dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ menu.main_menu_item }} </a> <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink"> {% for item in menu.items.all %} {% for second_item in item.items_second_level.all %} {% if item.items_second_level.all != None %} <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" href="#">{{ item.sub_menu_item }}</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">{{second_item.sub_menu_item}}</a></li> </ul> </li> {% else %} <li><a class="dropdown-item" href="#">{{ item.sub_menu_item }}</a></li> {% endif %} {% endfor %} {% endfor %} </ul> </div> {% endfor %} Namely, {% else %} part always "blanks". When I change condition to {% if item.items_second_level.all == None %} again, only items which satisfies the if condition get showed (obviously this time the ones that were not shown before). it behaves like there is no else. Does anyone know what could be the issue here? -
Django CORS header ‘Access-Control-Allow-Origin’ missing despite being in Response Headers
I have a webpage with a Django Backend API and an angular frontend SPA. I have django-cors-headers==3.5.0 installed and set up (configurations at the end). When trying to load an .mp3 file from my angular frontend SPA from localhost:4200, and only when loading the mp3 file, I receive the following error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.aldrune.com/media/session_audio/2020-12-01_-_Session_28.mp3. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Please note that at the same time I am able to take a look at the HTTP Request and I can see that contrary to the given error message, the response DOES have the header: Access-Control-Allow-Origin: * What gives? How can I have the header in my response and yet my browser claims it's not there? And why does this only happen with the .mp3 file, while all my media and static-file images, that stem from the exact same application- and http-server are unaffected? I am aware a lot of similar questions about Djanog and CORS have been asked before, but I couldn't find any that asked while seeing very clearly that the header that supposedly isn't there is very visible in the request. Below the setup on my … -
Getting TypeError: Failed to Fetch error. even though data is available at backend
I am trying to get data with fetch request but getting 'Typeerror: fail to fetch'.My front end is in react and the backend is in Django.There is no cors issue and when I am firing the query from the frontend, I am able to make data available at the backend but it is not able to reach the frontend. below is my code: try{ const data1 =await fetch( `http://localhost:8000/api/Manual_doc/?year=${e.target[0].value}&number=${e.target[1].value}&label=${e.target[2].value}` ) } catch(err) { alert(err.message); } }``` I am calling manual search on click on the button. Any help will be appreciated. -
TypeError: Movie() got an unexpected keyword argument 'actors'
I am working on a school project using Django and Python. Now I have created a website for using rest-apis. However, while testing I encountered an error that I simply can't seem to be able to solve. It occurs whenever I try to create a movie with POSTMAN using the api.I get the following error over and over again and I can't find what is wrong. Error message: raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Movie() got an unexpected keyword argument 'actors' My serializer class MovieSerializer(serializers.ModelSerializer): # Queryset gets all the data from the Actor model as specified with objects.all() actor_pks = serializers.PrimaryKeyRelatedField(queryset=Actor.objects.all(), source='actors', write_only=True, label='Actors', many=True) rent_pks = serializers.PrimaryKeyRelatedField(source='rent', read_only=True, label='Rent') # Change image-options to allow post/put/patch without an image image = serializers.ImageField(allow_null=True, required=False) def __init__(self, *args, **kwargs): # Get additional parameters from constructor depth = kwargs.pop('depth', None) fields = kwargs.pop('fields', None) # Add diffrent pks to fields if field is not None from constructor fields.append('actor_pks') if fields is not None else None fields.append('rent_pks') if fields is not None else None fields.append('image') if fields is not None else None # Overwrite meta tags self.Meta.depth = depth if depth is not None else 1 self.Meta.fields … -
How to check if value is None
I want to check if the "nilai" is None/Null cursor.execute('SELECT s.kode_ktg_id,(SUM(n.nilai_angka * S.nilai_mk)/SUM(s.nilai_mk)) as nilai_ktg FROM mahasiswa_khs k, mahasiswa_convert_nilai n, mata_kuliah_si s WHERE k.nilai = n.nilai_huruf AND k.nim = "%s" AND k.kode = s.kode GROUP BY s.kode_ktg_id',[nim]) nilai = cursor.fetchall() I check with this if nilai[0] is None: But I got error tuple index out of range -
Django authenticate returning none but login works?
When I run the below code, it prints "done." However, when I check if user is returning anything, it doesn't - it returns None. Is this a problem, if dj_login() is running without any errors? def login(request): if request.method == 'POST': try: username = request.POST.get('username') password = request.POST.get('password') try: user = authenticate(request, username=username, password=password) dj_login(request, user, backend='django_auth_ldap.backend.LDAPBackend') messages.success(request, "You have been logged in.") print("done") return render(request, "app/login.html") except Exception as e: print(e) messages.error(request, "Failed to Login Errors: {}".format(e)) return render(request, "app/login.html") except Exception as e: messages.error(request, "Failed to Login Errors: {}".format(e)) return render(request, "app/login.html") return render(request, 'app/login.html') -
Django rest_framework with custom User model - duplicate key value violates unique constraint
I start to learn django (rest_framework) and build an app. I created a custom user model and manager, below the code: class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) username = models.CharField(_('username'), max_length=255, unique=False, blank=True) mobile = models.CharField(_('mobile'),max_length=255, blank=True) picture = models.ImageField(upload_to='images/thumbnail/%Y/%m/%d/', null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] @property def picture_preview(self): if self.picture: return mark_safe('<img src="{}" width="300" height="300" />'.format(self.picture.url)) return "" objects = CustomUserManager() I have also customize the view for the admin..and everything work fine. Now when I register a new user from the admin and for instance I put two … -
Loadbalancer - multiple databases in django
I am writing a loadbalancer project, where I am supposed to catch all sql requests and execute them with my methods, but not while using decorators (@loadbalancer) as I would have to use them in each model. Is there a way to write it once and it will work for all? -
Filter ManyToMany by user from current model
I'm bit stuck on one stuff. How I can reach all Rerservation from the current Main model which belongs to the current user? Any help will be be appreciate class ReservationPay(generic.DetailView): model = Main def get_context_data(self, **kwargs): context = super(Reservation, self).get_context_data(**kwargs) context['user_rea'] = Main.objects.filter(all_resa__user=self.request.user).all() class Rerservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) prix = models.DecimalField(max_digits=6,decimal_places=2) class Main(models.Model): all_resa = models.ManyToManyField('Rerservation',blank=True, related_name='all_resa_reservation') -
Define list of objects in models.py in postgeSQL & Django-rest project
I mostly work with Node.js & MongoDB and I am pretty new to SQL dbs especially postgreSQL I am writing an application that makes use of django-rest-framework & postgreSQL as a DB. This is how my data structure as .json should look like. { id: "19eea956-34e5-11eb-adc1-0242ac120002" picture: [{ url: "", mimeType: "" }, { url: "", mimeType: "" }] } For the above data I am currently writing models.py which looks like as follows. from django.db import models from django.contrib.postgres.fields import ArrayField class Picture(models.Model): url = models.CharField() mimeType = models.CharField() class A(models.Model): id = models.CharField(max_length=120, primary_key=True) picture = ArrayField(Picture) def __str__(self): return self.id What I am trying to do in my models.py is to have picture as an Array of Objects or in python terminology List of Dictionaries. I read about ArrayField in postgreSQL but unable to find any example about how to define Array of Objects in models.py, any help here would be appreciated. Thanks :) -
Django form not showing except for submit button
I'm having this issue where the django form isn't showing up on the webpage. The only thing that shows up is the submit button. I cannot figure out the issue. Views.py class NewThreadView(CreateView): model = Thread form_class = NewThreadForm template_name = 'thread/newthread.html' def get_context_data(self, *args, **kwargs): context = super(NewThreadView, self).get_context_data(*args, **kwargs) forms.py class NewThreadForm(forms.ModelForm): class Meta: model = Thread fields = ('name', 'body', 'author', 'thread_forum') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter title'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), 'author': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id': 'author', 'type': 'hidden'}), 'thread_forum': forms.Select(attrs={'class': 'form-control', 'type': 'hidden'}), } newthread.html <div class="form-group"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" name="thread_submit">Create Thread</button> </form> </div> -
I need help correcting that issue
i have that error when im trying to access an object on my admin. TypeError at /admin/core/order/11/change/ str returned non-string (type NoneType) my model for the order class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete= models.SET_NULL, blank=True, null=True) payment = models.ForeignKey('Payment', on_delete= models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username def get_total(self): total= 0 for order_item in self.items.all(): total += order_item.get_final_price() return total i cannot have access on the admin what should i do please? -
Can not paginate and write ordering for only one module from two querysets inside get_context_data
def get_context_data(self, **kwargs):\ context_data = super().get_context_data(**kwargs)\ context_data['queryset1'] = Choice.objects.all()\ context_data['queryset2'] = Timer.objects.all()\ return context_data I am a beginner in Django and I just wanted to make some "ordering" and "pagination"\ for just queryset1 but nowhere in docs it is written... Could you please help? Thank you in advance -
Django Admin: Add Action Button To Send Email
I have a model where Mail is a Foreign Key. The user can add a mail object,I want to add a button to the change form upon clicking which the email should be sent. models.py class Evaluation(models.Model): ... mail = models.ForeignKey(Mail, related_name="evaluation", null=True, blank=True, on_delete=models.CASCADE) I possibly want the button to execute something like this: def process(self): if self.mail is not None: send_mail( self.mail.subject, self.mail.body, settings.EMAIL_HOST_USER, [self.lead.user.email], fail_silently=False ) How could I achieve the same? -
Why updating nested user throws error of the field already exist?
I've tried to update a model with its related field which is customized user but after sending request with patch it returns 400 the code is here: models.py class Land(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) ... class User(AbstractBaseUser, PermissionsMixin): """Custom user model that support using national instead of username""" national_code = models.CharField(max_length=255, unique=True, blank=True) ... serializers.py class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() fields = ('first_name', 'last_name', ...,) extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def update(self, instance, validated_data): """Update a user, setting the password correctly and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user class LandSerializer(serializers.ModelSerializer): user = UserSerializer() utm_points = UTMPointsSerializer(many=True, read_only=True) letters = LettersSerializer(many=True, read_only=True) class Meta: model = Land fields = ('id', 'user', ...,) read_only_fields = ('id', 'approved',) def update(self, instance, validated_data): user = validated_data.pop('user') user_serializer = UserSerializer(data=user) if user_serializer.is_valid(): user = user_serializer.update(instance=instance.user, validated_data=user) validated_data['user'] = user instance.save() return instance views.py class LandViewSet(BasicViewSet): serializer_class = LandSerializer queryset = Land.objects.all() def get_serializer_class(self): """Return appropriate serializer class""" if self.action == 'retrieve': return self.serializer_class elif self.action == 'upload_image': return LandImageSerializer return self.serializer_class def partial_update(self, request, pk=None): land = self.get_object() # user_serializer = UserSerializer(land.user, data=request.data['user']) serializer = self.get_serializer(land, … -
Can I use Django with Next.js?
I am new to Next.js and see that there is a /api folder. This seems like it COULD replace my Django Rest Framework backend. Is that what the /api folder is intended to do? Moreover, is it common to see Django Rest Framework as a backend for Next.js? Thanks! -
Django don't save a form using Floppyforms
I have a field called medicamento in my model that is a foreign key and I want all the values in that field to be displayed in a searcheable dropdown in my form. I was able to do that but when I try to save, it says "Select a valid choice. That choice is not one of the available choices." Hope u can help dudes! Thanks in advance models.py class Stockmov(models.Model): numero = models.AutoField(primary_key=True) created= models.DateTimeField(auto_now_add=True,verbose_name="Fecha de Movimiento") author = models.ForeignKey(User,verbose_name="autor",on_delete=models.PROTECT, null=True, blank=True) medicamento= models.ForeignKey(Medicamento,on_delete=models.CASCADE) motivo= models.CharField(max_length=200) Cantidad = models.IntegerField() forms.py class StockmovForm(forms.ModelForm): class Meta: model = Stockmov fields = ['medicamento', 'motivo', 'Cantidad' ] widgets = { #'medicamento': forms.Select(attrs={'class':'form-control', 'placeholder':'Medicamento'}), 'medicamento': forms.widgets.TextInput(attrs={'class':'form-control', 'placeholder':'Medicamento'},datalist=Medicamento.objects.all()), 'motivo': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Motivo'}), 'Cantidad': forms.NumberInput(attrs={'class':'form-control', 'placeholder':'Cantidad'}), } labels = { 'medicamento':'Medicamento', 'motivo':'Motivo del Movimiento', 'Cantidad':'Cantidad del Movimiento', } views.py class StockmovCreate(CreateView): model = Stockmov form_class = StockmovForm success_url = reverse_lazy('stockmov:stockmov') def form_valid(self, form): form.instance.author = self.request.user print(self.request.user) return super(StockmovCreate, self).form_valid(form) Template <form action="" method="post">{% csrf_token %} {{ form.as_p }}`s` <div class="text-center"> <input type="submit" id="btnCrear" class="btn btn-secondary btn-block" value="Crear Movimiento" /> </div> </form> -
Django : Add different users to one project (project management web application)
I need help with implementing a form on which I can add new users to a specific project, using Django (Python) It's for a project management web application that I'm working on. Here are the necessary steps that I have accomplished before, please let me know whether I missed something. Models.py '''class Projet(models.Model): """autofield exists""" nom_projet = models.CharField(max_length=200, null=True) date_debut = models.CharField(max_length=200, null=True) date_fin = models.CharField(max_length=200, null=True) domaine = models.CharField(max_length=200, null=True) budget = models.IntegerField(null=True) description = models.CharField(max_length=500, null=True) users = models.ManyToManyField(User, blank=True, related_name='projet_users') def __str__(self): return self.nom_projet''' Forms.py class AddUserForm(forms.Form): user = forms.ModelChoiceField(queryset=User.objects.all()) Views.py def add_user_to_project(request, project_id): if request.method == "POST": form3 = AddUserForm(request.POST) if form3.is_valid(): Projet.users.add(form3.cleaned_data["user"]) return redirect("...") else: form3 = AddUserForm() return render(request, "createmembers.html", {"projet":Projet, "form3": form3}) Is this correct? What should I do next please? -
'User' object has no attribute 'get_all_permissions'
'User' object has no attribute 'get all permissions'!!! class UserManager(BaseUserManager): def create_user(self, email, username, full_name, phone, password): if not email: raise ValueError('plz input email') if not username: raise ValueError('plz input username') if not full_name: raise ValueError('plz input full_name') if not phone: raise ValueError('plz input phone') user = self.model(email=self.normalize_email(email), username=username, full_name=full_name, phone=phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, full_name, phone, password): user = self.create_user(email, username, full_name, phone, password) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(max_length=50, unique=True) username = models.CharField(max_length=100, null=True, blank=True, unique=True) full_name = models.CharField(max_length=300) phone = models.CharField(max_length=15) address = models.CharField(max_length=500) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) permission = models.ManyToManyField(Permission, related_name='users') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'full_name', 'phone'] objects = UserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser @property def is_staff(self): return self.is_admin -
Django Form Field Query
I have a field in my form that is a model based field and is currently pulling all students within the database. What I am trying to do is limit the amount of students in that field to a query. Attached is my forms.py, views.py , and my models.py . The query currently in my views called student_name is exactly what I want applied to the field on the form called student_name. How do I accomplish this ? Thanks views.py if request.method == "GET": class_name = Section.objects.get(sectionpsid=classid) getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid__student_name', flat = True) student_name = getstudents.all().order_by('studentpsid') my_class_id = request.session['my_class_id'] sectionpsid = Section.objects.get(sectionpsid = my_class_id) form = Rapid_Fire_Form() context = ({'form': form, 'my_class_id': my_class_id, 'sectionpsid':sectionpsid, 'student_name': student_name}) return render(request, 'points/rapid_fire.html', context ) forms.py class Rapid_Fire_Form(forms.ModelForm): class Meta: model = K8Points fields = ('student_name', 'behavior','academic', 'time_frame','date','day','week_of','sectionpsid') labels = {'sectionpsid':_('Section Name'),'student_name':_('Student Name'),'time_frame':_('Time Frame') } def __init__(self, *args, **kwargs): super (Rapid_Fire_Form,self).__init__(*args,**kwargs ) self.fields['date'].disabled = True self.fields['day'].disabled = True self.fields['week_of'].disabled = True def clean(self): cleaned_data = super(Rapid_Fire_Form, self).clean() date = cleaned_data.get("date") time_frame = cleaned_data.get("time_frame") student_name = cleaned_data.get("student_name") if K8Points.objects.filter(date=date, time_frame=time_frame, student_name=student_name).exists(): raise forms.ValidationError('Error: This timeframe {} was already logged to the student {} on {}'.format(time_frame, student_name.student_name, date)) Model K8 Point Tracking System class K8Points(models.Model): date … -
Read data from Django templates in Vue when using webpack_loader
I'm just getting started with django-webpack_loader. I followed this guide and I now have a setup that allows me to inject vue components and pages into django templates. I have a component Question.vue that looks like this: <template> <div class="question_box"> <p class="question_text"> {{ text }} </p> <p v-for="(answer, index) in answers" :key="index" :class="{ 'correct' : (index + 1) == correct_answer_index}"> <strong>{{ index + 1 }}</strong> {{ answer }} </p> <p> {{ solution }} </p> </div> </template> <script> export default { name: 'Question', props: { }, data: () => { return { text: "", answers: [ ], correct_answer_index: -1, solution: "", } } } </script> I also have a component QuestionHistory.vue whose template looks like this <template> <div id="app"> <!-- will print some <Question />'s here based on django template context --> </div> </template> In my Django template, I get a context dictionary that contains a list of questions that I need to render using the Question component. The template is injected with QuestionHistory: {% load render_bundle from webpack_loader %} <div id="app"> <app></app> </div> {% render_bundle 'chunk-vendors' %} {% render_bundle 'vue_app_question_history' %} The thing is, I don't know how to pass the context received from Django onto my Vue components. If … -
django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P<pk>[0-9]+)$']
im trying to create a django page for update a dta inside database, i made this before in other projects and aways worked, but in my project it returns this error: django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P[0-9]+)$'] i reviewed my code a thousand times and i can't see nothing wrong, even if comparing with the other projects. Obs.: please ignore the css part of my template, i'm not used to write the css inside the html, but as it's just a test i don't create a external file. urls.py: from django.urls import path import tables1.views as vw urlpatterns = [ path('admin/', admin.site.urls, name = 'admin'), path('mytables/', vw.mytables, name = 'mytables'), path('',vw.home), path('table/<int:pk>',vw.table, name = 'tableurl'), path('newtable/',vw.newtable,name = 'newtable'), path('update/<int:pk>',vw.update,name = 'update'), path('delete/<int:pk>',vw.delete,name = 'delete'), path('new/',vw.new, name = 'newurl') ] models.py: class Table(models.Model): idd = models.AutoField(primary_key=True, default=None) name = models.CharField(max_length=100) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Tables' def __str__(self): return self.name class Transacao(models.Model): # Forein key defined here date = models.DateTimeField(auto_now_add=True) desc = models.CharField(max_length=200) value = models.DecimalField(max_digits=7, decimal_places=2) obs = models.TextField(null=True, blank=True) tableid = models.CharField(max_length=3) class Meta: verbose_name_plural = 'Transacoes' def __str__(self): return self.desc views.py: from .models import Table from … -
Django ajax How would I change my code to use ajax to like posts without refreshing
I'm trying to create a like button. Currently I have it so that user's can like/unlike a post on an article. However, whenever they press the button, the page resets and takes them back to the top. I want to use Ajax to fix this. These are my files. index.py <form action="{% url 'like-article-view' %}" method="POST" class="mb-1"> {% csrf_token %} <input type="hidden" name="article_id" value={{article.id}}> <button type="submit" class="ui primary button" name="{{article.id}}" id="like-unlike-btn"> {% if user not in article.liked.all%} Like {% else %} Unlike {% endif %} </button> view.py def like_unlike_post(request): user = request.user.id if request.method == 'POST': article_id = request.POST.get('article_id') article_obj = Article.objects.get(id=article_id) user_ = CustomUser.objects.get(id = user) if user_ in article_obj.liked.all(): article_obj.liked.remove(user_) else: article_obj.liked.add(user_) like, created = Like.objects.get_or_create(user=user_, article_id=article_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' else: like.value='Like' article_obj.save() like.save() return redirect('index') urls.py (relevant urls) path('', views.indexView, name="index") path('liked/', views.like_unlike_post, name='like-article-view'), models.py (relevant models) class Article(models.Model): title = models.CharField(max_length=100) description = models.TextField() category = models.ForeignKey(Category, on_delete = models.CASCADE) liked = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='likes') LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) How would I implement Ajax in this? I've … -
Django: query set, multiple filters. Can i set the order in which the WHERE clause is formed so that it will help me in indexing
I have the following query in django: end_date = timezone.now() start_date = end_date + timedelta(-5*365) queryset = ( DailyPriceHistory .objects .filter(symbol=symbol,datetime_utc__range=(start_date, end_date)) .order_by('datetime') .order_by('creation_time') .values_list('high','low','open','datetime','close','creation_time') ) the Sql it generates is SELECT `daily_price_history`.`high`, `daily_price_history`.`low`, `daily_price_history`.`open`, `daily_price_history`.`datetime`, `daily_price_history`.`close`, `daily_price_history`.`creation_time` FROM `daily_price_history` WHERE (`daily_price_history`.`datetime_utc` BETWEEN '2015-12-04 18:43:28.710229' AND '2020-12-02 18:43:28.710229' AND `daily_price_history`.`symbol` = 'A') ORDER BY `daily_price_history`.`creation_time` ASC Currently i have symbol and datatime as seperately indexed columns I found why the filter sequence is not followed. i.e .filter(symbol=symbol,datetime_utc__range=(start_date, end_date)) I wanted WHERE (`daily_price_history`.`symbol` = 'A' AND `daily_price_history`.`datetime_utc` BETWEEN '2015-12-04 18:43:28.710229' AND '2020-12-02 18:43:28.710229') but it uses WHERE (`daily_price_history`.`datetime_utc` BETWEEN '2015-12-04 18:43:28.710229' AND '2020-12-02 18:43:28.710229' AND `daily_price_history`.`symbol` = 'A') Also i dont see order_by('datetime') in the sql, is this because datetime is indexed -
DoesNotExist at /profile/1/ Profile matching query does not exist
My experience using Django is limited, but I hope I can explain my problem clearly. After successfully login to an application I am developing, I get re-directed to a user-page where I have different links. The error "DoesNotExist at /profile/1/ Profile matching query does not exist." occurs once I click on these links. My model looks like this. from django.db import models from numpy import array from django.db.models import F from django.contrib.auth.models import User from user.models import Profile class Data(models.Model): posted_by = models.ForeignKey(User, null=True, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) Product = models.CharField(max_length=20, default="") item = models.CharField(max_length=20, null=True) quantity = models.IntegerField() price = models.IntegerField(default=0) total = models.IntegerField(editable=True,blank=True, null=True) date_created = date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.profile) def save(self, *args, **kwargs): self.total = self.price * self.quantity super().save(*args, **kwargs) @classmethod def get_projects(cls): projects = Data.objects.all() return projects @classmethod def find_projects(cls, search_term): project = Data.objects.filter(title__icontains=search_term) return project class Sales(models.Model): sales = models.IntegerField(default=0, blank=False, null=False) margin = models.IntegerField(editable=True, blank=True, null=True) user = models.ForeignKey(Profile,max_length= 20 ,null=False, on_delete=models.CASCADE, related_name='username') date_created = date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.user) def save(self, *args, **kwargs): self.margin = self.sales - Data.objects.get().total if self.sales > self.margin: self.margin = self.margin else: -self.margin return super().save( *args, **kwargs) UserModel is the …