Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change Django Builtin dev Server inside a Docker container?
The Django builtin Development Server has the "feature" of filtering out HTTP Headers containing underscores: https://github.com/django/django/blob/7785e03ba89aafbd949191f126361fb9103cb980/django/core/servers/basehttp.py def get_environ(self): # Strip all headers with underscores in the name before constructing # the WSGI environ. This prevents header-spoofing based on ambiguity # between underscores and dashes both normalized to underscores in WSGI # env vars. Nginx and Apache 2.4+ both do this as well. for k in self.headers: if '_' in k: del self.headers[k] return super().get_environ() For development purposes, i'd like to comment out this for loop. I run Django inside a Docker container. How can I comment out these lines when building the image? -
How can I migrate changes from views.py in an app in Django?
I just started with Python/Django this week. I've been following the freeCodeCamp 4 hour course in youtube(https://www.youtube.com/watch?v=F5mRW0jo-U4&t=3885s). I didn't have any problem creating the virtual enviroment, the project and other apps that hold database models. However, at around the hour and 4 minutes mark of the video, the very same code the teacher is displaying in the video throws me an error. He creates a new app called "pages" and in the views.py script codes this function from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home_view(): return HttpResponse('<h1>Hello World</h1>') Then the pages app is included in the INSTALLED_APPS array, in the settings scripts INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', ] The problems comes when I try to migrate the changes from pages. The 'python manage.py makemigrations' followed by the 'python manage.py migrate' commands don't detect any change in the views.py script of any of the apps, so when I try to import those views in the urls.py file, it throws an error. I don't know how to make the changes in views noticeable for the manage.py, so it can migrate them. Ive been looking in the documentation and in StackOverflow, … -
For loop on form not functing properly
I have a feature that allows users to upload multiple images to their blog but it is not working correctly. When a user uploads multiple images only one of them is uploaded to the postgres db. view def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) form = CommentForm if request.method == 'POST': test = PostImagesForm(request.POST, request.FILES) files = request.FILES.getlist('images') if test.is_valid(): for f in files: instance = test.save(commit=False) instance.post = Post.objects.get(pk=pk) instance.save() else: print(instance.errors) postgallery = PostImages.objects.filter(post_id=post) #########ignore############ comments = Comment.objects.filter(post=post)#.order_by('-create') buildlogs = BuildLog.objects.filter(post_id=post) if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.author = request.user new_comment.post = post new_comment.save() context = { 'post':post, 'form':form, 'comments':comments, 'buildlogs':buildlogs, 'PostImagesForm':PostImagesForm, 'postgallery':postgallery } return render(request, 'blog/post_detail.html', context) form class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } you can see i am getting the list of files via the files = request.FILES.getlist('images') then running a for loop on the contents. If I break the code in the stack trace I can see that the two files are in the list so i am very confused on why it is not properly iterating though the list and … -
large json data in django model slows down any query
I have a django model that looks like this: class SomeModel(Model): some_field = CharField(max_length=10) large_data = JsonField(blank=True, null=True) the "large_data" field can get really large, like 150mb. I know this is really bad practice, most of the data could decoupled into other sql database tables, but this is legacy application and the impact of the rework would be huge. It turns out that any query to this table is really slow, sometimes I just want to modify the "some_field" value, but even when I save that field individually like in the code below, the update query takes ages obj.some_field = "ice cream" obj.save(update_fields=["some_field"]) I am sure the large_data is the guilty because if I set its value to "None" then the save operation is committed right away. Are there optimization tricks that can be applied to my example without reworking the json field? Thanks in advance -
Django-rest framework "This field is required." with no empty fields
I'm tying to setup a basic API following the quickstart on https://www.django-rest-framework.org/tutorial/quickstart/ GET request are working but when I try to POST from the django-rest framework UI i get the following error. Data I want to post: { "name": "3", "description": "3", "price": 3, "speed": "3" } Answer I get from django-rest framework: (price field has default=0, anyhow it won't get the value posted) { "name": [ "This field is required." ], "description": [ "This field is required." ], "speed": [ "This field is required." ] } My serializer: class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ['name','description','price','speed'] My viewset: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } Models.py class Product(models.Model): name = models.CharField(max_length=100,null=False,unique=True) description = models.CharField(max_length=250,null=False) price = models.IntegerField(default=0) # price in cents speed = models.CharField(max_length=50,null=False) def __str__(self): return self.name def get_display_price(self): return (self.price / 100) class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' Urls.py router = routers.DefaultRouter() router.register(r'products', ProductViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('orders/', include('orders.urls')), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Any help would be appreciated and please Let me know if I should add more code -
django and node js integrate
Hello I don't know if this is a silly question or not. I'm planning to build a chat and live streaming app, I'm a Django developer, but it would be nice to include Node in this. Django will assign and register clients, node js will take care of the data in real time, but I ended up thinking about creating a request from React to Django, then sending Django a request to Nod and then to React. This is very expensive and there is no data allocation here. All clients will have all directories, and React will filter each person's data individually Node js server let express = require('express'); let cors = require('cors'); let http = require('http'); let bodyParser = require('body-parser'); let path = require('path'); const port = 9000; app = express(); const server = http.createServer(app).listen(port, () => {}); const { Server } = require('socket.io'); const io = new Server(server, { cors: { origin: 'http://localhost:3000', methods: ['GET', 'POST'], allowedHeaders: ['my-custom-header'], credentials: true, }, }); app.use(cors()); app.use(express.static(path.join(__dirname, 'client'))); app.use(bodyParser.json()); app.post('/server', (req, res) => { io.emit('command', req.body); console.log(req.body); res.status(201).json({ status: 'reached' }); }); io.on('connection', (socket) => { socket.on('command', (data) => { io.emit('command', data); console.log(data); }); }); Django Request def handelRequest(serializer): notification = … -
django form 'str' object has no attribute 'id' when passing a list of choices
I am creating a form where the view passes a list to the form and this list is used to create choices. The choices seems to be created correctly, but I get an error 'str' object has no attribute 'id' I first learned how to pass the list using this: Django pass list to form to create Choices models.py class Grade(models.Model): """Each time a new score is added we create a grade object to track history of grades""" score = models.CharField( max_length=3, choices=PROFSCALE, blank=True, default=INCOMPLETE) assessment = models.ForeignKey( Assessment, on_delete=models.CASCADE, null=True, blank=True) objective = models.ForeignKey( Objective, on_delete=models.CASCADE, blank=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) cblock = models.ForeignKey(Classroom, on_delete=models.CASCADE, default=1) time_created = models.DateField( auto_now=False, auto_now_add=False, default=timezone.now) class Objective(models.Model): """The gradebook is graded agains learning objectives""" course = models.ForeignKey(Course, on_delete=models.CASCADE) objective_name = models.CharField(max_length=10) objective_description = models.CharField(max_length=30) def __str__(self): return self.objective_name forms.py class SingleGradeForm(forms.Form): """ form for adding in one single grade for a student. """ SCORE_CHOICES = ( ("IN", "I"), ("BE", "BEG"), ("DV", "DEV"), ("AP", "APP"), ("EX", "EXT"), ) score = forms.ChoiceField(choices=SCORE_CHOICES) objective = forms.ChoiceField(label='Learning Objectives', choices=[]) time_created = forms.DateField(widget=forms.TextInput( attrs={'type': 'date'}), label='Assessment Date') # from https://stackoverflow.com/questions/53177528/ def __init__(self, objs=None, *args, **kwargs): super(SingleGradeForm, self).__init__(*args, **kwargs) if objs: self.fields['objective'].choices = [ (o.id, o.objective_name) for o … -
How to get Django Admin Log Entries from last hour?
In standard Django, the django_admin_log table shows the date and time of changes to the database entries in the action_time column: sqlite> select * from django_admin_log; 1|2021-07-18 21:34:01.312033|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 2|2021-07-18 21:47:02.451262|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 3|2021-07-18 22:09:42.689067|6|[6] (1960-03-20) Pat Three|[]|8|1|2 4|2021-07-18 22:09:52.292117|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 5|2021-07-19 12:21:57.715529|9|[9] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 6|2021-07-19 12:35:22.504624|9|[9] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 ... more entries I'd like to query the entries based on some comparison, I assumed a naive ansatz could work with filter (as is possible in SQLite itself), so I'd like the Python equivalent of the below SQL statement: sqlite> select * from django_admin_log where action_time > '2021-07-20'; 12|2021-07-20 16:34:00.114548|13|[13] (1960-01-20) Pat Changed|[{"changed": {"fields": ["Family name"]}}]|8|1|2 I thought it would be something along the lines of from django.contrib.admin.models import LogEntry last_hour_changes = LogEntry.objects.filter(last_hour > action_time) -
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?