Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Speeding Up Cors Request in React Native
I have recently been developing an application in React Native with a Django Rest Framework backend, and we need to send the requests through a cors-anywhere online proxy. This makes the app really slow, how can I speed this up? -
return render() or any response after get dats from ajax on django python
I am new to django and I am using the django-easy-pdf library. I am sending an Ajax request to the django framework, I catch the data and with it I generate a response to display a pdf. I would like my view () method in djando not to return a JsonReponse but to return my response to view the generated pdf js / ajax code: $(function () { $(document).on('submit', '#f_generateCot', function (e) { e.preventDefault(); $.ajax({ url: $("#bGenerate").attr('urlDestinity'), data: { datsCot: JSON.stringify({ customerName: $("#nClient").val(), customerEmail: $("#emClient").val(), placeName: $("#nPlace").val(), placeAddress: $("#dPlace").val(), projectName: $("#nProject").val(), proposalNumber: $("#nPropuesta").val(), durationWork: $("#dProject").val(), unitDuration: $("#dUnd").val(), autorName: $("#fName").val() + $("#lName").val(), dateToday: new Date(), }), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, type: 'POST', dataType: 'json', success: function (data) { }, error: function () { } }); }); }); python code: from easy_pdf.rendering import render_to_pdf_response def docCotHtml(request): datsCot = {'customerName': 'seed'} resp = render_to_pdf_response(request, 'generateCot/modelCot.html', datsCot, download_filename='cot.pdf', content_type='application/pdf') if request.method == 'POST': datsCot = json.loads(request.POST.get('datsCot')) resp = render_to_pdf_response(request, 'generateCot/modelCot.html', datsCot, download_filename='cot.pdf', content_type='application/pdf') return resp #return JsonResponse() return resp -
Form not Submitting value when clicking submit button
I am using django forms to submit a report. But after clicking on submit button it sends POST request but no data is added in POST request. this is my forms.py class WeeklyForm(forms.Form): teachers = forms.ModelMultipleChoiceField(queryset=CustomTeacher.objects.values_list('tname', flat = True), widget =forms.Select( attrs ={'class': 'form-control' , 'placeholder' : ' Teachers Name '})) students = forms.ModelMultipleChoiceField(queryset=CustomStudent.objects.values_list('sname', flat = True), widget =forms.CheckboxSelectMultiple( attrs ={'class': 'form-control' 'form-check-input' 'form-check-inline', 'placeholder' : ' Students Name '})) class_name = forms.CharField(widget= forms.Select(choices= [('1', 'UKG'), ('2', 'Class 1'), ('3', 'LKG'), ('4', 'Montessori') ] ,attrs={'class': 'form-control', 'placeholder' : 'Select Class'})) date = forms.DateField(initial = datetime.date.today() , required=False, widget =forms.DateInput( attrs ={'class': 'form-control' , 'placeholder' : ' Date ', 'name' : 'date'})) objective = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'objective'})) target = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'target'})) how = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'how?'})) material = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'material required'})) support = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'Any Support Required?'})) This is function from views.py which I am using to get data and insert into database view.py def weekly(request): context = '' form = WeeklyForm() context = {'form': form} if request.method == 'POST': form = WeeklyForm(request.POST) if form.is_valid(): tname1 = form.cleaned_data['teachers'] … -
I want to send and notification message in WhatsApp using django app
I have a multi-vendor eCommerce Django project, I want to send WhatsApp notification messages to all the customer in my Django project. I would like to know if there is a way to connect to WhatsApp to send messages in Django? -
Python 3 urllib giving TypeError
I'm trying to integrate shippypro with my project using their API docs ,but I'm getting this error "POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str." I'm using python version 3+. from urllib.request import Request, urlopen def get(self, request, *args,**kwargs): values = """ { "Method": "GetTracking", "Params": { "Code": "RHRJ233243" } } """ headers = { 'Content-Type': 'application/json', 'Authorization': 'Basic APIKEY' } request = Request('https://www.shippypro.com/api', data=values, headers=headers) response_body = urlopen(request).read() print(response_body) -
Django model relationships make avg ratings be an average of ratings number field
So I have two Django Models 'Movie' and 'Rating' i want the Movie field avg_rating to be an average of the ratings belonging to that movies number field. I also want the avg_rating on the movie field to update every time a review is added. Im new to Django so I don't really know where to start. Below is my models file. any help would be appreciated from django.db import models from django.db.models import IntegerField, Model from django.core.validators import MaxValueValidator, MinValueValidator class Movie(models.Model): title = models.CharField(max_length=200) date = models.DateField() image = models.CharField(max_length=200) details = models.CharField(max_length=500) genre = models.CharField(max_length=50) duration = models.CharField(max_length=20) classification = models.CharField(max_length=50) avg_rating = models.PositiveSmallIntegerField( default=1, validators=[ MaxValueValidator(5), MinValueValidator(0) ] ) class Rating(models.Model): number = models.IntegerField( default=1, validators=[ MaxValueValidator(5), MinValueValidator(0) ] ) comment = models.CharField(max_length=200, default='') movie = models.ForeignKey(Movie, default=1, on_delete=models.CASCADE) -
error "(13: Permission denied) while connecting to upstream on nginx, Django and uwsgi
can some please help me to understand this problem please? I am getting "502 bad gateway" error in my browser and in the nginx logs I'm getting error "(13: Permission denied) while connecting to upstream, client". I have deployed python 3.6.8, uWSGI 2.0.19.1 , Django 3.07 and nginx/1.14.1 . can someone be kind enough to look at my settings and logs copied below and possibly offer some advice? my uwsgi_params location and security settings (HomeTM) [root@localhost Home_Task_Manager]# ls db.sqlite3 manage.py Home_Task_Manager Home_Task_Manager.sock uwsgi_params (HomeTM) [root@localhost Home_Task_Manager]# ls -lah total 8.0K drwxr-xr-x. 3 root root 130 Aug 10 08:24 . drwxr-xr-x. 6 root root 193 Aug 10 16:51 .. -rw-r--r--. 1 root root 0 Jul 1 16:22 db.sqlite3 -rwxr-xr-x. 1 root root 644 Jul 1 16:19 manage.py drwxr-xr-x. 3 root root 156 Aug 9 16:28 Home_Task_Manager srw-rw-rw-. 1 nginx root 0 Aug 10 08:24 Home_Task_Manager.sock -rw-rw-rw-. 1 nginx root 664 Jul 19 00:25 uwsgi_params (HomeTM) [root@localhost Home_Task_Manager]# mysite_uwsgi.ini location and permissions: _____________________________________________________________________________ (HomeTM) [root@localhost HomeTM]# ls -lah total 12K drwxr-xr-x. 6 root root 193 Aug 10 16:51 . drwxr-xr-x. 4 root root 87 Aug 10 06:13 .. drwxr-xr-x. 3 root root 265 Jul 14 22:45 bin drwxr-xr-x. 2 root root 6 … -
django - testing a django-admin command using mock
I have a command (let's call it do_thing): class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("filename", type=str) def handle(self, *args, **kwargs): with open(kwargs["filename"]) as f: # do something with the data here and I want to use unittest.mock.mock_open() to simulate reading from a file. Based off the example shown in the link above, I currently have (in a test in tests.py): with patch('__main__.open', mock_open(read_data="some content here")) as m: call_command("do_thing", "foo.txt", run=True) However, when I run this, Django/Python acts as if the mock patch had no effect: FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt' What am I doing wrong here? Thank you! -
twitter developer api oauth gives bad authentication data, but all good
Trying to get Twitter to authenticate my get request to the new api for recent tweets around a particular topic. I have some issues with the authentication, that I can't seem to pin down. I authenticated my application using a client key and client secret, then authenticated a user and accepted that the app can read and write permissions. With the users authentication token and secret I tried to authenticate to get the data from the newish api and got bad authentication error. Can you see what I am doing wrong?: curl --request GET --url 'https://api.twitter.com/2/tweets/search/recent?query=python' --header \ 'authorization: OAuth \ oauth_consumer_key="i_put_api_key_here",\ oauth_consumer_secret="i_put_api_secret_here",\ oauth_token="i_put_user_token_after_accepting_app_can_make_changes",\ oauth_token_secret="i_put_oauth_token_secret", \ oauth_signature_method="HMAC-SHA1",\ oauth_timestamp="",\ oauth_version="1.0"' return data is: {"title":"Unauthorized","type":"about:blank","status":401,"detail":"Unauthorized"} I'm referring to this document: https://developer.twitter.com/en/docs/authentication/oauth-1-0a I'm pretty sure I am supplying all the data it needs correctly. -
Python-Django-Template and PHP Integration: why not?
Title. I have a project coded in Python using Django as the framework, as well as using Python Django-templates for the frontend for a business. I'm planning to integrate a payment system into it and from what I've seen, most of them are coded in PHP. I've already built a sort of checkout screen using the Django-template that could still slot in the payment screen before finalizing the transaction of the product. (I'm still researching on whether this is the best implementation, or whether I should do alot of redirections) As a PHP newbie, naturally I started researching on how do I go about implementing this(as I dont even know where to start). I came across ('refer to the FAQ on the linked site which LOLs at the idea') a ('it's a terrible idea') few ('it's an awful idea') topics ('Please do not encourage anyone to use PHP inside Django, this is wrong on so many levels') that discourages PHP and Django use. The one thing in common is that none of those ever explain why exactly is it a bad idea... Why? -
How to do a logical operation before saving to database in python Django
So i am new to Django, and i want to make some hardware compatibility check feature in my app, i make a form to be filled and check the compatibility from database then show me the result. but the problem is the form seems to just keep saving to database without processing the logical operation first. this is my view class CreateSimView(LoginRequiredMixin, CreateView): login_url = '/login/' model = Simulation form_class = SimPostForm template_name = 'sim_post.html' redirect_field_name = 'sim/sim.html' def simpost(request): mtb = Motherboard.objects.all() cpu = Cpu.objects.all() vga = Vga.objects.all() ram = Ram.objects.all() storage = Storage.objects.all() mtbform = request.GET.get('mtb_name') cpuform = request.GET.get('cpu_name') vgaform = request.GET.get('vga_name') ramform = request.GET.get('ram_name') strform = request.GET.get('str_name') simcpu = cpu.objects.values_list('socket', flat=True).filter(name__icontains=cpuform) simcpu1 = mtb.objects.values_list('socket', flat=True).filter(name__icontains=mtbform) simvga = vga.objects.values_list('vga_interface', flat=True).filter(name__icontains=vgaform) simvga1 = mtb.objects.values_list('vga_interface', flat=True).filter(name__icontains=mtbform) simram = ram.objects.values_list('mem_type', flat=True).filter(name__icontains=ramform) simram1 = mtb.objects.values_list('mem_type', flat=True).filter(name__icontains=mtbform) simstr = str.objects.values_list('str_interface', flat=True).filter(name__icontains=strform) simstr1 = mtb.objects.values_list('str_interface', flat=True).filter(name__icontains=mtbform) if simcpu == simcpu1 : if simvga == simvga1: if simram == simram1: if simstr == simstr1: form = SimPostForm(request.POST) if form.is_valid(): form.save() return render(mtbform,cpuform,vgaform,ramform,strform,"/") else: strform = "not compatible" return render(mtbform,cpuform,vgaform,ramform,strform,"/") else: ramform = "not compatible" return render(mtbform,cpuform,vgaform,ramform,strform,"/") else: vgaform = "not compatible" return render(mtbform,cpuform,vgaform,ramform,strform,"/") else: cpuform = "not compatible" return render(mtbform,cpuform,vgaform,ramform,strform,"/") my models for the form … -
Syncing users across multiple platforms
We have a mobile app with firebase as a backend and a web app with Django as a backend. What is the best way to can make it possible for the users of one app to login into the other with same login credentials? -
Solr and Haystack autocomplete with spaces
I am trying to get an autocomplete / auto-suggest function working, and have encountered a problem with Haystack (latest master) and Solr (6.6.6). I am using Haystack's autocomplete() function, which requires the indexed field to be an EdgeNgram (or Ngram). The autocomplete queries work fine until I have a space and start the beginning of a second word. For example: "st" yields ["Star Wars", "Starlight Express"...] "wa" yields ["Star Wars", "Waterworld"...] "star" yields ["Star Wars", "Starlight Express"...] However, as soon as I get to a space and the start of a second word I get no results: "star w" yields no results From my investigations so far this seems to be because Haystack is converting the two word phrase into an AND based two word query. "star AND w", or (AND: ('title', 'star'), ('title', 'w')). The combination of the AND operator and the second query term "w", which is not a valid stem, means that no results are returned. I could override Haystacks autocomplete to use the OR operator to partially fix this... But, is there a better approach / solution? Ideally I would like the search for "star w" to return "star wars" (and not all films starting with … -
Django/Python Guidance
I am trying to build an e-commerce website using Django, most specifically with the Django-Shop package and I am having some troubles along the way, and I just thought that if I could find a mentor or somebody to help me during the way would be the perfect way for me to learn more and be able to finish the project. And I am willing to pay for that, so if you already used Django-shop for some project or are confident about helping me to build an e-commerce website with normal Django I would be more than happy to work with you. So that you know where I got stuck now, I simply cannot make a new product type based on the BaseProduct model that I have, it seems like a very good idea to kickstart the project using the Django-shop package, but it is very hard to understand it as a whole since there is a lot of code on it already. -
<class ‘decimal.ConversionSyntax’> errors when importing data from a CSV file using Python (tried using CSV and Pandas)
I have a CSV file from a small business that represents their records for about 70,000 orders spread out over about 30 years. My goal is to store this data in a Django project with a DecimalField in the model setup to receive the import. Before trying to store the data in Django I'm first trying to import this data into Python. While most of the records import fine there are about 1 in 1000 that throw off a <class 'decimal.ConversionSyntax'> error during the import. This is causing me to get incorrect data into Python. I need to either fix how it reads the data or fix the problem in the data itself. I have tried both the python csv library and pandas to open the file. I've looked at the csv file in a text editor (SublimeText) and can't find any anomalies with the way the data is stored. I have tried to convert the data to UTF-8 using Microsoft Excel I have attempted to copy the data out of Excel into SublimeText, then back from SublimeText into a new row in Excel (virgin row with no data in it beforehand). None of this has resolved the issue. How … -
optimizing django model @property
I am new to django and django-rest-framework. I have a project to optimize an API endpoint and found a use case where a @property on a model which return a boolean expression whenever being called on the SerializerMethodField() found to be the cause of N+1 problem on SQL queries using django-debug-toolbar. Is there any way or a proper way implement this so I can eliminate the N+1 problem on SQL. Please see below code. Thanks. model: class StudentActivity(BaseModel): bootcamper = models.ForeignKey(Bootcamper, blank=False, null=False, on_delete=models.CASCADE) class_activity = models.ForeignKey(ClassActivity, blank=False, null=False, on_delete=models.CASCADE) score = models.FloatField(blank=True, null=True, choices=constants.ACTIVITY_SCORES) score_date = models.DateTimeField(blank=True, null=True) web_path = models.URLField(blank=True, null=True) user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) @property def is_graded(self): return self.class_activity.studentactivity_set.filter(score__isnull=False).exists() serializer: class BootcampClassStatisticsSerializer(ModelBaseSerializer): pass_rate = serializers.SerializerMethodField() def get_pass_rate(self, instance): pass_rate = None total_student_activities = 0 pass_count = 0 bootcampers = instance.bootcamper_set.all() date = self.context.get('date') for bootcamper in bootcampers: student_activities = bootcamper.studentactivity_set.all() if date: student_activities = student_activities.filter(class_activity__date=date) for sa in student_activities: if sa.is_graded: total_student_activities += 1 if sa.score == constants.PASS or sa.score == constants.SUPERB: pass_count += 1 if total_student_activities: pass_rate = round(pass_count / total_student_activities * 100, 2) return pass_rate class Meta: model = BootcampClass fields = ( 'id', 'batch_number', 'start_date', 'end_date', 'class_type', 'pass_rate' view: class BootcampClassStatisticsList(APIView): queryset … -
how can I get details from restful api django?
I am pretty new with restful Django, but I am not new with Django framework at all, but I want to create an endpoint where I can grab customers by id e.g. detail/<id> customers/ to grab all serializers.py class CustomersSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' views.py class CustomerViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): """ get all """ queryset = Customer.objects.all() serializer_class = CustomersSerializer urls.py router = DefaultRouter() router.register(r'customer', CustomerViewSet) # get all router.register(r'detail', DetailViewSet) # detail/<id> class DetailViewSet(...): ???? -
How do I use a ModelForm in UpdateView with type=datetime-local?
class AppointmentViewForm(ModelForm): class Meta: model = Appointment fields = '__all__' widgets = { 'appointment_date': DateTimeInput( format =('%Y-%m-%d %H:%M'), attrs={ 'type': 'datetime-local' }, ) } I want to use a DateTimeInput instead of a TextInput for a DateTimeField in a ModelForm that's intended to be used as a form_class. When I render my ModelForm into my UpdateView, all of my other object fields are instanced per usual. However, if I use my widget for 'appointment_date', I get back a field with a blank field form (no datetimefield instance). On top of the field not being instanced, I am unable to save my form with the current information I have in the widget. Any way to fix these two issues? -
URL arguments processing in Django Forms and Class-Base Views
I need help. I am a newbie. I have difficulty in accomplishing the following: Pass the URL argument which is Base.id into a Class-Base View and Form CLass Extracting the URL argument Base.id to create the base object in the ProjectCreateForm Extract the base_file of Base object and collect the keys using pandas dataframe Assign the keys as choices to the ProjectCreateForm's column_selector MODELS: The are the models class Base(models.Model): name = models.CharField(max_length=50, default='New Model') base_file = models.FileField(upload_to='project-files') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('base-detail', kwargs={'pk': self.pk }) class Project(models.Model): title = models.CharField(max_length=50, default='New project') base = models.ForeignKey(Base, on_delete=models.CASCADE) base_file_columns = models.CharField() def __str__(self): return self.title def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk, 'base': self.base }) VIEW: How I can improve this to later on process the input of the user. class ProjectCreateView(LoginRequiredMixin, CreateView): model = Project fields = ['title', 'base'] template_name = 'projects/projectCreate.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) FORM: How can I use the URL argument in the form class ProjectCreateForm(forms.ModelForm): name = forms.CharField(max_length=100) base_file_columns = forms.CharField( widget = forms.Textarea() ) column_selector = forms.MultipleChoiceField( widget = forms.CheckboxSelectMultiple # label="Select Feature Predictor:" ) def __init__(self, *args, **kwargs): super(ProjectCreateForm, self).__init__(*args, **kwargs) ### NOT SURE … -
Django REST Framework how to retrieve Nested relationships
I'm using Django Rest framework in my project and I need to retrieve data from my Author model and related Books model, so the data should look like this: { 'author': 'SomeAuthor', 'books': [ {'title': 'Example1'}, {'title': 'Example1'}, {'title': 'Example1'}, ... ],}. { 'author': 'SomeAuthor2', 'books': [ {'title': 'Example1'}, {'title': 'Example1'}, {'title': 'Example1'}, ... ], } my here is models.py: class Author(models.Model): author = models.CharField(max_length=50, null=True, blank=True) class Book(models.Model): title = models.CharField(max_length=50, null=True, blank=True) author = models.ForeignKey('Author', on_delete=models.CASCADE) as was described here, my serializer.py looks like this: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['title'] class AuthorSerializer(serializers.ModelSerializer): book = BookSerializer(many=True, read_only=True) class Meta: model = Author fields = ['author', 'book'] here is my views.py: def author_list_view(request): if request.method == 'GET': author_list = Author.objects.all() serializer = AuthorSerializer(author_list, many=True) return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and i've got this result: [ { "author": SomeAuthor, }, { "author": SomeAuthor2, } ] without books, what i'm doing wrong? -
Why am I getting this error? too many values to unpack (expected 2)
I'm creating a blog of stocks and in the views.py I defined the stocks that are in the database, but I don't understand what this error means, so I need a little help with this, thanks in advance! Here are the relevant code parts so you can see what's going on here. Traceback Traceback (most recent call last): File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\snin2\Desktop\basura\lapagina\app1\views.py", line 62, in StockView stock_sym = StockNames.objects.get(StockNames.objects.all()) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 404, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1247, in build_filter arg, value = filter_expr ValueError: too many values to unpack (expected 2) views.py def StockView(request, sym): stock_sym = StockNames.objects.get(StockNames.objects.all()) stock_posts = Post.objects.filter(stock__symbol=sym) return render(request, 'app1/stockview.html', {'stocks':stock_posts, 'sym':sym, 'stock_sym':stock_sym}) urls.py (the last urlpattern) from django.urls … -
Images don't get loaded in production
I am creating a website with Django and has several pictures that are added depending on what I put on the database. In order to host the website online, I used Heroku and used their PostgreSQL database for my online database. For some reason as soon as I upload the images they were there, but after some time they all disappeared. Django knows that the images exist and the URL for that image is also perfectly fine when I right-click the image and click open on a new tab. This is how my website is now... -
Python/Django/MySQL optimisation
Just a logic question really...I have a script that takes rows of data from a CSV, parses the cell values to uniform the data and makes a check on the database that a key/primary value does not exist so as to prevent duplicates! At the moment, the 1st 10-15k entries commit to the DB fairly quick but then it starts really slowing as there are more entries in the DB to check against for duplicates....by the time there are 100k rows in the DB the commit speed is about 1/sec argh... So my question, is it (pythonically) more efficient to extract and parse the data separately to the DB commit procedure (maybe in a class based script or?? Could I add multiprocessing to the csv parsing or DB commit) and is there a quicker method to check the database for duplicates if i am only cross-referencing 1 table and 1 value?? Much appreciated Kuda -
how to make get user specific posts in django
I am creating a web app where users are allowed to post stuffs and i have a profile section where i want users to see the stuffs they have posted so i am using IF loop in django. {% if user_post.author == "request.user.username" %} hello there {{user_post.title}} {% else %} try againnn {{user_post.author}} {{request.user.username}} {% endif%} here in the if loop i am checking for all the authors and comparing them with the user logged in. but it is not executing, in the else part i am confirming names of the user . but the else part is executing. i am not sure if it can be done this way..if not please suggest me a way thanks -
Unable to open downloaded file embedded file link in a webpage because file format or extension is not valid
My client has requested that I embed a link for a downloadable excel in my react/django site and unfortunately the download works whenever I run the site on my local, but after deployment you can successfully download the link, but whenever you open it, excel throws a popup that says "Excel cannot open the file 'filename' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file. I've checked the file in the directory of the build on GAE and the extension is still .xlsx, after the download I still see the .xlsx extension in my downloads folder. I've even tried to convert the excel to a pdf and embed that link, and while that still works on my local, after deployment I get "Failed to open file." I'm not sure if this is actually related to the deployment or some of the config settings in django or react tripping me up similar to how static images need to be specified in the app.yaml. I've searched the documentation on the subject on their site here: https://cloud.google.com/appengine/docs/flexible/python/reference/app-yaml and nothing jumps out to me …