Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: __init__() got an unexpected keyword argument 'instance' for custom user in Django
When I am trying to register a custom user or when i am trying to view profile of login user, i am getting this error. I am not sure why i am getting this error, Here is my code, please suggest where i am doing wrong. Thank you in advance. Url.py path('register/', RegisterView.as_view(template_name='users/register.html'), name='register'), path('profile/', user_views.profile, name='profile'), Model.py user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=254, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the absence of a "Password field", that is built in. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Email & Password are required by default. objects = UserManager() ``` Form.py ``` class RegisterForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: Model = User fields = ('email',) def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean_password2(self): # Check that the two password … -
Template extending not working properly - Django
i have 3 files, Base.html, Navbar.html and dashboard.html. im trying to extend base.html and include navbar.html in dashboard. its getting extended but the problem is then dashboard's content data is not visible. If i remove navbar.html it works but no navbars. Below are the files pls check and help to resolve. Navbar.html {% load static %} <!-- Navbar --> <nav class="main-header navbar navbar-expand navbar-white navbar-light"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a> </li> <li class="nav-item d-none d-sm-inline-block"> <a href="dashboard" class="nav-link">Home</a> </li> </ul> <!-- SEARCH FORM --> <form class="form-inline ml-3"> <div class="input-group input-group-sm"> <input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search"> <div class="input-group-append"> <button class="btn btn-navbar" type="submit"> <i class="fas fa-search"></i> </button> </div> </div> </form> <!-- Right navbar links --> <ul class="navbar-nav ml-auto"> <div class="dropdown-divider"></div> </ul> # Side configutarion {# <li class="nav-item">#} {# <a class="nav-link" data-widget="control-sidebar" data-slide="true" href="#" role="button">#} {# <i class="fas fa-th-large"></i>#} {# </a>#} </nav> <!-- /.navbar --> <!-- Main Sidebar Container --> <aside class="main-sidebar sidebar-dark-primary elevation-4"> <!-- Brand Logo --> <a href="dashboard" class="brand-link"> <img src="{% static 'img/AdminLTELogo.png' %}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> <span class="brand-text font-weight-light">Acro Paints</span> </a> <!-- Sidebar --> <div class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel … -
How to use string of <li> in django view?
I am building a blog where users can click on several <li> items in the sidebar to show blog posts according to the clicked category. So far I managed to show the five latest blog posts on the landing page (blog.html extends base.html) with a load more button to display another five so on and so forth until the pagination is done. Now I would like to extend this logic to use the same views (there are two views, one for the initial 5 posts and one for the pagination - load more logic) for the categories as well to avoid ending up with two views + 1x Ajax function for each category. Is there any dynamic solution to this? My basic idea is to get the string of the clicked <li> item and filter the queryset by the category then to get the correct objects from the database. So the general logic would be the same and each URL would be mapped to the very same view. If my general idea might work, how can I use the clicked string within the view function to adjust the queryset? views.py def render_blog(request): # Get 5 latest posts and order by … -
Django - Variable inside style not detected
{% if photos %} {% for photo in photos %} {% endfor %} {% else %} No images availble for the project. {% endif %} And I want to add a picture url inside the style tag. div class='image-block col-sm-4' style="background: url({{photo}}) no-repeat center top;background- size:cover;" How can I get the {{photo}} url inside the string? -
Blank field not working correctly in Django model
I have a Django model described as follows- class Building(models.Model): name = models.CharField(max_length=25,unique=True,blank=False) country = models.CharField(max_length=20,blank=False) city = models.CharField(max_length=20,blank=False) def __str__(self): return self.name All of the fields are required as blank is set to False in each of them but still, I am able to save objects for this model by leaving city and country as blank. -
virtualenv could not install on my machine due to permission denied
creating c:\program files\python38\Lib\site-packages\distlib error: could not create 'c:\program files\python38\Lib\site-packages\distlib': Access is denied ---------------------------------------- How do I fix this? I tried to install virtualenv and django but got the error above -
Elastic Beanstalk: /bin/sh: /opt/python/run/venv/bin/activate: No such file or directory
Trying to deploy a django app which uses channels following this https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 These are my config files: 01_env.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "dashboard/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "dashboard.settings" PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP Rules: ws aws:elbv2:listenerrule:ws: PathPatterns: /websockets/* Process: websocket Priority: 1 aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP 02_setup.config container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "django-admin.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' When I run eb create django-env it fails with Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. and in the logs, I found that the reason is: 2020-06-17 16:36:41,880 P4189 [INFO] Command 00_pip_upgrade 2020-06-17 16:36:41,883 P4189 [INFO] -----------------------Command Output----------------------- 2020-06-17 16:36:41,883 P4189 [INFO] /bin/sh: /opt/python/run/venv/bin/activate: No such file or directory So even though I'm following the guide, the directory seems to not exist. I'm also not being able to SSH into the EC2 instance to check this. Has the python venv directory in Amazon Linux 2 changed? -
Django Rest Framework : Nested Serializer not working
I have almost tried everything but am not able to reach at the point model.py file class RecievingImages(models.Model): """Original and Masked Images""" .... name = models.CharField(max_length = 100, unique = True, primary_key=True) area = models.IntegerField() number = models.IntegerField() agency_name = models.CharField(max_length=100, default='general') rawImage = models.ImageField(upload_to=imageNameForRawImage,) ... class UpdationImages(models.Model): """ Update Image wrt name""" .... name = models.ForeignKey(RecievingImages, on_delete=models.PROTECT, related_name='updated') updated_image = models.ImageField(upload_to=UpdatedImageFolder,) updated_image_url = models.TextField(default='None') .... serializer.py class UpdatedImageSerializer(serializers.ModelSerializer): model = UpdationImages fields = ('name', 'updated_image', 'updated_image_url') class RecievingImagesSerializer(serializers.ModelSerializer): updated = UpdatedImageSerializer(many= True, read_only=True) model = RecievingImages fields = ('updated','name','area','number','agency_name', rawImage) I have used related_name in the model and also following the documentation along with that with many = True But still in serializer.data updated does not show views.py class MappingSinglePhoto(APIView): """ Mapping Single Image """ def post(self, request): try: data = request.data # import pdb; pdb.set_trace() name_of_image = data['name'] mapped_images_qs = UpdationImages.objects.select_related('name').filter(name = name_of_image) for image in mapped_images_qs: serializer = RecievingImagesSerializer(instance = image) pdb.set_trace() serializer.data # return Response(serializer.data) except Exception as e: print(e) NOTE if I use depth=1 then it's working fine, but I am not looking for all the fields that depth displays. Thanks & Regards -
Django model order by custom algorithm Using the difference between the current time and creation time
Django version 2.1.15 Python version 3.7.4 Djngo settings.py LANGUAGE_CODE = 'ko-kr' TIME_ZONE = 'Asia/Seoul' I am not familiar with English.I will write in English as hard as possible. Django model order by custom algorithm Using the difference between the current time and creation time my model is models.py class Review(models.Model): title = models.CharField(max_length = 100) content = models.TextField() movie = models.ForeignKey(Movie,on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete = models.CASCADE) like_users=models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='like_reviews') created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) i want to Descending order_by (Count(like_users)/(current_time - created_at + 60)) Review model (current_time-created_at) : I want to change the difference between two hours to minutes. (integer) I tested these things. from django.db.models import ExpressionWrapper,F,Value from django.db.models.fields import DurationField,DateTimeField def test(request): now = timezone.localtime() test = Review.objects.annotate(diff_time=(ExpressionWrapper(Value(now, DateTimeField()) - F('created_at'), output_field=DurationField()))).annotate(diff_value=F('diff_time')+60).values() But failed. How can I get the results I want? I used a translator to ask questions, but I hope my intentions are clearly communicated. I'm so sorry for my poor English. -
Django, accessing model methods
In the Django documentation, they recommend writing business logic in Model. How do the View layer or queryset access the methods in Model ? As per example in documentation (https://docs.djangoproject.com/en/3.0/topics/db/models/) from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" How do view layer access the baby_boomer_status ? I have a little experienced in Django development but I used to write logics in View itself. -
join the results of two query on each others with Django
I have 2 models, i simplify them for the example: class CustomerOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) isPaid = models.BooleanField(default=False) and class EventParticipant(models.Model): customerOrder = models.ForeignKey(CustomerOrder, on_delete=models.CASCADE) event = models.ForeignKey(Product, on_delete=models.CASCADE) What i need to do is to display in a table every participants for an event but link the order to the participant so i can display the isPaid status for each participant. I think its similar to a join on SQL. So i tried something like: participants = EventParticipant.objects.filter(event=event_pk).select_related('customerOrder') but when i try to access it like participants.cusomerOrder i get: 'QuerySet' object has no attribute 'customerOrder' so i guess is missunderstand something. Thanks -
Saving a form in a foreign key field
I have two models Order and a date model. The order model has a foreign key attribute of date model. I have made a form in which I can update the date fields of order, but when I click submit it creates a new date object in date model not in the order date field. The order model date field is empty. My views code seems to be alright maybe somethings wrong in my form.py.I want my form to save values in the date field in order. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) view.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if … -
What does "uWSGI is a self-healing application" practically mean?
According to Django Official Documentation: uWSGI is a fast, self-healing and developer/sysadmin-friendly application container server coded in pure C. What exactly are self-healing applications and how is this paradigm implemented by uWSGI? Last but not least, what is the importance of this aspect of uWSGI for django? -
Possible to have react + Django on pythonanywhere.com
Is it possible to deploy react front end app and Django as back end app on pythonanyhere.com? I have django API as back end and React as Front app. -
DICOM image display in Django
How to display DICOM image in my Django 3 template HTML file. I have pydiacom, Pil & Matplotlib installed. I want to send the dicom image from view to template. How can I do this, is it the correct process for I'm doing wrong. -
Find and delete content with BeautifulSoup
I have blog text (application in django) where I want to get rid of some content. I try to search for content using BeautifulSoup. I want to find and delete everything between wphimage tags. Below is my code. What doesn't work is the wphimage tag that appears when I display soup objects after running it, where I did write to obj.text my code class Command(BaseCommand): def handle(self, *args, **kwargs): article = Blogposts.objects.all() for obj in article: soup = BeautifulSoup(obj.text, 'html.parser') for i in soup.find_all('wphimage'): obj.text = str(i.replace_with('')) obj.save() content of blog post Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <wphimage data="{'FileId':6182,'Copyright':'John Smith','Alignment':'left','ZoomDisabled':false,'ImageOnly':false,'AlternativeText':'John Smith','ImageVersion':'conductorportraitlong','tabid':0,'moduleid':0}"> <span style="display:block; float:left;" class="DIV_imageWrapper"> <a data-lightview-title="Adela Frasineanu" data-lightview-caption="" class="lightview" href="//example.com/static/images/image.JPG"> <img src="//example.com/static/images/image.JPG" alt="John Smith"> </a> <a href="javascript:;">≡ <span>John Smith</span></a> <a class="A_zoom lightview" href="//example.com/static/images/image.JPG" data-lightview-title="John Smith" data-lightview-caption="">+ </a> </span> </wphimage> Lorem ipsum dolor sit amet, consectetur … -
Try to display images from a directory in Django
I try to display all images from a directory that is in the project. In the views.py def showimages(request): path='C:\\Users\Peter\PycharmProjects\displayimages\displayimages\display\static' img_list = os.listdir(path) return render(request, 'displayphotos.html', {'images':img_list}) In the html file {% for image in images %} <p>{{image}}</p> <img src="{% static '{{image}}' %}"> {% endfor %} But the display is <p>DSC_5390.jpg</p> <img src="/static/%7B%7Bimage%7D%7D"> <p>DSC_5392.jpg</p> <img src="/static/%7B%7Bimage%7D%7D"> If I print them in paragraph tag, all file names are correct, but all wrong in img tag. How can I fix it? -
What should I change to get access to the context data 'post'?
I have passed the context 'is_liked' to the home page and I have tried to set up the condition of is_liked in PostListView by getting the context data and modify it. But it did not run in the home page without any error message. I am thinking if it is because I have defined the context_object_name to post so that I should change the def get_context_data. Thanks Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context -
Geodjango: how to load .shp file and convert to geojson with the right CRS?
I have multiple shapefiles (.shp) with their auxiliary files that I want to display on a Leaflet map. The shapefiles use different coordinate reference systems (CRS) and I struggle to grasp the most straightforward and reliable way to show things on the map. In the geodjango tutorial, DataSource is used to load a shapefile and then manipulate it. However, in their examples they only retrieve the geometry of individual features, not of the entire shapefile. I have used PyShp and I am able to show a map using something like: sf = shapefile.Reader(filename) shapes = sf.shapes() geojson = shapes.__geo_interface__ geojson = json.dumps(geojson) However, this fails when the CRS is not WGS84 things don't work, and I don't see how to convert it. Reading a bit more, this post complains about CRS support and pyshp, and suggests using ogr2ogr. So after trying to understand the options I see using Datasource, pyshp, and ogr2ogr as possible options, but I don't know which option really makes most sense. All I want is convert a .shp file using Django into a geojson string that uses WGS84, so that I can include it on an HTML page that uses Leaflet. Can anyone with more experience … -
Summation of number in django
I have two models like this: class ItemType(models.Model): type = models.CharField(max_length=100) class Items(models.Model): item_type = models.ForeignKey(ItemType, on_delete=models.CASCADE) item_amount = models.FloatField() now I want to get sum of item_amount according to item_type. How I can do this? -
Dynamic Wagtail bgcolor templatetags
I am trying to get a dynamic background color with Wagtail templatetags when I convert an image like this : {% load wagtailimages_tags %} {% image my_file width-768 format-jpeg bgcolor-171721 as image_jpeg %} <img src="{{ image_jpeg.url }}"/> How I can change the value bgcolor-171721 with a dynamic variable in my template ? -
Log out when sending a form
I've got a problem, i've create an app where you can make comment (wich send a form to a database and save it) if you're login on only, but when i press the button "Create" instead of redirecting me to the page where it show all the comments, it log me out and bring me back to the "log out" view (wich is / ) the create Teamplate : {% extends 'base.html' %} {% block content %} <div class="create_comment"> <h2>Write a comment</h2> <form class="site-form" action="{% url 'create' %}" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> </div> {% endblock %} The Views of Create : @login_required(login_url='/userprofile/login/') def comments_create(request): if request.method == 'POST': form = forms.CreateComment(request.POST) if form.is_valid(): form.save() return redirect('/usercomments') else: form = forms.CreateComment() return render(request,'usercomments/comments_create.html', {'form':form}) Log out view : def logout_view(request): if request.method == 'POST': logout(request) return redirect('/') else: pass -
update() methid in CreateView django
i want to to update field whenever an instance been created i tried signals but it seems complicate to ManyToManyField class MobileCustomer(models.Model): customer = models.CharField(max_length=30) phone = models.CharField(max_length=13) mobile = models.ManyToManyField(MobileStorage,through='SelectMobile') class SelectMobile(models.Model): mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) item = models.ForeignKey(MobileCustomer,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) imei = models.ManyToManyField(Imei) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Mobile(models.Model): mobile_name = models.CharField(max_length=40,unique=True) class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) active = models.BooleanField(default=True) i want to update active field in Imei model when MobileCustomer created !? i tried this in my CreateView form_valid imei = Imei.objects.filter(selectmobile__item=self.object).update(active=False) print(imei) and it printed 0 ? how to make it work either using signals or update() whenever an instance created inside createview -
Django model autogenerate from a legacy mysql database: do I have to change the on_delete parameter's value from models.DO_NOTHING
I write a sql file for a mysql database as follows: create table bank ( bankname VARCHAR(20) not null, city VARCHAR(20) not null, money DOUBLE not null, constraint PK_BANK primary key (bankname) ); create table department ( departID CHAR(4) not null, departname VARCHAR(20) not null, departtype VARCHAR(15), manager CHAR(18) not null, bank VARCHAR(20) not null, constraint PK_DEPARTMENT primary key (departID), Constraint FK_BANK_DEPART Foreign Key(bank) References bank(bankname) ); create table employee ( empID CHAR(18) not null, empname VARCHAR(20) not null, empphone CHAR(11), empaddr VARCHAR(50), emptype CHAR(1), empstart DATE not null, depart CHAR(4), constraint PK_EMPLOYEE primary key (empID), Constraint FK_DEPART_EMP Foreign Key(depart) References department(departID), Constraint CK_EMPTYPE Check(emptype IN ('0','1')) ); create table customer ( cusID CHAR(18) not null, cusname VARCHAR(10) not null, cusphone CHAR(11) not null, address VARCHAR(50), contact_phone CHAR(11) not null, contact_name VARCHAR(10) not null, contact_Email VARCHAR(20), relation VARCHAR(10) not null, loanres CHAR(18), accres CHAR(18), constraint PK_CUSTOMER primary key (cusID), Constraint FK_CUS_LOANRES Foreign Key(loanres) References employee(empID), Constraint FK_CUS_ACCRES Foreign Key(accres) References employee(empID) ); create table accounts( accountID CHAR(6) not null, money DOUBLE not null, settime DATETIME, accounttype VARCHAR(10), constraint PK_ACC primary key (accountID), Constraint CK_ACCOUNTTYPE Check(accounttype IN ('SaveAccount','CheckAccount')) ); create table saveacc ( accountID CHAR(6) not null, interestrate float, savetype CHAR(1), … -
Django: How to compare two querysets and get the difference without including the PK
I don't think the word difference is correct because you might think difference() but it makes sense to me what I am trying to achieve. I do apologize if this is a common problem that's already been solved but I can't find a solution or dumbed down understanding of it. I have two querysets of the same model as follows: qs1 = ErrorLog.objects.get(report=original_report).defer('report') # 272 rows returned qs2 = ErrorLog.objects.get(report=new_report).defer('report') # 266 rows returned I want to compare the first one to the second one and find the 6 rows that don't match in the first qs1 I tried difference() and intersection() but I keep ending up with the same 272 rows or 0 rows. I have a feeling that it sees pk as a unique value so it never finds matching rows. I tried the following: # Get the 4 fields I want to compare and exclude field_1 = [error.field_1 for error in qs2] field_2 = [error.field_2 for error in qs2] field_3 = [error.field_3 for error in qs2] field_4 = [error.field_4 for error in qs2] # Assuming this would work qs3 = qs1.exclude(field_1__in=field_1, field_2__in=field_2, field_3__in=field_3, field_4__in=field_4) # But ended up with 10 rows in qs3 since it doesn't loop …