Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove/Strip extra space from the output of for...loop in Django template
In my template I need to print some items and add "," after each one, unless it is the last item. So here is my code: <li> <strong>Category</strong>: {% spaceless %} {% for t in project.technology.all %} {{ t.title }} {% if not forloop.last %},{% endif %} {% endfor %} {% endspaceless %} </li> While it works, it adds an extra whitespace between each item and ",", so what I see is like this: Tech1 , Tech2 , Tech3 while it should be Tech1, Tech2, Tech3 Even spaceless template tag is not working. Please assist. -
FILEFIELD Attibute has no file associated with it
This error keeps appearing when I try to update forms with image fields. I'm trying to upload or update a customer LOGO image. When I try to upload images, the field containing the image says "[field] attribute has no file associated with it" I'm using model forms and generic update views. I don't know how to make the attribute have the file associated with it. I tried a save() override in the model and it still gave me that error. models.py class Customers(models.Model): associations = models.ManyToManyField(Association) company_name = models.CharField(help_text='Company Name', max_length=200, default=None) contact1_first_name = models.CharField(help_text='Primary Contact First name', max_length=50, default=None) contact1_last_name = models.CharField(help_text='Primary Contact Last name', max_length=50, default=None) address1 = models.CharField(help_text='Address 1', max_length=50, default=None) address2 = models.CharField(help_text='Address 2', max_length=50, default=None, blank=True) city = models.CharField(help_text='City', max_length=50, default=None) state = models.CharField(help_text='State', max_length=50, default=None) zip_code = models.CharField(help_text='Postal/ZIP', max_length=20, default=None) phone = models.CharField(help_text='Phone', max_length=20, default=None) email = models.EmailField(default=None) contact2_first_name = models.CharField(max_length=50, null=True, blank=True) contact2_last_name = models.CharField(max_length=50, null=True, blank=True) contact2_phone = models.CharField(help_text='Phone', max_length=20, default=None, null=True, blank=True) contact2_email = models.EmailField(default=None, null=True, blank=True) fax = models.CharField(max_length=20, null=True, blank=True) mobile = models.CharField(max_length=50, default=None, blank=True, null=True) web_address = models.CharField(max_length=50, null=True, blank=True) date_entered = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) date_turned_off = models.DateTimeField(default=None, null=True, blank=True) num_locs = models.SmallIntegerField(default=1) notes = models.TextField(help_text='Notes', null=True, … -
How to create a Docusign envelope with a custom pdf (Python, Django)
My goal is to create a pdf using WeasyPrint and add it the the payload sent to the Docusign Api when requesting an envelope to be created. Here are my steps: generate the a pdf with WeasyPrint and return a based64 string def generate_envelope_document(document_name: str, context: dict): content = render_to_string(f"insurance_contracts/{document_name}.html", context=context) css = find(f"insurance_contracts/{document_name}.css") doc = HTML(string=content, media_type="screen").write_pdf(stylesheets=[css], zoom=0.8) return base64.b64encode(doc).decode("utf-8") create my envelope definition: def create_envelope_definition(envelope_data: dict, context: dict, custom_fields: dict = None): mandate = Document( document_base64=generate_envelope_document("name1", context), name="name1", file_extension="pdf", document_id=1, ) conditions = Document( document_base64=generate_envelope_document("name2", context), name="name2", file_extension="pdf", document_id=2, ) signer = Signer( email=envelope_data["signer_email"], name=envelope_data["signer_name"], recipient_id="1", routing_order="1", ) signer.tabs = Tabs( sign_here_tabs=[ SignHere( anchor_string="Sign", anchor_units="pixels", anchor_y_offset="50", anchor_x_offset_metadata="50", ) ] ) envelope_definition = EnvelopeDefinition( status="sent", documents=[mandate, conditions], recipients=Recipients(signers=[signer]) ) if custom_fields: envelope_definition.custom_fields = CustomFields( text_custom_fields=[ TextCustomField(name=field_name, value=field_value, required=False) for field_name, field_value in enumerate(custom_fields) ] ) return envelope_definition create a Docusign Api object: def get_envelopes_api_client(): """ Create the docusign api client object Return EnvelopesApi object """ api_client = ApiClient() api_client.host = settings.DOCUSIGN_BASE_PATH api_client.set_default_header("Authorization", "Bearer " + get_access_token()) envelope_api = EnvelopesApi(api_client) return envelope_api create and send the Docusign envelope: envelope_api = get_envelopes_api_client() try: envelope = envelope_api.create_envelope( settings.DOCUSIGN_ACCOUNT_ID, envelope_definition=envelope_definition ) except ApiException as e: logger.error(e.body.decode()) return None return envelope at the moment … -
Want to iterate through dictionary with dynamic keys in django template
I Have dictionaries within a dictionary with specific keys. Now I want to access each key in the template dynamically. I want to use main keys as subheadings within a table and show the data of that related keys under those subheadings. I have tried as like below but it seems not working. Error: TemplateSyntaxError at /daily/report Could not parse the remainder: '{{ledger}}' from 'ledgers.{{ledger}} how can I accomplish this? My View: @login_required def accounts_report(request): credit_vouchers = CreditVoucher.objects.all() debit_vouchers = DebitVoucher.objects.all() heads = AccountHead.objects.all() opening_balance = request.GET.get('balance') balance = float(opening_balance) date_from = request.GET.get('from') date_to = request.GET.get('to') credit_vouchers = credit_vouchers.filter(date__gte=date_from, date__lte=date_to) debit_vouchers = debit_vouchers.filter(date__gte=date_from, date__lte=date_to) ledgers = {} for head in heads: key = head.head_name ledgers.setdefault(key, []) for item in ledgers: key = item ledgers.setdefault(key, []) a_head = AccountHead.objects.get(head_name=key) d_vouchers = debit_vouchers.filter(account_head=a_head) c_vouchers = credit_vouchers.filter(account_head=a_head) for voucher in d_vouchers: balance -= voucher.amount ledgers[key].append({ 'date': voucher.date, 'description': voucher.description, 'voucher_no': voucher.voucher_serial, 'debit_amount': voucher.amount, 'credit_amount': 0, 'balance': balance, }) for voucher in c_vouchers: balance += voucher.amount ledgers[key].append({ 'date': voucher.date, 'description': voucher.description, 'voucher_no': voucher.voucher_serial, 'debit_amount': 0, 'credit_amount': voucher.amount, 'balance': balance, }) context = { 'heads': heads, 'opening_balance': opening_balance, 'ledgers': ledgers } return render(request, 'accounts/report.html', context=context) Template: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> table, th, … -
Django - Get response to return image without saving file to models
I am using the tmdb api to return movie info as well as images. Steps below of Get logic Api request is made which provides movie info as well as "backdrop_path" I then use this path to make another request for the jpg related to that movie. Blocker I'm unable to then output that jpg. It currently returns a url path as below. Views.py from django.shortcuts import render from django.views.generic import TemplateView import requests import urllib # Create your views here. def index(request): # Query API with user input if 'movie' in request.GET: api_key = 'api' id = request.GET['movie'] url = 'https://api.themoviedb.org/3/search/movie?api_key={}&language=en-US&query={}&include_adult=false' response = requests.get(url.format(api_key,id)) # successful request if response.status_code == 200: # Parse json output for key value pairs tmdb = response.json() # save image jpg backdrop_path = tmdb['results'][0]['backdrop_path'] url = 'https://image.tmdb.org/t/p/original/{}' gg = urllib.request.urlretrieve(url.format(backdrop_path), 'test.jpg') context = { 'title': tmdb['results'][0]['original_title'], 'overview': tmdb['results'][0]['overview'], 'release_date': tmdb['results'][0]['release_date'], 'vote_average': tmdb['results'][0]['vote_average'], 'vote_count': tmdb['results'][0]['vote_count'], 'backdrop_path' : tmdb['results'][0]['backdrop_path'], 'jpg' : gg } return render(request, 'home.html', {'context': context}) else: # returns homepage if invalid request return render(request, 'home.html') else: # Homepage without GET request return render(request, 'home.html') -
Django/Node js/Laravell/Spring.Which of these would be best for backend beginners?
I am beginner at backend.Pls tell which of these options would be best for me and WHY?? If you have any other framework to suggest.Please speacify. -
Adding 'through' to M2M relationship end up in loosing data
I have a model like this (I deleted all other fields because it does not matter for my problem): class Project(models.Model): reviewers = models.ManyToManyField(User, related_name="review_project") The model is on a very old project already populated. I want to add an intermediate table because we now want to have more information, the intermediate table looks like: class Rate(models.Model): """ Intermediate table for reviewers between User and Project """ user = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'reviewer': True}) project = models.ForeignKey(Project, on_delete=models.CASCADE) rate = models.IntegerField( default=100, validators=[ MinValueValidator(0), MaxValueValidator(100) ] ) However when I update my reviewers field on my project models like this: reviewers = models.ManyToManyField(User, related_name="review_project", through='Rate') And add code to see the Rate Inline on my admin zone I can see that the data from my previous M2M relationship is missing. I mean that if on a project I had 2 users on the field reviewers I do not see them on my rate intermediate table. How can I create a new intermediate table ( which should, under the hood, actually be just add a field to it ) and not loose data ? Thanks -
Nestes ForLoop in HTML - Python
I have 2 {% forloops %} in my HTML file one is nested and I can't seem to get them to work. One is to only display the data of the user that is logged in to my website, "{% for item in user.Building.all %}" and the other is for a filter functionality I have set up on the same page, "{% for post in item.filter.qs %}" Small example of HTML: {% if user.Building.all %} {% for post in user.Building.all %} <tr> {{ post.time }} {{ post.date }} </tr> {% endfor %} {% endfor %} Example of Django View for creating data(User specific) - Python: def adddata_building_mobile(response): if response.method == 'POST': form = SheetForm_Building(response.POST, response.FILES) if form.is_valid(): instance = form.save(commit=False) instance.user = response.user instance.save() response.user.Building.add(instance) return redirect('sheets') else: form = SheetForm_Building() return render(response, 'sheets/add_data/mobile/add_data_building.html', {'form': form}) Example of Django View for lisitng data(Filter Specific) - Python: class ListData_Building(ListView): model = Sheet_Building fields = '__all__' template_name = 'sheets/individual/list_data_building.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = Sheet_Building_Filter(self.request.GET, queryset=self.get_queryset()) return context The problem is that I can only either get the filter to work where it filters out the data based on what I am choosing it to filter by OR it … -
Setting a ForeignKey to the current logged in user | Django Rest framework ViewSets
I am building a REST API with Django Rest Framework's ViewSets and have come across a problem. When using a POST request on my API, I can't easily insert the current logged in user into the model. The model I am serializing is as follows: from django.db import models from django.contrib.auth.models import User # Create your models here. class Question(models.Model): op = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) body = models.TextField() time_created = models.DateTimeField(auto_now_add=True) The field that is giving me the issue is the op field, which is a ForeignKey for Django's default User class. This API has a POST URL for creating a new question on the site. I want the viewset to insert the current logged in user into the creation. Other questions have suggested defining a custom create() method on the serializer, but that doesn't work since I want to insert the current logged in user, and not a set one. My Serializer: class QuestionSerializer(ModelSerializer): class Meta: model = Question fields = ("op", "title", "body") My viewset: class QuestionViewSet( mixins.UpdateModelMixin, mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet, ): queryset = Question.objects.all() serializer_class = QuestionSerializer -
AWS S3 links not working when used from docker swarm, but works when used in docker-compose
I have a Django application and related services running on an EC2 ubuntu instance. The static files are being stored and fetched from S3 using django-storages library and are working fine when I start the services using docker-compose. But recently I tried to set it up on 2 different EC2 servers running under same security group using Docker Swarm, and none of the S3 static file links are working. All of them throw this error in browser console: Failed to load resource: the server responded with a status of 403 (Forbidden) Also, when I use collectstatic to copy the files over to S3, it shows "4066 static files copied", but there's nothing on S3 bucket. The same however, when run on docker-compose copies all the files correctly, and if nothing was changed, shows "0 static files copied" The only changes I made were in the Compose file (to set it up for swarm) and opening required ports on EC2 security groups. Code was left untouched. I can't figure out what's causing this exactly. Any help will be appreciated! -
Dashboard conception using python/pandas
I have to develop a dashboard with 'customisable' indicators and data comming from multiple csv files. This will be developped with Django. I first look for Django package but did not find any package that could be useful. But I do not know how to proceed. I start learning about pandas library and it is pretty cool but one of my issue is that I have to format dashboard following a model. My idea was to define indicator store in a python model and loop over thi smodel to calculate indicators and produce dashboard. For example, indicators could be defined as follow: indicators = [ { 'id': 1, 'type': 'recruitement', # header in pivot table 'label': 'Randomized all, N', # indicator label 'value': ['number',], # indicator expected result format 'filter': None, # indicator filter to apply 'source': 'crf_ran', # indicator csv files source for calculating }, { 'id': 2, 'type': 'recruitement', 'label': 'Sex (Woman), %', 'value': ['pourcentage',], 'filter': 'sex == 2', 'source': 'crf_ran', }, { 'id': 3, 'type': 'Follow up', 'label': 'D7 visits: N performed (% performed/expected)', 'value': ['number','pourcentage',], 'filter': 'timing == 7', 'source': 'crf_vis', }, ] source data #1 (crf_ran.csv): record_id,country,pat,sex,age,hiv 1,Ivory Coast,CIV-TR-001,2,51,'positive' 2,Ivory Coast,CIV-SM-002,1,33,'negative' ... source data #2 … -
Wagtail/Weasyprint URLFetchingError at /resume/generate
I am doing my first django/wagtail project, where I use this template to produce a resume. I've managed to publish my project via heroku and I'm able to load it. However I don't know how to tackle the error URLFetchingError at /resume/generate when I want to press "Get PDF". Below you can see my full traceback and how I've set up my urls.py file. Any suggestions on how to fix this would be greatly appreciated. urls.py from django.urls import include, path from django.contrib import admin from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ path('django-admin/', admin.site.urls), path('admin/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), path('search/', search_views.search, name='search'), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = urlpatterns + [ # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This should be the last pattern in # the list: path("", include(wagtail_urls)), # Alternatively, if you want Wagtail pages to be served from a subpath # of your … -
Issue with Uploading File, Processing, and then Download Files - Django
I'm trying to do what the title of this post says. I get the files within the app itself, but it doesn't download to the user. What happens is the user enters a csv with raw data into the form, that CSV goes into the view, it gets handled, goes through the download functions, and then produces the necessary CSV files into the MEDIA_ROOT and to the user (or that's the idea) View def keyword(request): if request.method == 'POST' and request.FILES["myfile"]: myfile = request.FILES["myfile"] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) handle_uploaded_file(keywordFunction(filename)) return HttpResponse('done') return render(request, 'keyword.html') def downloadKeywords(request): file_path = os.path.join(MEDIA_ROOT,'keywords.csv') if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 def downloadAds(request): file_path = os.path.join(MEDIA_ROOT,'adcustomizerfeed.csv') if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 def handle_uploaded_file(f): downloadKeywords(f) downloadAds(f) Script That Produces CSV Files def keywordFunction(yourFile): listofkeywords=['electrician'] adgrouplist=[] keyword_list = pd.read_csv(os.path.join(MEDIA_ROOT,yourFile)) keyword_list['PathCity(text)'] = keyword_list['City(text)'].apply(lambda x : str(x).strip().replace(' ','-')) keyword_list['Path Count'] = keyword_list['PathCity(text)'].apply(lambda x: len(x)) keyword_list['Zips_Split'] = keyword_list['zipcode'].apply(lambda x: str(x).replace(' ',',')) KLcsv = keyword_list.to_csv(os.path.join(MEDIA_ROOT,'adcustomizerfeed.csv'),index=False) for eachkeyword in listofkeywords: for eachcity in keyword_list.itertuples(): city=eachcity[2] zips = eachcity[-1].split(',') # … -
queryset when building django form
I am trying to get specific querysets based when a customer-specific form loads, showing only that customer's name (embedded as an ID field), its respective locations and users. The idea is to select one user and any number of locations from a multichoice box. I've tried to pass the ID as a kwarg but am getting a KeyError. I've tried the kwarg.pop('id') as found on the web and same issue. Any advice? class LocGroupForm(forms.ModelForm): class Meta: model = LocationsGroup fields = ('group_name', 'slug', 'customer', 'location', 'user_id',) def __init__(self, *args, **kwargs): qs = kwargs.pop('id') super(LocGroupForm, self).__init__(*args, **kwargs) self.fields['customer'].queryset = Customers.objects.get(pk=qs) self.fields['location'].queryset = CustomerLocations.objects.filter(customer_id=qs) self.fields['user_id'].queryset = CustomerUsers.objects.filter(customer_id=qs) -
Nginx 502 Bad Gateway -- Django Google App Deployment
After successfully completing this google app deployment documentation I run the last code within the documentation. -- $ gcloud app deploy -- After a few minutes waiting for the app to deploy I get this "502 badgateway nginx". Im currently on a MacBook Pro (Big Sur). What would we be the best approach for this error? -
django.core.exceptions.ImproperlyConfigured: URL route 'add</int:product_id/>' uses paramet er name 'product_id/'
Views.py def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( _cart_id=_cart_id(request) ) cart.save(), try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart ) cart_item.save() return redirect('cart:cart_detail') urls.py path('add</int:product_id/>', views.add_cart,name='add_cart'), -
Validate before csv file can be uploaded to Google BigQuery Table
I have an django web application that appends csv/xlsx file from GCP Storage to existing table in Bigquery using: client.load_table_from_uri(uri, table_id, job_config=job_config) This is working fine. But, there are certain files that have few records that can not be appended to BigQuery Table. Is there a way we can pre-validate the file and check what records can be uploaded and what can not before proceeding/actually appending to BigQuery table? -
How to properly append Django serialized data into excel sheet
I'm working on a task where I have to create an API URL that has some serialized data and I have to add it to the excel sheet. I'm using openpyxl for this task. def fruit_report_export(request): temp_file = "report.xlsx" media_doc_path = os.path.join(settings.MEDIA_ROOT, Reports if os.path.exists(media_doc_path): pass else: os.mkdir(media_doc_path) path = os.path.join(settings.MEDIA_ROOT, f"Reports/July-2021") if os.path.exists(path): excel_path = os.path.join(path, temp_file) else: os.mkdir(path) excel_path = os.path.join(path, temp_file) # creating excel wb = Workbook(excel_path) wb.save(excel_path) # add data into excel wb = load_workbook(filename=excel_path) wb_sheet = wb["Sheet"] wb_sheet.title = "Report" ws = wb["Report"] headers = ["Fruit Id", "Fruit Name", "Total Qty"] ws.append(headers) fruit_serializer = FruitSerializer(fruits, many=True) # looping through serializer data for fruit in fruit_serializer.data: for data in fruit ws.append([fruit[data] for h in headers]) wb.save(excel_path) # Saving virtual workbook bytes = save_virtual_workbook(wb) response = HttpResponse(bytes, content_type="application/ms-excel") response["Content-Disposition"] = "attachment; filename=temp.xlsx" return response fruit_serializer.data: List of OrderedDict [ OrderedDict([('Fruit Id', 1), ('Fruit Name', 'Apple'), ('Total Qty', 15)]), OrderedDict([('Fruit Id', 2), ('Fruit Name', 'Banana'), ('Total Qty', 25)]), OrderedDict([('Fruit Id', 3), ('Fruit Name', 'Mango'), ('Total Qty', 10)]) ] fruit value inside fruit_serializer.data OrderedDict([('Fruit Id', 1), ('Fruit Name', 'Apple'), ('Total Qty', 25)]) data inside fruit is Fruit Id Fruit Name Total Qty fruit[data] value is 1 Apple 15 etc... … -
How to make calculations after requesting with M2M fields (DRF)
class Product(models.Model): name = models.CharField(max_length=255) ht = models.CharField(default=0) wd = models.CharField(default=0) len = models.CharField(default=0) class Parcel(models.Model): product_list = models.ManyToManyField(Product) class ParcelSerializer(serializers.ModelSerializer): class Meta: model = Parcel fields = '__all__' class ProductSerializer(serializers.ModelSerializer): product_volume = serializers.ReadOnlyField() class Meta: model = Product fields = '__all__' class ParcelCreateView(generics.CreateAPIView): queryset = Package.objects.all() serializer_class = PackageSerializer class ParcelListView(generics.ListAPIView): serializer_class = ParcelSerializer class ProductCreateView(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer class ProductListView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer My output is : [ { "id": 1, "products": [ 1 ] }, { "id": 2, "products": [ 1, 2 ] } ] How can I get product id and product volume as below? I didn't understand what to do because it's ManyToManyField. After the request comes, how can I get product ids from the body and calculate their volume [ { "id": 1, "products": [ 1 : Result #Volume of ID : 1 Product (wd*ht*len) ] }, { "id": 2, "products": [ 1 : Result #Volume of ID : 1 Product (wd*ht*len), 2 : Result #Volume of ID : 1 Product (wd*ht*len) ] } ] -
Django: complex order by and filter by from many relations query with nested models
What I want to achieve: I want list of [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "counts": 600, "details": [ { "id": 13, "length_max": 21, "length_min": 15, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] } ] }, { "location": "Loc3", "session": [ { "start": "2021-01-01", "counts": 500, "details": [ { "id": 15, "length_max": 19, "length_min": 16, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] } ] } ] My Viewset is class AquaticFilter(FilterSet): type_filter = filters.CharFilter(method="filter_by_type") def filter_by_type(self,queryset,name,value): queryset = queryset.filter(session__details__type=value).distinct() return queryset class SessionModelViewSet(ModelViewSet): queryset = Session.objects.all() serializer_class = SessionSerializers filter_backends = (DjangoFilterBackend,) filter_class = SessionFilter I am trying to filter based on type, but am not able to fetch what I need. The out I am getting is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "counts": 600, "details": [ { "id": 13, "length_max": 21, "length_min": 15, "length_avg": 16, "length_std": 19, "is_active": false, "type": "dog" } ] }, { "start": "2021-01-01", "counts": 600, "details": [ { "id": 7, "length_max": 39, "length_min": 25, "length_avg": 25, "length_std": 27, "is_active": true, "type": "cat" }, { "id": 19, "length_max": 39, "length_min": 25, "length_avg": 25, "length_std": 27, "is_active": false, "type": "cat" } ] … -
Django: django.db.utils.IntegrityError: null value in column "post_id" of relation "posts_comment" violates not-null constraint
I am getting this error django.db.utils.IntegrityError: null value in column "post_id" of relation "posts_comment" violates not-null constraint DETAIL: Failing row contains (16, Just a check, 2021-07-20 14:13:15.751175+00, , null,). This is my comment model class Comment(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_comments") reply = models.ForeignKey('Comment', null=True, related_name='replies', blank=True, on_delete=models.CASCADE) content = models.TextField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) This is my serializer class CommentSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) user = serializers.ReadOnlyField(source="user.username") content = serializers.CharField() comment_id = serializers.PrimaryKeyRelatedField(source='reply', queryset=Comment.objects.all(), write_only=True, required=False) def create(self, validated_data): user = self.context['request'].user content = validated_data['content'] comment = Comment(user=user, content=content) comment.save() return comment This is my view function def post(self, *args, **kwargs): post = get_object_or_404(Post, slug=self.kwargs['slug']) serializer = CommentSerializer(data=self.request.data, partial=True, context={'request': self.request}) if serializer.is_valid(): comment_id = self.request.POST.get('comment_id') comment_qs = None if comment_id: comment_qs = Comment.objects.get(id=comment_id) serializer.save(post=post) else: serializer.save(post=post) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Can someone help to solve this? Thanks note: I don't want to use ModelSerializer. want to learn to use Serializer. -
ImportError: cannot import name 'faker' from partially initialized module 'faker' (most likely due to a circular import)
from random import randint from faker import faker from quiz.models import Quiz, Question, Choice import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'schoolauthquiz.settings') django.setup() fakegen = faker() name = ['HTML', 'CSS', 'JavaScript', 'MySQL','Python', 'jQuery', 'Bootstrap4','Math'] fake_num_questions = fakegen.randint(1, 10) def add_quiz(): q = Quiz.objects.get_or_create( quiz_title=random.choice(name), num_questions=fake_num_questions)[0] q.save() return q def populatequestion(N=10): for entry in range(N): quiz = add_quiz() fake_question_text = fakegen.question_text() # fake_question_num = fakegen.question_num() fake_answer = fakegen.answer() fake_explanation = fakegen.explanation() # fake_question = fakegen.question() fake_choice_text = fakegen.choice_text() fake_correct = fakegen.correct() Q = Question.objects.get_or_create(quiz=quiz, question_text=fake_question_text, question_num=fake_num_questions, answer=fake_answer, explanation=fake_explanation)[0] """ question_num=num_questions question=questionid """ ch = Choice.objects.get_or_create( question=Q, correct=fake_correct, choice_text=fake_choice_text)[0] if name == 'main': print("populating script!") populatequestion(10) print("populating populatequestion Complate!") ` -
Django thinks my model object dosent exist
django thinks my model object doenst exist. The code is working fine because it behaves like its supposed to for another user. i get this enter image description here BUt its there in the admin page.enter image description here It be because I can migrate since it thinks there is a feild that dosent exist with a null param that wont work. I deleted it tho and the ENTIRE model that was associated with it. enter image description here See? its not there. enter image description here can anyone tell me what is happeing here? -
Edit the value of an attribute inside a serializer Django Rest
What I'm trying to do is changing the value of an attribute in the serializer (seemed like the appropriate place to change it). "unsupported operand type(s) for *: 'int' and 'DeferredAttribute'". This is the error that I'm recieving when doing it my way. Any assistance would be most welcomed. Models: class Product(models.Model): price =models.IntegerField name=models.CharField(null=True) In a different app I have the other model class Order_unit(models.Model): amount=models.IntegerField price=models.IntegerField product=models.ForeignKey(Product) Serializer: from order.models import * from product.models import * class OrderUnitSerializer(serializers.ModelSerializer): price= serializers.SerializerMethodField('get_price') class Meta: model = Order_unit fields = ['order', 'product', 'amount', 'price'] def get_price(self,Order_unit): price= Order_unit.amount*Product.default_price return price -
html id value not changing
I am trying to update the applied candidate selection status using ajax but I am having issues with the select tag name attribute which is not changing its ID value when I am iterating through, it's showing the same id in every iteration my template <th>skills req</th> </tr> {% for val in applicants %} <tr> <td>({{val.user.id}}){{val.user.username | capfirst }}</td> <td>{{val.apply_date}}</td> <td> <select class="status_select" name="status" id="{{val.user.id}}"> <-- even though here it should be changing it <option value="onhold">Onhold</option> <option value="selected">Selected</option> <option value="rejected">Rejected</option> </select> </td> <td> <b>{{val.job_post.job_type}}</b> </td> <td>{{val.job_post.title}}</td> <td>candidate skills</td> </tr> {% endfor %} </table> jquery snippet $("body").on("change", ".status_select", function (e) { e.stopPropagation(); console.log($(this).val()); id = $(".status_select").attr("id"); console.log(id); console.log("working"); $.ajax({ url: "/users/status_change/", type: "GET", contentType: "application/json", dataType: "json", data: { id: id, selected_val: $(this).val(), }, success: function (data) { console.log(data); }, error: function (error) { console.log(error); console.log("calling from error"); }, }); }); I mean to say like this (id value stuck at 4) id-> 4 [20/Jul/2021 19:31:10] "GET /users/status_change/?id=4&selected_val=rejected HTTP/1.1" 200 19 selected id-> 4 [20/Jul/2021 19:31:16] "GET /users/status_change/?id=4&selected_val=selected HTTP/1.1" 200 19 rejected id-> 4 [20/Jul/2021 19:31:18] "GET /users/status_change/?id=4&selected_val=rejected HTTP/1.1" 200 19 onhold id-> 4 [20/Jul/2021 19:31:19] "GET /users/status_change/?id=4&selected_val=onhold HTTP/1.1" 200 19 onhold id-> 4 [20/Jul/20 my view def status_change(request): if request.method=='GET': …