Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to submit image and text field in single API endpoint using drf and angular
Good day guy i'm working on an drf api endpoint that requires user uploading image and text to the same endpoint, i've done all that is required but i still keep getting error, below is snippet of my code and error msg APIVIEW class CreateProfileView(APIView): parser_classes = (MultiPartParser,) serializer_class = schoolProfileSerializer queryset = schoolProfile.objects.all() permission_classes = [permissions.AllowAny] def perform_create(self, serializer): serializer.save(user=self.request.user) def post(self, request): file_upload = schoolProfileSerializer(data =request.data, instance=request.user) if file_upload.is_valid(): file_upload.save() return Response(file_upload.data, status=status.HTTP_201_CREATED) else: return Response(file_upload.errors, status=status.HTTP_400_BAD_REQUEST ) SERIALIZER class Base64Imagefield(serializers.ImageField): def to_internal_value(self, data): if isinstance(self, six.string_types): if 'data: ' in data and ';base64, ' in data: header, data = data.split(';base64,') try: decode_file = base64.b64decode(data) except TypeError: self.fail('invalide image') file_name = str(uuid.uuid4())[:16] file_extension = self.get_file_extension(file_name, decode_file) complete_file_name = "%s.%s" %(file_name, file_extension) data = ContentFile(decode_file, name=complete_file_name) return super(Base64Imagefield, self).to_internal_value(data) def get_file_extension(self, file_name, decode_file): extension = imghdr.what(file_name, decode_file) extension = 'jpg' if extension == 'jpeg' else extension return extension class schoolProfileSerializer(serializers.ModelSerializer): parser_classes = (MultiPartParser, FormParser, ) id = serializers.IntegerField(source='pk', read_only=True) email = serializers.CharField(source='user.email', read_only=True) username = serializers.CharField(source='user.username', read_only=True) badge = Base64Imagefield(max_length=None, use_url=True) class Meta: model = schoolProfile fields = ( 'email', 'id', 'username', 'school_name', 'address', 'badge', 'gender', 'level', ) def create(self, validated_data, instance=None): if 'user' in validated_data: user = validated_data.pop('user') … -
how to display many to many and many to one datas of my table in django
I am totaly new to django and django rest-api, I have a tables named op , it has many to many relation with two other tables. (country through op_country) , (sector throgh op_sector) and 1 to many relation with table named attachements. below is my table models. class Op(models.Model) : name = models.CharField(max_length=40) class Meta : db_table = "op" class Country(models.Model) : name = models.CharField(max_length=60 , null=True , unique=True) coun_op = models.ManyToManyField(Op , through='Op_country' , through_fields=('country_id' , 'op_id')) class Meta : db_table = "country" def __str__(self) : return self.name class Op_country(models.Model) : op_id = models.ForeignKey(Op , on_delete=models.CASCADE) country_id = models.ForeignKey(Country , on_delete=models.CASCADE) class Meta: db_table = "op_country" class Attachments(models.Model) : op_id = models.ForeignKey('Op' , on_delete=models.CASCADE) link = models.CharField(max_length=200) class Meta : db_table = "attachments" **`below are my serializers.`** class op_Serializer(serializers.ModelSerializer): class Meta: model = Op fields = ['id', 'name'] class country_Serializer(serializers.ModelSerializer) : class Meta: model = Country fields = ['id', 'name'] class op_country_Serializer(serializers.ModelSerializer) : class Meta: model = Op_country fields = ['id', 'op_id', 'country_id'] class attachments_Serializer(serializers.ModelSerializer) : class Meta: model = Attachments fields = ['id', 'name','link'] right now when I sent a get request to my view my below viewset @permission_classes([AllowAny]) class op_ViewSet(viewsets.ModelViewSet) : serializer_class = op_Serializer def get_queryset(self) : … -
TypeError: unsupported operand type(s) for /: 'str' and 'str' django setting.py
when im taking my course of django i got this error i don't know how to fix it here is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } -
Choosing among ManyToMany, CharField and JSONField for performance
I want to get the most performance out of my database. I have instances between 250.000-300.000 and each of them has 15 columns. 5 of them is ManyToMany field. And their instances are very low in quantity, like 10-15 for each. And there is 4 columns in each. But only one of them has 1000-1200 instances with same amount of columns. Can I get a better performance by converting ManyToMany fields to CharFields or even storing everything into a single JSONField? How much do you think it will affect? And how can I test it and get numbers to compare? Example code is very much appreciated. Since I upload data to my database by using only fixtures, I don't really need any convenience of editing data in admin dashboard. -
Private messaging in Django - how to perform 1-sided delete
I have been trying to create a simple messaging system on my Django site. I have the basic functionality up and running but would now like to add a delete button. Originally, I was just going to use a DeleteView with jQuery but I realized this would delete the message object entirely making it inaccessible for both the sender and receiver. For example, if one user deleted a message from their inbox, it would also delete the message from the receiver's sent box. Is there a way to perform some kind of 1-sided delete so a user can delete a message on their side without impacting the other's? Maybe some way to create 2 message objects each time (i.e., a sent message and a received message)? Thanks! Message model: class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") reciever = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reciever") subject = models.CharField(max_length=128, default="-") content = models.TextField() send_date = models.DateTimeField(default=timezone.now) Delete JQuery: $(".delete-btn").click(function(e){ e.preventDefault if (confirm('Are you sure you want to delete?')) { var deleteUrl = $(this).attr("delete-href") var picID = $(this).attr("message-id") if (deleteUrl){ $.ajax({ url: deleteUrl, type: 'DELETE', method: "POST", data: {'csrfmiddlewaretoken': '{{csrf_token}}'}, }) } } }); Inbox HTML: <h1 class="d-inline-block">Inbox</h1> <a class="btn btn-secondary float-right" href="{% url 'compose' username=user.username … -
Django: Force ipv4 for EMAIL_HOST? (GMail: 421, '4.7.0 Try again later, closing connection.')
If I try to send a mails with Django via settings.EMAIL_HOST, I get this error: (421, '4.7.0 Try again later, closing connection.') I found a work-around (GMail 421 4.7.0 Try again later, closing connection) It works if I use a IPv4 connection (and not IPV6). EMAIL_HOST = '64.233.184.108' But this is just a work-around, I would like to have a solution. Because if google changes the IP of the smtp servers, my solution will fail. How can I tell Django or Python to use IPv4 when I use this? EMAIL_HOST = 'smtp.gmail.com' By default my system uses ipv6, and then Google thinks I am a spammer and blocks me with "(421, '4.7.0 Try again later, closing connection.')" -
Django - using modelForms data in another models field
I'm trying to make a form to create a new account with allocation attached to account model. Allocation has three properties that need inputs, then I need to attach that to account where there is the current allocation - which contains the foreign key(allocation) Here is my code: Views.py: def accounts(request): return render(request, 'accounts.html', { 'accounts': Account.objects.all() }) def createAccount(request): form = createAccountForm() otherForm = createAllocation() if request.method == 'POST': form = createAccountForm(request.POST, prefix="primary") otherForm = createAllocation(request.POST) if form.is_valid() and otherForm.is_valid(): otherForm = otherForm.save() form = form.save() context = {'form':form, 'otherForm':otherForm} return render(request, 'create_account.html', context) Models.py: class Allocation(models.Model): equity = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)], null=True, blank=True) bonds = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)], null=True, blank=True) options = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)], null=True, blank=True) date_assigned = models.DateField(auto_now_add=True) @property def is_valid(self): """ :return: True if sum of equity, bonds and options is 100 """ if self.equity + self.bonds + self.options != 100: # sum is not 100 return False return True class Account(models.Model): class Meta: app_label = 'account' ACCOUNT_TYPES = ( ('roth_ira', 'Roth IRA'), ('traditional_ira', 'Traditional IRA'), ('brokerage', 'Brokerage Account'), ('trust', 'Trust'), ) balance = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPES, null=False, blank=False) taxable = models.BooleanField(default=False) create_date = models.DateTimeField(null=True, blank=False) close_date = models.DateTimeField(null=True, blank=True) current_allocation = models.ForeignKey(Allocation, … -
Use model viewset as well as generic viewset toether in python django
I wrote seperate class api for each user functionality but someone experienced told me to combine all in one class using custion method functionality of viewset in django rest framework. This is my code: class UserRegisterViewset(viewsets.ModelViewSet): ''' Register's user in local db''' serializer_class = UserSerializer queryset = User.objects.all() class RequestPasswordResetEmailViewset(viewsets.ViewSet): ''' Resets password of user by mail''' def create(self, request, format=None): data = {'request': request, 'data': request.data} serializer = RequestPasswordResetEmailSerializer(data=data) email = request.data['email'] if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) uidb64 = urlsafe_base64_encode(smart_bytes(user.id)) token = PasswordResetTokenGenerator().make_token(user) current_site = "pdsp.datawrkz.com" relativelink = reverse( 'password-reset', kwargs={ 'uidb64': uidb64, 'token': token}) absurl = 'http://' + current_site + relativelink email_body = 'Hi ' + user.username + \ ' Use link below to reset your password \n' + absurl data = { 'email_body': email_body, 'to_email': user.email, 'email_subject': 'Reset your password'} email = EmailMessage( subject=data['email_subject'], body=data['email_body'], to=[ data['to_email']]) email.send() return Response( {'Success': 'We have sent you a link to reset your password'}) class PasswordTokenCheckViewset(viewsets.ViewSet): ''' Checks generated password token for user creation''' def create(self, request, uib64, token): try: id = smart_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(id=id) if not PasswordResetTokenGenerator().check_token(user, token): return Response( {'error': 'Token is not valid, please request a new one'}) return Response({'Success': True, 'message': 'Credentials Valid', 'uid64': uidb64, … -
Django showing Id of model in browser url instead of model name
I created models for companies in my new application in django and have also created the instance for it to show detail page for each company. But when a company is clicked, it shows the id of the company instead of the name in URL like this: http://127.0.0.1:8000/companies/2/ is there a way I can make it return the company name instead like this: http://127.0.0.1:8000/companies/stackoverflow/ this is the code for my model and am using function based views for this: class Company(models.Model): Online_Merchant = 'merch' Education = 'edu' Transportation = 'trans' Hospitalism = 'hosp' Healthcare = 'health' Construction = 'const' Blog = 'blog' Finance = 'fin' Media = 'media' Government_Agency = 'agency' Other = 'other' Manufacturing = 'manufacturing' sector = [ (Online_Merchant, 'Online Merchant'), (Education, 'Education'), (Transportation, 'Transportation'), (Hospitalism, 'Hospitalism'), (Healthcare, 'Healthcare'), (Construction, 'Construction'), (Blog, 'Blog'), (Finance, 'Finance'), (Media, 'Media'), (Manufacturing, 'Manufacturing'), (Government_Agency, 'Government Agency'), (Other, 'Other') ] Free = 'Free' Premium = 'Premium' package = [ (Free, 'Free'), (Premium, 'Premium') ] user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='Company User') company_sector = models.CharField(max_length=30, choices=sector, default=Online_Merchant, verbose_name='Sector') company_name = models.CharField(max_length=100) company_description = models.TextField() company_logo = models.ImageField(upload_to='company_logos', blank=True, null=True) company_address = models.TextField(max_length=2000) rating_array = ArrayField(models.IntegerField(), size=0, default=list) average_rating = Int_max.IntegerRangeField(default=0, verbose_name='Avg', min_value=1, max_value=5) … -
local variable 'final_result' referenced before assignment I am making an django calculator web app and i got stuck with this error
from django.shortcuts import render from django.http import HttpResponse import re def index(request): if request.method=="POST": values=request.POST['values'] #string having whole ques print(values) vals=re.findall(r"(\d+)",values) #extrect values operators=['+','x','÷','-'] opr=[] for v in values: for o in operators: if v==o: opr.append(o) print(opr) #extrect operators print(re.findall(r"(\d+)",values)) for o in opr: if o=='÷': i=opr.index(o) res=float(vals[i])/float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) elif o=='x': i=opr.index(o) res=float(vals[i])*float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) elif o=='+': i=opr.index(o) res=float(vals[i])+float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) else: i=opr.index(o) res=float(vals[i])-float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) if(len(opr)!=0): if opr[0]=='÷': result = float(vals[0])/float(vals[1]) elif opr[0]=='x': result = float(vals[0])*float(vals[1]) elif opr[0]=='+': result = float(vals[0])+float(vals[1]) else : result = float(vals[0])-float(vals[1]) final_result=result print(final_result) res=render(request,'index.html',{'result':final_result,'values':values}) return res -
Django: null value in column "user_id" violates not-null constraint
I'm using Postgresql and I have created the following models in my Django Project. Models.py User = settings.AUTH_USER_MODEL Discount_Type=( ('$', '$'), ('%', '%'), ) class Invoice(models.Model): ticket = models.OneToOneField(Ticket, related_name='invoice', blank=True,null=True, on_delete=models.CASCADE) updated_by = models.ForeignKey(User, null=True, blank=True, related_name='invoice_editor', on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_paid = models.BooleanField(default=False) federal_price = models.DecimalField(default=20.00, max_digits=6, decimal_places=2) federal_qty = models.PositiveIntegerField(default=1) federal_amount = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2) state_price = models.DecimalField(default=20.00, max_digits=6, decimal_places=2) state_qty = models.PositiveIntegerField(default=1) state_amount = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2) discount = models.DecimalField(default=0.00, max_digits=6, decimal_places=2) discount_type = models.CharField(default='$', max_length=5, choices=Discount_Type) discount_value = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2) amount_payable = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2) def __str__(self): return str(self.amount_payable) class Meta: ordering = ['-date_updated'] class Ticket(models.Model): tax_year = models.CharField(max_length=50, default='2020') service = models.CharField(max_length=50, default='Tax Filing') description = models.TextField(max_length=1000, blank=True) # Customer customer = models.ForeignKey(User, related_name='ticket_customer', on_delete=models.CASCADE) My forms.py class TicketCreateForm(forms.ModelForm): class Meta: model = Ticket fields = ('tax_year', 'service', 'description',) widgets = { 'tax_year': forms.Select(attrs={'class': 'form-control'}), 'service': forms.Select(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'rows':3, 'cols':60, 'class':'form-control'}), } my views.py def customer_ticket_create(request): form = TicketCreateForm() if request.method == 'POST': form = TicketCreateForm(request.POST or None) if form.is_valid(): ticket = form.save(commit=False) ticket.customer = request.user ticket.save() Invoice.objects.create( ticket=ticket, updated_by=request.user) return redirect('customer_home') But I'm getting django.db.utils.IntegrityError: "user_id" violates not-null constraint. This error is because of … -
How render fields individually in Django Using Crispy Forms package
I want to register a new Student in my database, the form that I am going to collect students data should be inline. I render every field individually but it doesn't save my data to the database until I change it to something like this {{ form|crispy }} Here is my students_form.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="gorm-group col-md-4 mb-0"> {{ form.first_name|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.last_name|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.father_name|as_crispy_field }} </div> </div> <div class="row"> <div class="gorm-group col-md-4 mb-0"> {{ form.email|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.phone|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.province|as_crispy_field }} </div> </div> <div class="row"> <div class="gorm-group col-md-4 mb-0"> {{ form.gender|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.national_id|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.semester|as_crispy_field }} </div> </div> <div class="row"> <div class="col-lg-12"> {{ form.current_address|as_crispy_field }} </div> </div> <div class="row"> <div class="gorm-group col-md-4 mb-0"> {{ form.hostel|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.budget|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.image|as_crispy_field }} </div> </div> <input type="submit" value="ذخیره" class="btn btn-success"> </form> It doesn't work but if change to {{ form|crispy }} it works I use class based views class StudentCreateView(CreateView): … -
Is Django already has a built-in microservice architecture?
I am working on a Django Project, but now it's going enormously large. I am thinking to convert it to microservice architecture but I found that Django also has a related architecture, apart from having a common database. So my question is, Is Django have a semi-microservice architecture built-in? -
multi-field login in Django
In addition to the standard name, email, and password for users in django, I want to be able to store their phone #, cell phone carrier, and a 2nd email. How do I save this additional information? -
Django Python - Itertools is not aligning products with sum of auction sales
I generate a list of Products based on two criterias Entity and Period. The list retrieved contains all Products and the sum of all auctions sales for each. The example below shows a list of 4 products for Company XZY in november. Out of all the products listed only one product (sku 30) had two auction sales $180 and $220. The problem is the rest of products had no sales so the null value is not aligning properly with the product. I will need to still list those products and show $0 in sales. Models.py class Entity(models.Model): entity = models.CharField(max_length=40) class Period(models.Model): period = models.CharField(max_length=7) class Product(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, default=None, blank=True, null=True) period = models.ForeignKey(Period, on_delete=models.CASCADE, default=None, blank=True, null=True) sku = models.CharField(max_length=40) class Post(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None, blank=True, null=True) auctionsale = models.DecimalField(max_digits=11, decimal_places=2) Views.py products = Product.objects.filter(entity=entityquery, period=periodquery).values('id', 'period', 'entity', 'sku') posts = Post.objects.filter(product__sku__in=products.values('sku'), product__entity=entityquery, product__period=periodquery).annotate(total=Sum('auctionsale')) mylist = list(itertools.zip_longest(products, posts, fillvalue='0')) Query Entity: Company XZY Period: November Expected results Product Total Auction Sales sku 10 $0 sku 20 $0 sku 30 $400 sku 40 $0 The results i am getting Product Total Auction Sales sku 10 $400 sku 20 sku 30 sku 40 -
How can I cloud-host a website that only 3 or so people will use, or how to protect it from DDoS attacks?
I want to create a website with Django (I already know how to do that), but I want to host it on AWS (I can figure that out later), for I don't want my laptop to store the database. The problem is that I don't want anyone to be able to access it. I only wish for me and other 2 or 3 people to be able to see it. If this is not possible, I could make a simple login page and create the users myself. That way, only the people I want will be able to use the web app. But this would leave it open to DDoS and many different types of attacks I don't know how to defend/prevent. So, now the question would be, do you guys know any tutorial on protecting your website from these attacks? I have looked online on these tutorials, but I only find how to defend from PS4 or WordPress. I am not looking for anything too big, as I said, I think that I could use @login_required from Django, and the only thing I will have to defend is the login page. I am almost sure 1 of these two … -
TypeError:super(type, obj): obj must be an instance or subtype of type
I, I created CRUD posting app which can upload some images optionally in Django. And then, when I tried to create a post, this error occured to me. I have no ideas what's happening on my app. There seems to be no invalid syntax. Here's a forms.py file. The part which is causing this error is at line 37. forms.py 10 class CreateForm(forms.ModelForm): 11 max_upload_limit = 2 * 1024 * 1024 12 max_upload_limit_text = naturalsize(max_upload_limit) 13 17 picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text, 18 widget=forms.ClearableFileInput(attrs={'multiple': True})) 19 upload_field_name = 'picture' 20 22 class Meta: 23 model = Ad 24 fields = ['title', 'category', 'text', 'picture'] 25 26 # Validate the size of the picture 27 def clean(self): 28 cleaned_data = super().clean() 29 pic = cleaned_data.get('picture') 30 if pic is None: 31 return 32 if len(pic) > self.max_upload_limit: 33 self.add_error('picture', "File must be < "+self.max_upload_limit_text+" bytes") 34 35 # Convert uploaded File object to a picture 36 def save(self, commit=True): 37 instance =super(CreateForm, self).save(commit=False) 38 40 f = instance.picture # Make a copy 41 if isinstance(f, InMemoryUploadedFile): # Extract data from the form to the model 42 bytearr = f.read() 43 instance.content_type = f.content_type 44 instance.picture = bytearr # … -
How do I query model db attributes based on drop down selection?
I am very new to Django. I am struggling to figure out how to query model attributes based off of drop down selections. The project I'm working on is a directory of animals available for adoption. Admin creates new cat or dog profiles which get added to cat app db and dog app db respectively. Customers visit the site and landing page has drop downs of "age" (e.g. baby, young, adult, etc.) and "type" (e.g. cat, dog, other) to filter the listings accordingly. Examples: CustomerA selects "baby" and "dog" from the dropdowns. I then want to query dog.models for all matches. CustomerB selects "adult" and "all" from the dropdowns. I then want to query dog.models and cat.models and other.models and return matches Is it best to create another db with foreign keys to dog, cat and other? Or can I just query from the view or template? #from cat.models class Cat(models.Model): name = models.CharField(max_length=200,validators=[MinLengthValidator(2, "Nickname must be greater than 1 character")]) breeds = models.ForeignKey(CatBreed, on_delete=models.PROTECT) age = models.PositiveIntegerField() ageGroup = models.IntegerField(choices=AgeGroup.choices, null=False, blank=False, default=0) sex = models.IntegerField(choices=SEX, blank=False, null=False, default=0) tagLine = models.CharField(max_length=150) goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information') goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information') goodWKids = models.BooleanField(null=False, … -
AWS EC2 + djnago + uwsgi : ERR_CONNECTION_REFUSED
I am trying to follow the steps in the guie, Before I even get to the nginx part I am trying to make sure that uWSGI works correctly my folder structure is srv/unifolio-back and I try to conect like below, (unifolio-back) ubuntu@ip-172-31-37-172:/srv/unifolio-back$ sudo /usr/bin/uwsgi -i /srv/unifolio-back/.config/uwsgi/mysite.ini [uWSGI] getting INI configuration from /srv/unifolio-back/.config/uwsgi/mysite.ini but I can't connect the site, (chrome send the ERR_CONNECTION_REFUSED message) my .config/uwsgi/mysite.ini file is ; #linku_uwsgi.ini file [uwsgi] ; # Django-related settings ; # the base directory (full path) chdir = /srv/unifolio-back/ ; # Django's wsgi file module = config.wsgi:application ; # the virtualenv (full path) home = /home/ubuntu/.local/share/virtualenvs/unifolio-back-_HCbnSkq plugins = python3 socket = /tmp/mysite.sock chmod-socket = 666 chown-socket = deploy:deploy uid = deploy gid = deploy http = :8080 enable-threads = true master = true vacuum = true pidfile=/tmp/deploy.pid logto = /var/log/uwsgi/unifolio-back/@(exec://date +%%Y-%%m-%%d).log log-reopen = true and the log is like below: *** Starting uWSGI 2.0.15-debian (64bit) on [Sat Dec 19 16:50:45 2020] *** compiled with version: 7.3.0 on 28 September 2018 15:41:15 os: Linux-5.4.0-1029-aws #30~18.04.1-Ubuntu SMP Tue Oct 20 11:09:25 UTC 2020 nodename: ip-172-31-37-172 machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 1 current working directory: /srv/unifolio-back writing pidfile to … -
GitLab CI generates database name for Postgres that is longer than the 63 character limit (django.core.exceptions.ImproperlyConfigured)
I'm having trouble using postgres as a service in a GitLab CI job that runs pytest for a Django application. Here is my GitLab CI job: Pytest: image: python:3.8 stage: test services: - postgres:13.1 - redis:6.0.9-alpine variables: DJANGO_SETTINGS_MODULE: "backend.settings.gitlab_ci" # the database name is too long, setting here explicitly # I tried setting DATABASE_URL and it didn't work: # DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/postgres" SECRET_KEY: "secret" DEBUG: "1" POSTGRES_HOST_AUTH_METHOD: trust script: - cd backend - pip install -r requirements/base.txt - pip install -r requirements/test.txt - flake8 - black -l 79 -S --diff . - pytest --cov --cov-config=.coveragerc coverage: '/TOTAL.+ ([0-9]{1,3}\.[0-9]{1,3}%)/' In backend/settings/gitlab_ci.py I have the following DATABASES settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'postgres', 'PORT': '5432', }, } Here are relevant logs from the failing CI job. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f8d71b8de20> def get_connection_params(self): settings_dict = self.settings_dict # None may be used to connect to the default 'postgres' db if settings_dict['NAME'] == '': … -
how to fix 'PluginReferenceField' object has no attribute 'rel' fields.py from djangocms-forms
class PluginReferenceField(models.ForeignKey): def init(self, *args, **kwargs): kwargs.update({'null': True}) # always allow Null kwargs.update({'editable': False}) # never allow edits in admin kwargs.update({'on_delete': SET_NULL}) # never delete plugin super(PluginReferenceField, self).init(*args, **kwargs) def _create(self, model_instance): return self.rel.to._default_manager.create(name=model_instance.name) def pre_save(self, model_instance, add): if not model_instance.pk and add: setattr(model_instance, self.name, self._create(model_instance)) else: reference = getattr(model_instance, self.name) if not reference: setattr(model_instance, self.name, self._create(model_instance)) reference = getattr(model_instance, self.name) if reference.name != model_instance.name: reference.name = model_instance.name reference.save() return super(PluginReferenceField, self).pre_save(model_instance, add) -
Django: AttributeError: 'NoneType' object has no attribute 'username'
I am trying to create a chat app and got stuck with this error. I am getting this error though I'm logged in as a superuser. My models.py class Message(models.Model): author = models.ForeignKey(User, null=True, related_name='author_messages', on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username def last_10_messages(): return Message.objects.order_by('-timestamp').all()[:10] Where I try to access it: for message in messages: print("message printing") result.append(self.message_to_json(message)) then def message_to_json(self, message): print("message.id=",message.id) print(message.author.username) return { 'id': message.id, 'author': message.author.username, 'content': message.content, 'timestamp': str(message.timestamp) } When i print the length of the object i notice it says 2..idk why coz i haven't added any messages yet. As the loop goes twice i noticed that the username got printed the first time but raised an error for the second loop(though idk why it loops coz i dont even have messages to load yet) like here The error also appears to be in the return function in my models class as in here I've read other posts but their errors were different... Would be really grateful if sum1 cud help out!! -
Pagination clears my other search parameters
For my program in Django I have the following Pagination section in my HTML file {% if player_list.has_other_pages %} <ul class="pagination" style="border: 1px solid #ddd;"> {% if player_list.has_previous %} <li><a href="?ppage={{ player_list.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in player_list.paginator.page_range %} {% with ppage_number=player_list.number radius=8 %} {% if i >= ppage_number|sub:radius %} {% if i <= ppage_number|add:radius %} {% if player_list.number == i %} <li class="active" style="border: 1px solid #ddd;"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li style="border: 1px solid #ddd;"><a href="?ppage={{ i }}">{{ i }}</a></li> {% endif %} {% endif %} {% endif %} {% endwith %} {% endfor %} {% if player_list.has_next %} <li><a href="?ppage={{ player_list.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} So when I press on any of the pagination buttons it calls the page with the search parameter ppage=### (where ### is some number). However, it clears any search parameters I had in the url befarepressing the button, anyway I can let it keep the other search parameters? This is the views function being called: . . . # player request parameters player_page = request.GET.get('ppage', 1) player_first_name = request.GET.get('pfname', None) player_last_name = … -
django.core.exceptions.FieldError: Unknown field(s) (title) specified for Customer
I am trying to register a non-Wagtail model as a snippet, and to allow the model to be created and saved from another snippet's interface. I have been getting this error and am not sure where to start. All of the other StackOverflow posts I've seen are specific to customizing the User model, which I am not doing. I've tried setting a title field for the snippet, as well as appending a 'title' to get_context. This is what I'm trying to accomplish, and I'm not certain if I'm doing it in the best way: There are customers and work orders. Each Work Order has a foreign key to a customer, and my goal is to be able to create customer models inline (or select from existing list) in the WorkOrder snippet interface. Customer Snippet @register_snippet class Customer(models.Model): """Customer model.""" customer_name = models.CharField(max_length=100, blank=False, null=False, help_text="John Doe") ...more regular customer info fields (address, city, state, etc.)... customer_home_phone = models.CharField(max_length=15, blank=False, null=False, help_text="Home Phone") panels = Page.content_panels + [ MultiFieldPanel( [ FieldPanel("customer_name"), FieldPanel("customer_home_phone"), ], heading="Customer Contact" ), ] WorkOrder Snippet @register_snippet class WorkOrder(ClusterableModel, models.Model): """Workorder model.""" STATUS_CHOICES = ( ('o', 'Open'), ('c', 'Closed'), ('x', 'Cancelled'), ) ...workorder fields (service address, city, state, … -
PARTNER_AUTHENTICATION_FAILED: The specified Integrator Key was not found or is disabled. An Integrator key was not specified
I am working on a Django Web App which is used to send documents to users via email and is using Docusign API for that purpose. I am using JWT Grant Authentication and have successfully get the access token which is working fine. Now, I want to send a document to the user via email for signing purpose. For that, I am using the following code: from django.shortcuts import render from django.http import JsonResponse from docusign_esign import EnvelopeDefinition, Recipients, Tabs, SignHere, Signer, CarbonCopy, Document, EnvelopesApi, ApiClient import base64 ACCESS_TOKEN = 'MY_ACCESS_TOKEN' ACCOUNT_ID = 'MY_ACCOUNT_ID' BASE_PATH = 'demo.docusign.net/restapi' def create_document(signer_name, signer_email, cc_name, cc_email): return f""" <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body style="font-family:sans-serif;margin-left:2em;"> <h1 style="font-family: "Trebuchet MS", Helvetica, sans-serif; color: darkblue;margin-bottom: 0;">World Wide Corp</h1> <h2 style="font-family: "Trebuchet MS", Helvetica, sans-serif; margin-top: 0px;margin-bottom: 3.5em;font-size: 1em; color: darkblue;">Order Processing Division</h2> <h4>Ordered by {signer_name}</h4> <p style="margin-top:0em; margin-bottom:0em;">Email: {signer_email}</p> <p style="margin-top:0em; margin-bottom:0em;">Copy to: {cc_name}, {cc_email}</p> <p style="margin-top:3em;"> Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie. Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée. Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice. Donut jujubes oat cake jelly-o. Dessert …