Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Even if username is not alphabetic or specified characters, it can be entered in various characters
When registering an account, usernames can be entered in various characters other than alphabets or specified characters. I want to restrict the character to use username in URL, but I don't know how. I also thought that there was a limitation when I checked the document, but I thought it might not be applicable. I want to know the cause. class User(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() user_id = models.UUIDField(default=uuid_lib.uuid4, primary_key=True, editable=False) username = models.CharField(_('username'), unique=True, max_length=50,validators=[username_validator],error_messages={ 'unique': _("A user with that username already exists."), },) class SignUp(generic.CreateView): """account""" template_name = "accounts/signup.html" form_class = forms.SignUpForm success_url = reverse_lazy('') def form_valid(self, form): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) domain = current_site.domain context = { 'protocol': self.request.scheme, 'domain': domain, 'token': dumps(user.pk), 'user': user, } subject = render_to_string('mail/create/subject.txt', context) message = render_to_string('mail/create/message.txt', context) send_mail(subject , message, 'an@apasn.com', [user.email], fail_silently=False) # user.email_user(subject, message) return redirect('accounts:signupdone') class SignUpForm(forms.ModelForm,UserCreationForm): class Meta: model = User fields = ('email','username') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' def clean_email(self): email = self.cleaned_data['email'] User.objects.filter(email=email, is_active=False).delete() return email -
DateTimeField not saving the Time and Date DJANGO2.1
I have tried countless times different approach to save and TIME and DATE using DateTimeField but DJANGO2.1 keep throwing a template error enter a valid date/time models.py class Party(models.Model): name = models.CharField(max_length=50) date = models.DateTimeField() forms.py class PartyForm(forms.ModelForm): name = forms.CharField() date = forms.DateTimeField(widget=forms.widgets.DateTimeInput(format=['%Y-%m-%d %H:%M'], attrs={'class':'myDateClass', 'type':'datetime-local'})) class Meta: model = Party fields = ['name', 'date'] Also, when i try to use input_formats below: date = forms.DateTimeField(widget=forms.widgets.DateTimeInput(input_formats=['%Y-%m-%d %H:%M'], attrs={'class':'myDateClass', 'type':'datetime-local'})) The terminal throw the error below: File "/Users/macadmin/Documents/Django_fun4/date_and_time/date_time/core/forms.py", line 30, in PartyForm attrs={'class':'myDateClass', 'type':'datetime-local'})) TypeError: __init__() got an unexpected keyword argument 'input_formats' Can anybody help me figure out how to save the TIME and DATE. (Time is the most important data i need right now but if i can save both TIME and DATE it would be great) Thank you for your help in advance. -
visual studio code unresolved import?
I have installed python version 3.7 and visual studio code latest version, after that i have created virtual environment and installed django and created Django project. Whenever i am opening some file, its showing error like below unresolved import 'django.contrib' unresolved import 'django.urls' Undefined variable: 'path' Undefined variable: 'admin' Below are the paths of my application 1) Python : C:\Python\Python37-32\python.exe 2) Virtual environment created D:\django_projects\envs\py1\ 3) Django Project created D:\django_projects\p1\p1 Below are the things i have tried 1) Re Installing Python 2) Setting the Python Path in environment variable even i selected include in the path at the time of python installation 3) Re installing the VS Code 4) Tried commenting the "python.jediEnabled": false, in settings.json file in vs code, but it was giving different error unable to import django. 5) unresolved import 'django.contrib' unresolved import 'django.urls' Undefined variable: 'path' Undefined variable: 'admin' -
how to keep html code with chart js script in the same file to work
im trying add chartJs to my project but the problem is i cant keep the html code <canvas id="myChart" width="400" height="400"></canvas> with the script code in one file {% block body %} <canvas id="myChart" width="400" height="400"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for i in products %}'{{i.product}}',{% endfor %}], datasets: [{ label: '# of Votes', data: [{% for i in products %}'{{i.price}}',{% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" type="text/javascript"></script> the error provide is Uncaught ReferenceError: Chart is not defined class Lists(ListView): template_name = 'charts.html' context_object_name = 'products' pass i also tried to to make a separate js file to the script but it provided Uncaught SyntaxError: Unexpected token % and when i copied the script into the … -
implement DRF get_queryset so that a bad query_param responds with an error message
I have a django model which I want to display via Django Rest framework. I am getting all objects in the model to be displayed via the get_queryset(). However, I also have a couple of query_params which will filter out certain objects. This is my main code which is working fine: class PlanView(generics.ListAPIView): """ API endpoint which allows prices to be viewed or edited """ serializer_class = PlanSerializer permission_classes = (IsAuthenticatedOrReadOnly,) # override method def get_queryset(self): //get all objects in Plan model queryset = Plan.objects.all() // possible query parameters to be read from url size = self.request.query_params.get("size", None) price = self.request.query_params.get("price", None) if size is not None: if size == "large": queryset = queryset.filter(Large=True) elif size == "small": queryset = queryset.filter(Large=False) if price is not None: queryset = queryset.filter(price=price) return queryset with this urlpattern: path(r'API/plans', views.PlanView.as_view(), name='prices'), The only problem is that when I purposefully write the below URL in a browser, http://127.0.0.1:8000/API/plans?size=sm which has a bad/misspelled query_param value, the get_query() code will just ignore it and display the objects as if there are no filters. I tried to put an else statement such as: if size is not None: if size == "large": queryset = queryset.filter(Large=True) elif size == … -
How to get and save data of the nearest element in page in python django
I need to add comment module on my homepage in django python - simple textarea under each post. I need to get the nearest post id before i save it in my form, that my comment knows to which post is related. My views.py def home(request): newPostForm = newPost() newCommentForm = newComment() if request.is_ajax(): newPostForm = newPost(request.POST) newCommentForm = newComment(request.POST) if newPostForm.is_valid(): instance = newPostForm.save(commit=False) instance.author = request.user instance.date_posted = timezone.now() instance.save() data = { 'message': 'post is added' } return JsonResponse(data) if newCommentForm.is_valid(): instance = newCommentForm.save(commit=False) instance.author = request.user instance.date = timezone.now() instance.save() data = { 'message': 'comment is added' } return JsonResponse(data) context = { 'newPostForm': newPostForm, 'newCommentForm': newCommentForm, 'posts': Post.objects.all().order_by('-date_posted'), 'comments': Comment.objects.all().order_by('-date_posted') } and my home.html <div class="leftcolumn"> <div class="new_post_form"> <form METHOD="POST" class="new_post" id="new_post"> {% csrf_token %} {{ newPostForm }} <button type="submit">Publish</button> </form> </div> <div id="posts"> {% for post in posts %} <div class="container"> <a class="user" href="#">{{ post.author }}</a>, {{ post.date_posted }} <img src="{{ post.author.profile.image.url }}" alt="{{ post.author }}" style="width:100%;"> <p>{{ post.content }}</p> {% for comment in post.comments.all %} <div class="comment"> <p>{{ comment.content }}</p> <form METHOD="POST" class="new_comment" id="new_commentt"> {% csrf_token %} {{ newCommentForm }} </form> </div> {% endfor %} </div> {% endfor %} </div> </div> I don't … -
n:m relation table foreign key column unique
i have 2 tables Pool table pid(PK) Problem table number(PK) | name | submit | accept and also have n to m relation table PoolProblem PoolProblem pid(FK from Pool table) | number(FK from Problem table) if i insert tuple in PoolProblem like this, 1 | 1 1 | 2 1 | 3 2 | 2 << i want to show error this line, because number fk is duplicated on entire table. i tried ManyToMany relation, set unique constraint at number column(but error,,,) how can i solve it? -
How to select only one row for one user in django?
I have a message database and it has senderid, receiverid, message and date. Now I would like to get list of users whom I have recently messaged with one latest message (sent or received) per person. How can I get just a single row of message per person. I tried but this game me all the messages between two users, I just want the latest message. querySet=MessageModel.objects.filter( Q(sUser=self.request.user) | Q(rUser=self.request.user) ) return querySet but this game me all the messages between two users, I just want the latest message. -
Django doesn't serve images because Debug is set to True - how can I make nginx serve those?
So I'm just deploying my second website. I have a static location with css, js files and everything works alright. Now I just realised that I also have some images uploaded by the users. Here is the model: photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_7 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_8 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_9 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) The problem is that when I try to access those images with DEBUG set to True, I get this Not Found The requested resource was not found on this server. I found on the internet that setting Debug to True makes django not serve the files anymore. So I have to configure nginx to serve those. How can I do that? I have to make it also serve the default /static/ folder, and these photos which don't have a fixed name. (%Y/%m/%d). The absolute path would be something like /etc/USERNAME/main-website/media/photo/%Y/%m/%d. Here is my nginx file from sites-enabled. server { server_name bestdavnic73.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/octavian56/main-website; } location / { include proxy_params; proxy_pass http://unix:/home/octavian56/main-website/bestDAVNIC73.sock; } listen 443 … -
How to realize registration via Facebook in django?
I have my API and here I developed registration view. Now I want to realize registration via facebook, idk how to do it correct. Where i can find some good example(i'm interested only backend part)? -
how can I filter a field list values whenever I change another field value?
I have 3 models Category, Subcategory, and Product I registered them on the Django admin, in the add product admin page I need the subcategories list to be filtered based on the category value I choose. right now the subcategory list shows all subcategories, I need when I choose the category A to have only the subcategories that are related to Category A. Category Model class Category(models.Model): name = models.CharField(max_length=200, db_index=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Subcategory Model class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='subcategories', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Product Model class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategory, related_name='products', on_delete=models.CASCADE) -
HTML select multiple values from styled list with checkboxes
I have a django project with a list of users that I want to include in a post request. Note that only the users that I have checked should be included in the post request in the django function based view. I wonder how I can get the value of the checked users into the django post request function based view? Its not exactly like in this picture but the checkbox and the user part Is the same, I couldn't find out how to put a local file into stack overflow! The Project Page: @login_required def projectPage(request): obj = Project.objects.filter(canview__user=request.user) assignments = Assignment.objects.filter(canview__user=request.user) allstudents = UserProfile.objects.all() username = request.user context = { 'object': obj, 'MyName': username, 'Assignments': assignments, 'students': allstudents } return render(request, 'allProjects.html', context) The POST REQUEST Page: @login_required def create_project(request): if request.method == 'POST': name = request.POST.get('Project-Name') description = request.POST.get('Project-Description') parent_assignment = Assignment.objects.get(pk=request.POST.get('Project-ParentAssignmentID')) membersInProject == SOMETHING project = Project(name=name, description=description, parent_assignment=parent_assignment, members = membersInProject) project.save() return redirect('allaStudieplaner') In The HTML template: {% for student in students %} <div class="custom-control custom-checkbox"> <span class="d-flex align-items-center"> <div style="margin-right: 10px"> <div class="circle"> <span class="initials" , style="color: #ffffff"> {{ elev.user|capfirst|first }} </span> </div> </div> <div style="width: 300px"> <span class="h6 mb-0" data-filter-by="text">{{elev.user|capfirst}}</span> </div> <div … -
Using select_related in add/edit django admin for single field
I need to resolve the N+1 problem. Below is my model: class Work(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(null=True, blank=True) book = models.ForeignKey('Chapter', on_delete=models.CASCADE) job = models.ForeignKey('Job', on_delete=models.CASCADE) user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=True, blank=True) prev_work = models.ForeignKey('self', on_delete=models.CASCADE, editable=False, null=True, blank=True) And now I overrided get_queryset in my ModelAdmin. It works great in List View but when I want to add new element it makes multiple queries because of the "book" field. So how can I override sql for SINGLE field. To be specific, it makes so many queries because in my model file I have this: def __str__(self): return self.book.project.slug + "-" + str(self.book.number) + "-" + self.job.name and there are many books and many projects. -
Including a list view with inclusion tag
I've a list view function (searchview) that I want to include to my template home page with the help of the inclusion tag, please how do I get around this... Thanks in anticipation -
getting the counts and values of foreignkeys relations with query
hi my models are like this and i'm using mysql class UserChannel(models.Model): ... channel = models.ForeignKey(Channel) user_entry_date = models.IntegerField() channelName = models.ForeignKey(ChannelName) is_verified = models.BooleanField(default=False) users = Fk ... class Channel(models.Model): ... name = models.CharField() is_active = models.BooleanField(default=True) class ChannelName(models.Model): ... channel = models.ForeignKey(Channel,) channel_name = models.CharField() i have to show differnt UserChannels and thier counts based on distinct Channel and ChannelName of a range of time which is timestamp (its something like a logging system) right now i am getting all UserChannels of a range of time and i want to show values based on that query so far i have managed to get this done with for loops but it is very inefficient and takes a lot of time to respond channels = Channel.objects.all().values('pk', 'name') channel_names = ChannelName.objects.all().values('pk', 'channel_name') result_list = [] for query in queryset: # list of all UserChannels of a range of time res = dict() for item in channels: query_specific = query.filter(channel=item['pk']) query_is_verified = query.filter(channel=item['pk'], is_verified=True) for channel_name in channel_names: count_query_specific = query_specific.filter(channelName=channel_name['pk']).count() if count_query_specific != 0: res['count_all_specific'] += f'{item["name"]}- {channel_name["channel_name"]} : {count_query_specific}' count_query_is_verified = query_is_verified.filter(channelName=channel_name['pk']).count() if count_query_is_verified != 0: res['count_is_verified'] += f'{item["name"]}- {channel_name["channel_name"]} : {count_query_is_verified}' so i want some thing like this in … -
Django Messages show up only in admin
I have set up a django message that gets displayed when the user logs in, but the messages show up only in the admin. accounts/views.py def login_page(request): form = LoginForm(request.POST or None) context = { 'form':form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username,password=password) if user is not None: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path,request.get_host()): return redirect(redirect_path) else: messages.info(request,"You are now logged in") return redirect("/") else: messages.error(request,"Something went wrong") print("Error") return render(request,"accounts/login.html", context) settings.py MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage' 'OPTIONS': { 'context_processors': [ ... 'django.contrib.messages.context_processors.messages', base.html {% if message is not None %} {% for message in messages %}{{ message }}{% endfor %}{% else %}{% endif %} -
display DB blob(image) column on html page
I need a help to display photo from oracle DB on html page in django webapp, I have django webapp, and it has Employee model which has image column as blob to save the employee photo in the DB, when I try to display the image column on the HTML page it doesn't display. and it displays it as the following: ** (b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x03\xbc\x00\x00\x010\x08\x02\x00\x00\x00\x1b\xcc\xea\xea\x00\x00\x12\IDATx\x9c\xed\xdd\x7flU\xf5\xf9\xc0\xf1\x16\nTj\x11\x8ct\x1bC@\x87\xd3\rA\xd0\xa1h\x1d2\x17\'\x04\xa63\xea\xe6/\xd4\x99\x918\xb3\x98-\xea\x96\x91\xb8\xcdE\xd9\x92mYt\x89f\xfa\x07\x81\x98,Q\xb6e\xfe\xc2\x88\xc4P (3\xc2\xa0\xa6\xc8\xc2\x06,\xfc\xa8h\xb5\x08\xa3\xed\xfd\xfe\xe1\xbe\xc4\x08\xf7<\xa7\xb7\xe7\x9e\xf6\xe8\xeb\xf5\xe7\xfd\x9c>\xe7Y\xd8\xbawNn\xef\xad-\x95J5\x00\x00@y\x83\xfa{\x01\x00\x00\x18\xe8D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04\xea\xfa{\x81<\xd4\xd6\xd6f2\'\xcdW\x8e\xa7\xb9W&_]\x9e\xdb\x8d\xb2\x92\xe7\xc2Y\xfd\x8b\x87\x06\xd4\xc2\x03\xea\xbf\x9f)\xef\x95\x89\xac\xfe\x83gr\xa34\x06\xd4o\x89\xac|"\xff\x15r3\xd0\xfe\xc7\x1b\xcaj\x99<\xff\xdf9\x13\x85\xfb\xb5\xf6\x89\xfcW\xe8G\x9e4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@\xa0\xb6T*\xf5\xf7\x0e\x00\x000\xa0y\xd2\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x81\xba\xfe^\x00\xe0S\xad\xa3\xa3\xe3\xf9\xe7\x9f\x7f\xed\xb5\xd7Z[[\xb7m\xdb\xd6\xd9\xd9\xf9\xde{\xef\xf5\xf4\xf4466\x8e\x181b\xc2\x84\t\x93&M:\xe7\x9csf\xcf\x9e=v\xec\xd8\xfe^\xf6\x7f\x8a\xb83@\x1f\xd5\x96J\xa5\xfe\xde\x01\xe0S\xa7\xbb\xbb\xfb\x89\'\x9ex\xf4\xd1G\xd7\xacY\xf3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0cPU\xa2\x19\xa0\xea\x9a\x9b\x9b\x9fx\xe2\x89a\xc3\x86e>\xf97\xbf\xf9\xcd\xad\xb7\xde\x9a\xf9\xd8\x9ab\xee\x0cP=\xa2\x19 \x0f\xdf\xfc\xe67W\xae\y\xca)\xa7d5p\xd8\xb0a\x8f?\xfe\xf8\xddw\xdf\x9d\xd5\xc0c\x15qg\x80*\x11\xcd\x009inn^\xbf~\xfd\xa5\x97^\xda\xf7Q\x93&Mjii\xb9\xf1\xc6\x1b\xfb>*Y\x11w\x06\xa8\x06\xd1\x0c\x90\x9f\xd3N;m\xe5\xca\x95\x8b\x17/\x1e7n\e\x13F\x8d\x1a\xf5\xc0\x03\x0fl\xd8\xb0\xe1\xfc\xf3\xcf\xcfv\xb7r\x8a\xb83@\xe6D3@\xden\xbd\xf5\xd6m\xdb\xb6-]\xba\xf4\xe2\x8b/\x1e4(\xed\xef\xe1)S\xa6\xfc\xfe\xf7\xbf\xdf\xb9s\xe7\xc2\x85\x0b\x87\x0c\x19R\xd5\r\x8fU\xc4\x9d\x012\xe4#\xe7\x00\xfa\xd3[o\xbd\xf5\xfc\xf3\xcf\xbf\xf6\xdak\xad\xad\xad\xff\xfa\xd7\xbf:;;\xdf{\xef\xbd\x9e\x9e\x9e\xc6\xc6\xc6\x11#F\x8c\x1f?~\xd2\xa4I\xe7\x9cs\xce\xec\xd9\xb3+~\xd0\x9b\xb9"\xee\x0c\xd0G\xa2\x19\x00\x00\x02\xde\x9e\x01\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x81\xff\x03\xf0\xc2\xa5\xc7\xda\xabX&\x00\x00\x00\x00IEND\xaeB`\x82') ** -
Combining two or more queryset or combining different models as a single output
I have created 2 models Images and UserDetails both contain a foreignkey field of auth_user (User) .If i provide a user id i want get data from 3 models. ie; from User , UserDetails and Images as queryset in DRF models.py from django.contrib.auth.models import User from django.db import models class Images(models.Model): name = models.CharField(max_length=10) userid = models.ForeignKey(User,on_delete=models.CASCADE) category = models.CharField(max_length=10) file = models.FileField(blank=True, null=True) class Categories(models.Model): name = models.CharField(max_length=15) class Skills(models.Model): name = models.CharField(max_length=20) category = models.ManyToManyField(Categories) class UserDetails(models.Model): userid = models.ForeignKey(User,on_delete=models.CASCADE) firebase = models.CharField(max_length=50) mobile = models.IntegerField() pin = models.IntegerField( null=True) latitude = models.CharField(max_length=50,null=True) longitude = models.CharField(max_length=50,null=True) profile_pic = models.ManyToManyField(Images,null=True) skill = models.ManyToManyField(Skills,null=True) is_freelancer = models.IntegerField() serializer.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Images fields = '__all__' views.py class Profile(ListAPIView): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) serializer_class = ImageSerializer def get_queryset(self): img = Images.objects.filter(userid=self.request.user.id) return img if i run this in postman i get { "count": 1, "next": null, "previous": null, "results": [ { "id": 2, "name": "", "category": "profile pic", "file": "http://127.0.0.1:8000/media/media/brand_EqkvDFf.png", "userid": 14 } ] } but i want output something like this { "count": 1, "next": null, "previous": null, "results": [ { "image": { "id": 2, "name": "", "category": "profile pic", "file": "http://127.0.0.1:8000/media/media/brand_EqkvDFf.png", "userid": 14 }, … -
How to properly use django testcase's addCleanup method?
I have a test subclass of APITestCase where I'm using the class-method setUpTestData to create data for my tests and also some mocks. Basically what I want to do is to run mock.patch.stopall (as shown next), but it's not working. I have based my implementation on THIS ANSWER and I'm using: Django v2.2.4 and djangorestframework v3.10.2 import mock from rest_framework.test import APITestCase class FooTest(APITestCase): @classmethod def setUpTestData(cls): patcher_one = mock.patch('route.one') mock_route_one = patcher_one.start() patcher_two = mock.patch('route.two') mock_route_one = patcher_two.start() cls.addCleanup(mock.patch.stopall) # etc super(FooTest, cls).setUpTestData() When running my tests with this code, I get: TypeError: addCleanup() missing 1 required positional argument: 'function' So I edit the addCleanup call to: cls.addCleanup(function=mock.patch.stopall) but I get the following: TypeError: addCleanup() missing 1 required positional argument: 'self' Editing to: cls.addCleanup(cls, function=mock.patch.stopall) I get AttributeError: type object 'FooTest' has no attribute '_cleanups' At this point I'm a bit lost. The workaround that I'm using is to do it in the tearDownClass method: @classmethod def tearDownClass(cls): mock.patch.stopall() But I would like to centralize all the testing logic in the setUpTestData method. Anyone see's where I'm messing up? -
Is it better to aggregate all data in a JSONField or use model ForeignKey?
I'm trying to create a business directory in multiple languages. Should I aggregate all the data in one JSONField, or should split it into multiple models, and why. models.py from django.db import models from django.contrib.postgres.fields import JSONField class Business(models.Model): name = models.CharField(max_length=500) subsidiary = models.ForeignKey(Business, on_delete=models.SET_NULL, null=True, blank=True) data = JSONField() {"name":{"ar":"Arabic Name","en":"English Name"}} etc -
Django how to pass header on request in get_queryset
I am using Django rest framework to pass a get request with a query_param like so: views.py class PlanView(generics.ListAPIView): """ API endpoint which allows prices to be viewed or edited """ serializer_class = PlanSerializer permission_classes = (IsAuthenticated,) # override method def get_queryset(self): queryset = Plan.objects.all() size = self.request.query_params.get("size", None) if portion is not None: if size == "large": queryset = queryset.filter(Large=True) elif size == "small": queryset = queryset.filter(Small=False) return queryset however, I set up an authentication class in settings.py like this: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ] so that I can pass a header with a token in request. This works well when I test with a third party client like postman. however how can I pass a header in the above view? -
Sending images twice to CouchDb instead of 1 time
I try to send zip file which is unpacked in memory and images are sent to database. But images are sent twice and I don`t know where the problem is. Can someone tell please? def uploadZIP(request): if request.method == 'POST': mosaic = 'C:/Users/lenovo/Downloads/myimages.zip' zip_name = ZipFile(mosaic) db_view = launch_db.view('_all_docs', include_docs=True) list_of_files = [name for name in zip_name.namelist()] imageNumber = len(list_of_files) imgInDBNumber = len(db_view) if imageNumber != 0: generalImageNumber = imgInDBNumber - 1 for j in range(imageNumber): for i in range(0, len(list_of_files)): archive = ZipFile(mosaic, 'r') image = archive.read(list_of_files[i]) image = Image.open(BytesIO(image)) file_name = 'img{0}'.format(generalImageNumber) rgb, img = rgbValue(image, file_name) generalImageNumber = generalImageNumber + 1 launch_db.save(rgb) launch_db.put_attachment(rgb, img, 'image.png', 'image/png') launch_db.commit() messages.info(request, 'ZIP file with images was successfully sent') return render(request, 'add_images.html') -
slow process during saving model in database
i want save a list of model in database table but i very slow when i use save() method for each item it took near 20min is that a best way to save objects to table Modles.py class Part(models.Model): block = models.CharField(max_length= 2, null= True) phase = models.CharField(max_length= 3, null= True) department = models.CharField(max_length= 20, null= True) type = models.CharField(max_length= 10, null= True) mark = models.CharField(max_length= 20, null= True) class Task(models.Model): name = models.CharField(max_length= 20) class ProjectTask(models.Model): project = models.ForeignKey('Project', on_delete= models.CASCADE) task = models.ForeignKey("Task", on_delete=models.CASCADE) weight_percent = models.FloatField() class PartTask(models.Model): part = models.ForeignKey('Part', on_delete= models.CASCADE) project_task = models.ForeignKey('ProjectTask', on_delete= models.CASCADE) progress = models.FloatField(null=True) views.py def import_part_task(_project_id): project_id = _project_id project_task = ProjectTask.objects.all().filter(project= int(project_id[0])) part_list = Part.objects.all() part_task_list = [] for part in part_list: for task in project_task: part_task = PartTask() part_task.part =part part_task.project_task = task part_task_list.append(part_task) #This ACTION TAKES VERY LOG TIME for part_task in part_task_list: PartTask.save(part_task) -
Django migrate: django.db.utils.OperationalError: (1364, "Field 'name' doesn't have a default value")
basic datas: mysql-server: 5.7.27-0ubuntu0.16.04.1 Ubuntu: 16.04 Python: 2.7.12 Django: 1.11.16 Virtualenv . I added a new application (gallery) and created the following table: class Medi(models.Model): gd_id = models.CharField(max_length=128) # name = models.CharField(max_length=512, default='1') original_name = models.CharField(max_length=512) title = models.CharField(max_length=512, blank=True, null=True) md5sum = models.CharField(max_length=32) date_of_event = models.DateTimeField() date_of_event_end = models.DateTimeField(blank=True, null=True) last_updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) . To be very clean after getting the above mentioned errors i deleted the table from the database, the entries from the django_migrations table and all the migrations file but init.py . I ran makemigrations and after that migrate which had the following output: python manage.py makemigrations Migrations for 'gallery': gallery/migrations/0001_initial.py - Create model Medi python manage.py migrate Operations to perform: Apply all migrations: admin, auth, bugtrack, common, contenttypes, follow, gallery, infokom, phonebook, sessions, sites Running migrations: Applying gallery.0001_initial... OK Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 227, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File … -
Django Import Error Module "app1.context_processor" does not define a "songs_list" attribute/class
I have 2 apps in my django project, app1 and app2 app1/views.py def list_view(request): songs = Song.objects.all() context = { 'tracks_list' : songs } return render(request,"app1/list.html",context) I want this list to appear on app2, so I created a file called 'context_processor' inside app1: from .models import Song def songs_list(request): songs = Song.objects.all() return {"songs_list":songs} and inside settings.py I added this to the context_processors: 'app1.context_processor.songs_list', And {{ songs_list }} to the templates In the end I get an Import Error: Module "app1.context_processor" does not define a "songs_list" attribute/class Thank you for any help