Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'str' object is not callable when i am trying to delete from Django admin interface?
getting this error when i am trying to delete from django admin panel TypeError at /admin/carts/cart/21/delete/ 'str' object is not callable Request Method: GET Request URL: http://localhost:8000/admin/carts/cart/21/delete/ Django Version: 2.2.6 Exception Type: TypeError Exception Value: 'str' object is not callable Exception Location: C:\Users\HP\spippt\ppt\lib\site-packages\django\db\models\deletion.py in collect, line 224 Python Executable: C:\Users\HP\spippt\ppt\Scripts\python.exe Python Version: 3.7.0 Python Path: ['C:\Users\HP\spippt\ppt\myproject', 'C:\Users\HP\spippt\ppt\Scripts\python37.zip', 'C:\Users\HP\spippt\ppt\DLLs', 'C:\Users\HP\spippt\ppt\lib', 'C:\Users\HP\spippt\ppt\Scripts', 'C:\Users\HP\AppData\Local\Programs\Python\Python37-32\Lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\HP\spippt\ppt', 'C:\Users\HP\spippt\ppt\lib\site-packages'] Server time: Wed, 11 Dec 2019 12:14:29 +0530 -
Memory leak in Django Server?
I am running daphne server on production. I am running 8 python processes on same machine, each on different ports. Problem is that the memory used by each process keeps on increasing over time from 2.5% on start to 11-12% after 12 hours. After sometime, the process restarts as well. Is this general behavior or am I missing something? output of top after 1 hour 15623 root 20 0 5202920 337408 50704 S 50.5 4.6 21:52.55 daphne 15624 root 20 0 5024892 335028 50344 S 30.2 4.6 22:21.99 daphne 15726 root 20 0 5111504 334544 50656 S 42.2 4.6 24:45.48 python 15626 root 20 0 5091180 332068 50224 S 33.2 4.5 22:40.56 daphne 15627 root 20 0 5143132 327988 50176 S 32.6 4.5 21:50.83 daphne 15625 root 20 0 5092620 320452 49908 S 29.2 4.4 20:50.55 daphne I am using supervisor, daphne, django-channel, django-rest-framework. Is there a way to detect when is this memory leak happening, if this is a memory leak. -
How could I save my input from a check box wherein when I check only one option on the box it gave me an error
How could I save my input from a check box wherein when I check option1 of the box and save it it gives me an error saying there is no value on option2 or vice versa. But when i marked them both. I was able to save it on the database, problem is on my database it should only show either value of 1 or 0 and null if there is no input. 1 if its regular and 0 if its special and if either of them has input the other one should be null. Here is my html code for now. <div class="col-md-6"> <div class="form-group bmd-form-group"> <input type="checkbox" name="is_regular" value="1"> Regular<br> <input type="checkbox" name="is_special" value="0"> Special<br> </div> </div> Model forms class Save_Holiday_Form(ModelForm): class Meta: model = Holiday fields = ['holiday_id', 'holiday_name', 'is_regular', 'is_special', 'date_start', 'date_end'] Views.py def add_holidays(request): holiday_name = request.POST['holiday_name'] date_start = request.POST['date_start'] date_end = request.POST['date_end'] is_regular = request.POST['is_regular'] is_special = request.POST['is_special'] holiday_info = Holiday( holiday_name=holiday_name, date_start=date_start, date_end=date_end, is_regular=is_regular, is_special=is_special ) holiday_info.save() return render(request, 'holidays.html') -
How to access views written in mongodb using mongoengine?
In one of my project, I'm using mongoengine 0.9 and pymongo 2.8 for the database and python django as a framework. I came through the view concept in mongodb and created a view in the database for a model named User. I can access the data from User model like in the code below added. But I don't know how to access the view from mongodb using mongoengine. Anyone have any suggestion, please help? user_list = User.objects(active=True) -
Django - get user id after saving the user
I'm working on a project using Python(3.7) and Django(2.2) in which I have implemented models for multiple type of users and combined models by using MultiModleForm to display as a single form on front end, after that when I try to create a user in view and call the save method for user model and try to get its id but it's giving an error. Here's what I have tried so far: From models.py: class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contact_email = models.EmailField(blank=False) customer_id = models.BigIntegerField(blank=False) contact_no = PhoneNumberField(blank=True, help_text='Phone number must be entered in the' 'format: \'+999999999\'. Up to 15 digits allowed.') collection_use_personal_data = models.BooleanField(blank=False) From forms.py: class ParentForm(forms.ModelForm): class Meta: model = Parent fields = ('contact_email', 'contact_no', 'collection_use_personal_data') class UserParentForm(MultiModelForm): form_classes = { 'user': UserForm, 'profile': ParentForm } From views.py: def post(self, request, *args, **kwargs): print(request.POST) user_type = request.POST.copy()['user-user_type'] form = None if user_type == 'PB': form = UserBelow18Form(request.POST) elif user_type == 'PA': form = UserAbove18Form(request.POST) elif user_type == 'Parent': form = UserParentForm(request.POST) print('user-parent form selected') elif user_type == 'GC': form = UserGCForm(request.POST) if form.is_valid(): user = form['user'] profile = form['profile'] if user_type == 'Parent' or user_type == 'GC': c_id = generate_cid() profile.customer_id = c_id print('id generated for … -
I am trying to insert data into db from Django view file. No error but data is not saving into db
I am trying to insert data into DB from a Django view file. No error but data is not saving into DB. I am trying scrape data from flipkart page, it is not showing any error but data is not saving into db def scrape_view(request): session=requests.Session() my_url="https://www.flipkart.com/mobiles/pr?sid=tyy%2C4io&p%5B%5D=facets.brand%255B%255D%3DRealme&otracker=nmenu_sub_Electronics_0_Realme&sort=price_asc" #link which I want t scrape uclient=session.get(my_url,verify=False).content page_soup=soup(uclient,"html.parser") containers=page_soup.findAll("div",{"class":"_3O0U0u"}) for container in containers: product_name=container.div.img["alt"] price_container=container.findAll("div",{"class":"_1vC4OE _2rQ-NK"}) price=(price_container[0].text) rating_container=container.findAll("div",{"class":"hGSR34"}) rating=rating_container[0].text new_redmi=Redmi_Mobiles() new_redmi.model_name=product_name new_redmi.price=price new_redmi.rating=rating new_redmi.save() return redirect('home') #models.py class Redmi_Mobiles(models.Model): model_name=models.CharField(max_length=200) price=models.CharField(max_length=10) rating=models.FloatField() def __str__(self): return self.model_name -
Cannot run migration command for django
I'm trying to practice and learn django to create a webapp and when I run the "python manage.py migrate" command, I get this error "django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")". What is the possible cause and how can it be fixed? -
I am getting (Cannot assign "11": "Notification.user_to_notify" must be a "User" instance.) in Django
Below is my code. I have 2 models Post and Notification. Whenever any user likes any post i am adding that to notifications tables. and getting 'Cannot assign "11": "Notification.user_to_notify" must be a "User" instance.' this error. #Post model class Post(models.Model): title = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='images/',blank=True) posted_by = models.ForeignKey(User, on_delete=models.CASCADE) #Notification model class Notification(models.Model): user_to_notify = models.ForeignKey(User, related_name = 'user_to_notify',on_delete=models.CASCADE) user_who_fired_event = models.ForeignKey(User, related_name= 'user_who_fired_event' ,on_delete=models.CASCADE) event_id = models.ForeignKey(Event, on_delete=models.CASCADE) seen_by_user = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) postExists = Post.objects.get(pk=post_id) # posted_by is having relation with User notification = Notification() notification.user_to_notify = postExists.posted_by.id(ERROR) #also tried notification.user_to_notify = postExists.posted_by(Still getting ERROR) -
Field return count of another table
I need that read_booksfield (in Purchased), return the Rating objects count. Should return the number of objects according to the filter of the same collections of each book in Rating and the same user. I don't know how to do this because Rating and Purchased are not directly dependent. rating/models.py class Rating(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) book = models.ForeignKey(Statement, on_delete=models.CASCADE, null=False) rating = models.IntergerField(default=0) book/models.py class Books(models.Model): collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING, blank=True, null=True) book = models.CharField(max_length=250, blank=True, null=True) collection/models.py class Collection(models.Model): title = models.CharField(max_length=50) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) purchased_collections/models.py class Purchased(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING) date = models.DateTimeField(default=datetime.now) read_books = models.IntegerField(default=0) -
How to Aggregate QuerySet for Arbitrary Keys Group By
<QuerySet [ {'id': 520, 'Commission': None, 'Effective Date': '2019-12-11 00:00:00+00'}, {'id': 520, 'Commission': 30, 'Effective Date': None} ]> Suppose I had a Django QuerySet like the above, with an arbitrary number of matching keys where only one is expected to not be null per key. How do I get a result like the following per id as if I'm grouping by id? <QuerySet [ {'id': 520, 'Commission': 30, 'Effective Date': '2019-12-11 00:00:00+00'} ]> -
Django models.ImageField does not validate image file (data sent by axios)
I'm using Django as my backend and React as my front. I want the users to be able to upload their photos, and I managed to do that recently. This is how the users send their photo in the front. addUserImage = (Image, id) => (dispatch) => { axios.post(`/api/${id}/image`, Image, { headers: { 'Content-Type': 'multipart/form-data', }, }) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err); alert('Your image file is not valid. Please check again.'); }); }; onChange = (e) => { if (e.target.files.length !== 0) { if (e.target.files[0].size > 50000000) { alert(`'${e.target.files[0].name}' is too large, please pick a smaller file`); } else { this.setState({ selectedImage: e.target.files[0] }, () => { const formData = new FormData(); formData.append( 'Image', this.state.selectedImage, ); //this.props.onUploadPhoto calls addUserImage from above. this.props.onUploadPhoto(formData, this.props.selected_object.id); }); } } } <Button variant="contained" component="label" > <input type="file" id="image" accept="image/png, image/jpeg, image/pjpeg, image/gif" onChange={this.onChange} style={{ display: 'none' }} /> Upload An Image! </Button> This code manages to show normal images successfully. However, I'm worried that some users might just upload fake image files(e.g. Forcefully changed extensions). I heard that Django's models.ImageField performs image validation. This is my related backend code. //views.py def post_photo(request, id): if request.method == 'POST': if request.user.is_authenticated: try: … -
Export file to csv but when it wont show the file in django
So i try to export result of query into csv files, but when i do , it says success , but i dont see where is the file , or the file being download in the browser , i already search the file but i dont find it anywhere, here's the code AJAX in html <script> $(document).ready(function() { $("#export").click(function () { var urls = "{% url 'polls:export' %}"; var name = $('#columnselect').val(); var table = $('#dataselect').val(); var column = $('#conditionselect').val(); var operator = $('#operator').val(); var condition = $('#parameter').val(); $.ajax({ url: urls, data: { 'name' : name, 'table': table, 'column' : column, 'operator' : operator, 'condition' : condition }, success: function(data) { alert("success"); }, error: function(data) { alert("error occured"); } }); }); }); </script> urls.py path('export/',views.export,name='export'), views.py def export(request): import cx_Oracle data_name = request.GET.get('name',1) table_name = request.GET.get('table',1) column_name = request.GET.get('column',1) operator = request.GET.get('operator',1) condition = request.GET.get('condition',1) dsn_tns = cx_Oracle.makedsn('IP', 'PORT', sid='') conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns) c = conn.cursor() c.execute("select "+data_name+" from "+table_name+" where "+column_name+operator+"'"+condition+"'") c.rowfactory = makeDictFactory(c) columnalldata = [] for rowDict in c: columnalldata.append(rowDict[data_name]) context = { 'obj4' : columnalldata } response = HttpResponse(content_type ='text/csv') response['Content-Disposition'] = 'attachment;filename="output.csv"' writer = csv.writer(response) writer.writerow(context) print(response) return response can someone find where … -
Can't GET user information with token using django-rest-knox TokenAuthentication
I'm a bit of a newbie to Django and authentication (I'm loosely following this tutorial) and I've searched all over and can't find anything that has helped me fix this problem. I'm using django-rest-knox to generate authorization an token(s) for a user and then attempting to send the token back (using Postman) to GET the user's information (id, username, and email) in a response from the server. I can get the tokens fine using my LoginAPI class, but when I try to pass the token back in a GET request to my UserAPI class, I get a 401 response with the following body: { "detail": "Authentication credentials were not provided." } Postman Screenshot Code from my python files is below. Any help is much appreciated. urls.py from .api import LoginAPI, UserAPI from django.urls import path, include urlpatterns = [ path('api/auth/login/', LoginAPI.as_view()), path('api/auth/user/', UserAPI.as_view()), path('api/auth/knox/',include('knox.urls')), ] api.py from rest_framework import permissions, generics, authentication from rest_framework.response import Response from knox.models import AuthToken from .seralizers import UserSerializer, LoginSerializer # Login API class LoginAPI(generics.GenericAPIView): permission_classes = [permissions.AllowAny, ] serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Get User … -
Django: Which one do you recommend? I have to replace django-facebook library
I have to replace django-facebook library. I thought I use social-auth-app-django libaray or python-social-auth ver0.2.1. I heard social-auth-app-django library can be used on Django version more than 1.8. But problem is django version is 1.8. I wonder which one choice is more wise. 1. Upgrade Django version 1.8 to 1.1 . 2. Replace django-facebook library to python-social-suth ver0.2.1 . Help :( -
How to leave a radio button selected by default according to a Django field?
File models.py: class AbstractRating(models.Model): stars = models.PositiveSmallIntegerField() user = models.ForeignKey(User, on_delete = models.CASCADE) content = models.TextField() created = models.DateTimeField(auto_now_add = True) class Meta: abstract = True class Rating(AbstractRating): course = models.ForeignKey(Course, on_delete = models.CASCADE) class Meta: verbose_name = 'calificación del curso' verbose_name_plural = 'calificaciones del curso' def __str__(self): return self.course.title I am trying to make a star rating system, the stars are defined in the stars field, the problem occurs at the moment of updating any instance of the Rating model. I need to leave a radio button selected by default (checked) according to the value of the stars field, but I don't know how to do it. Basically the problem is to set the attribute marked on the correct radio button. But I do not know how to do it. You may have to use templates tags, but I don't know how to do it, I already tried. Any solution? File HTML: <div class="rating-stars"> <input type="radio" name="stars" value="1" id="1"> <input type="radio" name="stars" value="2" id="2"> <input type="radio" name="stars" value="3" id="3"> <input type="radio" name="stars" value="4" id="4"> <input type="radio" name="stars" value="5" id="5"> </div> File views.py: class RatingUpdateView(LoginRequiredMixin, CheckCourseOwnerAndRatingMixin, UpdateView): model = Rating form_class = RatingForm template_name = 'ratings/rating_update_form.html' success_url = reverse_lazy('courses:list-of-user') def … -
Django NoReverseMatch using views parameter
i am doing a inventory app and i have included actions(CRUD) to perform on the saved items. However when a click on 'dispatch' i get this error, NoReverseMatch at /inventory Reverse for 'dispatch' with arguments '('hhe/ge/3.009/67-8',)' not found. 1 pattern(s) tried: ['dispatch/(?P[^/]+)$'] hhe/ge/3.009/67-8 is one of model_numbers. dispatch_view in views.py def dispatch_view(request,model_number): if request.method=='POST': dispatch_item=New_asset.objects.get(model_number=model_number) form= dispatch_form(request.POST,instance=dispatch_item) if form.is_valid(): post = form.save(commit=False) post.save() return HttpResponseRedirect('/inventory') else: form = dispatch_form() return render(request, 'dispatch.html', {'form': form,'dispatch_item':dispatch_item}) url.py path('dispatch/<str:model_number>', views.dispatch_view,name='dispatch'), url(r'^inventory$', views.allassets,name='inventory'), inventory.html {% for asset in query %} <tr class="clickable-row"> <td>{{asset.asset_name}}</td> <td>{{asset.model_number}}</td> <td>{{asset.quantity_received}}</td> <td>{{asset.specification}}</td> <td>{{asset.supplied_by}}</td> <td>{{asset.department_assigned}}</td> <td>{{asset.date_received}}</td> <td><a href=" {%url 'dispatch' asset.model_number%}"><span class="glyphicon glyphicon-pencil" >Dispatch</span></a> Thanks -
ValueError: Cannot assign object must be a instance
I have been trying to register a ClienteNatural, which has two foreign keys, one of Correo and another of Lugar. When making the query in the database to pass the Correo object to the ClienteNatural, I get this error, if someone can help me. Thank you. Momentarily I put a fixed value to Lugar just to test, then I will make it dynamic, but that Lugar object that I assign to fk_lugar doesn't generate an error, just fk_correo. Error: *** ValueError: Cannot assign "'Correo object (22)'": "ClienteNatural.fk_correo" must be a "Correo" instance. Models.py class ClienteNatural(models.Model): rif = models.CharField(primary_key=True, max_length=12) carnet_id = models.IntegerField(blank=True, null=True) complemento_direccion = models.CharField(max_length=25) puntos_disponibles = models.IntegerField(blank=True, null=True) cedula = models.CharField(max_length=12) primer_nombre = models.CharField(max_length=12) segundo_nombre = models.CharField(max_length=12, blank=True, null=True) primer_apellido = models.CharField(max_length=12) segundo_apellido = models.CharField(max_length=12) fk_lugar = models.ForeignKey('Lugar', db_column='fk_lugar', on_delete=models.CASCADE) fk_correo = models.ForeignKey('Correo', db_column='fk_correo', on_delete=models.CASCADE) class Meta: managed = False db_table = 'cliente_natural' class Correo(models.Model): codigo = models.AutoField(primary_key=True) usuario = models.CharField(unique=True, max_length=30) class Meta: managed = False db_table = 'correo' class Lugar(models.Model): codigo = models.AutoField(primary_key=True) nombre = models.CharField(max_length=50) tipo = models.CharField(max_length=50) fk_lugar = models.ForeignKey('self', models.DO_NOTHING, db_column='fk_lugar', blank=True, null=True) class Meta: managed = False db_table = 'lugar' forms.py class Cliente_Natural_Form(forms.ModelForm): rif = forms.CharField(max_length=12, required=True) carnet_id = forms.IntegerField complemento_direccion = … -
Django: looping through filtered list in template
I have an html template where I would like to loop through objects in a model (SpeciesPage) which are filtered by a certain field value (subfamily_name="Pierinae") and display them in a list. The filtered results span multiple foreign key relationships. Ultimately, I want the template to loop through and display multiple filtered results in separate lists, but I cannot get anything to render looping through one filtered list. I feel like what I'm trying to accomplish should be simple. models.py (abbreviated to show only relevant fields) class Subfamily(models.Model): subfamily_name = models.CharField(max_length=200) class Tribe(models.Model): subfamily = models.ForeignKey(Subfamily, on_delete=models.SET_NULL, null=True) tribe_name = models.CharField(max_length=200) class Genus(models.Model): tribe = models.ForeignKey(Tribe, on_delete=models.SET_NULL, null=True) genus_name = models.CharField(max_length=200) class Species(models.Model): genus = models.ForeignKey(Genus, on_delete=models.SET_NULL, null=True) species_name = models.CharField(max_length=200) species_page = models.OneToOneField('SpeciesPage', on_delete=models.SET_NULL, null=True) class SpeciesPage(models.Model): title = models.CharField(max_length=100, primary_key=True) species_name = models.OneToOneField(Species, on_delete=models.SET_NULL, null=True) views.py class SpeciesPageListView(generic.ListView): model = SpeciesPage template_name = 'speciespage_list.html' def show(request): pierinae_pages = SpeciesPage.objects.filter(species_name__genus__tribe__subfamily__subfamily_name="Pierinae") context = { 'pierinae_pages': pierinae_pages, } return render(request, 'speciespage_list.html', context=context) speciespage_list.html ... {% for speciespage in pierinae_pages %} <tr> <td><i>{{ speciespage.title }}</i></td> ... </tr> {% endfor %} ... I used the following answers from here in an attempt to solve my problem: Cannot use filter inside Django template html … -
How to import dbpedia data into arangodb for use in a django website?
I'm new to programming and just learnt python and some django basics. I want to build a website to display wikipedia data in a particular format and also display the connections using plotly dash. However i'm unable to find instructions on how to import dbpedia data into arango db so as to store objects/entities as documents with attributes and map the graph of relationships. Something like relfinder on dbpedia website, offering more info along with it. Is it possible to first setup arango db in django and then use sparql querying with python to build my own dataset according to requirements? If yes, please provide some instructions or link some resources with info on how to do it. Is there any other way I could achieve this in an easier way? -
DateInput - Enter a valid date
I have a form field that I want to have as a calendar widget that defaults to the current date. I had it so it was showing the date in d/m/y format but when I'd submit it would say Enter a valid date forms.py class CreateBlogPostForm(forms.ModelForm): published = forms.DateField() class Meta: model = BlogPost fields = ('title', 'published','featured_image', 'post',) widgets = { 'title': forms.TextInput(attrs={'class': 'testimonial-name-field', 'placeholder': 'Title'}), 'published': forms.DateInput(format=('%d-%m-%Y'), attrs={"type": 'date'}), 'post': forms.TextInput(attrs={'class': 'blog-post-field', 'placeholder': 'Write something..'}), } models.py class BlogPost(models.Model): title = models.CharField(max_length=100) published = models.DateField() featured_image = models.ImageField(upload_to='blog/%Y/%m/%d') post = models.TextField() slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Blog" def __str__(self): return self.title create-blog.html {% extends 'base.html' %} {% block content %} <div class="container text-center"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form.title}} {{form.post}} {{form.featured_image}} {{form.published}} {{form.errors}} <button type="submit" class="btn btn-primary"><i class="fa fa-plus" aria-hidden="true"></i> Submit</button> </form> </div> {% endblock content %} -
Angular Routing structure for Webshop with Filter
Im working on a Angular Webshop with Django Backend. I filter the articles by multiple parameters like brand,Color, gender or category. To avoid nasty hardcoding and URLs I tried Angular routing, where I used query parameters at the end of the URL for each filter option. But there are many variations, because of the filters the user can pick. So I‘m searching for a better way to solve this issue. The main Idea was a structure like „www.example.com/Gender/Brand/Category...“. But because the user can choose the filter individually, the Routing Params from Angular wouldn’t be clearly associated to a single filter option (first path wouldn’t be Gender if the user just picks the filter „Adidas“ -> URL: www.example.com/Adidas“). So how can I associate the Routing Param with a variable to pass it to the Django Filter ? import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; import {RouterModule} from '@angular/router'; import {AppComponent} from './app.component'; import {HomepageComponent} from './home/homepage.component'; @NgModule({ declarations: [ AppComponent, HomepageComponent ], imports: [ BrowserModule, HttpClientModule, RouterModule. Module.forRoot([ {path: 'home', component: HomepageComponent}, {path:':param1', component: filteredListCompoment }, {path:':param1/:param2', component: filteredListCompoment}, {path:':param1/:param2/ :param3', component: filteredListCompoment}, {path: '**', redirectTo: '', pathMatch: 'full'} ]), ], bootstrap: [AppComponent] }) export class … -
Should I use Generic Relations or One To One?
I'm making a social media website and I'm currently coding the comments, different types of posts and reports (the models). I read that when using Generic Relations, the ORM would use N queries to get all the related content. I know this can be quit hard on runtimes and memory, so should I use One To One fields instead of Generic Relations? Someone on another post said to not prematurely optimize your site, but it couldn't hurt to do what you can for optimization so there are less updates later right? Side question, could I further optimize the site (say when a user is looking at a post) by querying for a few comments and only load more when the user clicks the 'load more' button? -
StaticLiveServerTestCase log in not working
I am currently trying to conduct functional testing on my django website using the StaticLiveServerTestCase. However, I cannot get passed my login page. It says that my username and password are incorrect, which leads me to believe that I am saving my user incorrectly. My test case is down below. I have seen several post regarding a login issue but none of them have helped my situation. Please let me know if you have any advice for how to correct this. class EmpTest(StaticLiveServerTestCase): def setUp(self): self.selenium = WebDriver() self.emp = User.objects.create(username='testuser0', password='password') self.emp.save() def tearDown(self): self.selenium.close() def test_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/accounts/login/')) username_input = self.selenium.find_element_by_id("id_username") username_input.clear() username_input.send_keys(self.emp.username) password_input = self.selenium.find_element_by_id("id_password") password_input.clear() password_input.send_keys(self.emp.password) self.selenium.find_element_by_xpath('//button[text()="Log in"]').click() time.sleep(15) -
Find Unique Value and attach all related values in Array of Objects
I want to create an array of objects. I have all the variables and need to just format all the values. These are my values: url = "Goodreads", search = "Fantasy", search_res = [ { "book": "Harry Potter", "rating": "10.0" }, { "book": "Lord of The Rings", "rating": "9.0" } ] url = "GoodReads", search = "Dystopia", search_res = [ { "book": "Handmaids Tale", "rating": "9.0" }, { "book": "Divergent Series", "rating": "8.5" } ] url = "Kindle", search = "Fantasy", search_res = [ { "book": "Twilight Series", "rating": "5.5" }, { "book": "A Discovery of Witches", "rating": "8.5" } ] url = "Kindle", search = "Dystopia", search_res = [ { "book": "Hunger Games", "rating": "9.5" }, { "book": "Maze Runner", "rating": "6.0" } ] My code: assign_url = url the_list = [] urls = { 'the_url' : assign_url, 'results' : [] } data['search'] = search data['results'] = search_res urls['results'].append(data) the_list.append(urls) pprint(json.dumps(the_list)) My Result: ('[{"the_url": "GoodReads", "results": [{"search": "Fantasy", ''"results": [{"book": "Harry Potter", "Rating": "10.0"}, {"book": "Lord of The Rings", "Rating": "9.0"}]}]}]') ('[{"the_url": "GoodReads", "results": [{"search": "Dystopia", ''"results": [{"book": "Handmaids Tale", "Rating": "9.0"}, {"book": "Divergent Series", "Rating": "8.5"}]}]}]') ('[{"the_url": "Kindle", "results": [{"search": "Fantasy", ''"results": [{"book": "Twilight Series", "Rating": "5.5"}, {"book": … -
Duplicate Values with Foreign Key in Django Model
So I have a few models in my django app that look like this: class WHID(models.Model): whid = models.CharField(max_length=8) class Department(models.Model): name = models.CharField(max_length=50) whid = models.ForeignKey(WHID, on_delete=models.CASCADE) I want to have it so that I can't create a duplicate Department name for each WHID. So if I have two entries in the WHID table: id whid 1 whid1 2 whid2 Then in the Department table: name whid Department1 1 Department1 2 Department1 1 <----How do I stop this record from being created Any help is appreciated. Thank you.