Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Redirect not updating page
I am having an issue with successfully calling a redirect after a user tries to login (successful or unsuccessfully). In the console I did notice that the GET and POST statements are correct. Thank You all in advance as this is a becoming a royal PIA. views.py class UserLoginFormView(View): form_class = UserLoginForm template_name = 'home/login.html' #Display Blank Form def get(self,request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) #Process Form Data def post(self,request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: return redirect('products') urls.py urlpatterns = [ url(r'^$', views.HomeView, name='home'), url(r'^register/$', views.UserFormView.as_view(), name="register"), url(r'^login/$', views.UserLoginFormView.as_view(), name="user_login"), url(r'^products/$', views.ProductsView, name="products"), ] login.html <form class="cozy" action="" method="post"> {% csrf_token %} <div class="form-group control"> <label for="username" class="control-label">Username</label> <input type="text" name="username" id="username" class="form-control"> </div> <div class="form-group control"> <label for="password" class="control-label">Password</label> <input type="password" name="password" id="password" class="form-control"> </div> {% if form.errors %} <p class=" label label-danger"> Your username and password didn't match. Please try again. </p> {% endif %} <div class="d-flex align-content-center justify-content-center"> <button type="submit" class="btn btn-lg btn-accent">Login</button> </div> </form> Console Output System check identified no issues (0 silenced). January 25, 2019 - 15:39:24 Django version 1.11.18, using settings 'svcreporter.settings' Starting development server … -
How do I activate database settings from my settings.py DATABASES array based on environment?
I'm using Django with Python 3.7. I have a settings.py file, which includes some database settings ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mainpage', 'USER': 'mainpage', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' }, 'production': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mainpage', 'USER': 'mainpage', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' } } The file includes a bunch of other things but I have only included the database array here. Is it possible to activate a particular database configuration from my array based on my environment or an environment variable? I would prefer not to have multiple settings files because then I have to repeat a lot of other configurations in them that do not change across environment. I'm happy to move the database settings to their own files if that's what it takes but I'm not sure how they would be activated. -
What is wrong with this code?? it doesn't log in and always the if..else result is false
The result of the this code always goes with else even if I entered the email and password right ... Some extra text so that the post becomes valid to be published Html page:- <div class="col-lg-2 col-lg-offset-3 col-md-offset-1 col-md-4"> <label>Email address:</label> </div> <div class="col-lg-4 col-md-6"> <div class="form-group"> <input name="user_email" type="email" class="form-control input-lg"> </div> </div> <div class="col-lg-3 col-md-1 visible-md visible-lg"></div> <div class="clearfix"></div> <!-- end email row --> <!-- start password row --> <div class="col-lg-2 col-lg-offset-3 col-md-offset-1 col-md-4"> <label>Password:</label> </div> <div class="col-lg-4 col-md-6"> <div class="form-group"> <input name="user_password" type="password" class="form-control input-lg"> </div> </div> views.py:- def loginUser(request): if(request.method=='POST'): email = request.POST['user_email'] password = request.POST['user_password'] user = authenticate(request, email=email, password=password) if(user): login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse('error') else: return render(request, 'logIn.html') urls.py:- urlpatterns = [ path('admin/', admin.site.urls), path('', views.indexPage, name='index'), path('signup/', views.signUp, name='signup'), path('login/', views.loginUser, name='login') ] -
Is there a difference in a django website deployed to aws elastic beanstalk between a mobile device or desktop computer?
I have deployed my web app (which right now is just some templates with js and css) to aws elastic beanstalk and the website is up and running. I used a predefined theme for the layout of the website that includes responsive design. On a dekstop computer the website is looking fine, even if I manually resize the window. In every resolution it looks great! Every icon and image gets loaded perfectly. Now if I want to look at the website on my smartphone (mobile device) it starts "srewing" up. It adds a white bar below the start page and on different browsers it just mixes some divs completely up, rendering them on the top of the page instead of the bottom. Some icons also are not correctly displayed. I tried different browsers for the desktop pc, everything fine. On the smartphone I have problems on all browsers. I checked the website (www.meyn-computer-lotse.de) on the http://www.mobilephoneemulator.com/ and there the website is also displayed perfectly. I just cannot find my mistake... Now I kinda have two questions: 1. Is there an easy way on a mobile device to lookup the css rules for the website, cause on the desktop pc I … -
How Can I Pass A Parameter From A DetailView To An UpdateView?
I am trying to pass a parameter from a DetailView to an UpdateView if the user clicks on a button. I've done this with other views, createview and updateview, but can't quite work out how to do this from a DetailView to an UpdateView. In my DetailView, I have an HTML button on the View that looks something like.. <button type="submit" name="status" value="cancel"></button> I am trying to pass the cancel value to the UpdateView.... I have tried to override POST as shown below: def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('Book:author_menu')) else: return super(BookView, self).post(request, *args, **kwargs) However when I do this it says method is not allowed. I also played around a bit with get_object....And while it does allow me to get the existing values...I can't seem to get the passed value... def get_object(self, queryset=None): obj = super(BookView, self).get_object(queryset=queryset) return obj I am trying to update/feed the cancel parameter to the UpdateView and then do something. Thanks in advance for any thoughts. -
How show JSON data from queryset in a Django listview template?
I'm trying to show information from my database as Listview template in a Django project, I've serialized my model and created the url for the JSON. I'm new on ajax / javascrip and I don´t understand how to make that "link" in order to be able to show the information from the JSON in the listview, the reason I want to do it in this way is that a "normal" render through a loop for over each one of the elements in the model takes a lot of time and reviewing some information I've found that use a JSON source is a good option. After serialized and go to the URL of the JSON, data is rendered and the JSON has a valid structure (I only show one as the entire result has more than 10000 records): JSON from my queryset I have tried the following code but data is not rendered in my template: views.py class datosview(generic.ListView): model = datos template_name = 'data/data_list.html' context_object_name = 'obj' from django.core import serializers from django.http import HttpResponse def data_json(request): query_set = serializers.serialize('json', datos.objects.all(), fields=('Insp_Lot', 'Description', 'Date', 'Material', 'Batch', 'Mean_Valuation','Lower_Limit', 'Upper_Limit', 'Target', 'Delvry_Quantity')) return HttpResponse(query_set, content_type='application/json') urls.py from django.urls import path from data.views … -
xhtml2pdf is not rendering my css file Django 2
I'm trying to create a pdf using xhtml2pdf. However, xhtml2pdf is not rendering the semantic-ui css using cdn. def render_to_pdf(path: str, params: dict): template = get_template(path) html = template.render(params) response = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), response if not pdf.err: return HttpResponse(response.getvalue(),content_type='application/pdf') else: return HttpResponse("Error Rendering PDF", status=400) -
How vertically center div in bootstrap col
I wand to create square boxes with a text center in it. Below is what I wish : I'm using Django and Bootstrap. To do my square, I have followed the instructions here : http://www.mademyday.de/css-height-equals-width-with-pure-css.html Then, here it is my HTML code : <div class="container-fluid d-flex h-100 flex-column"> <div class='row flex-fill'> <div class='colonne_salle col-sm-2'> <div class='row'> {% for s in salle %} <div class='col-sm-6 square'> <div class="bloc-salle" id="{{ s.name }}"> <h3 class='nom-salle'>{{ s.name }}</h3> </div> </div> {% endfor %} </div> </div> And my css : .bloc-salle{ /* margin : 15px 0 15px 0; */ position: absolute; top: 0; left: 0; bottom: 0; right: 0; } .square:before{ content: ""; display: block; padding-top: 100%; /* initial ratio of 1:1*/ } For the moment, I'm getting this result : Thanks a lot if you can help me ! -
CORS issue with Django and React hosted on same server
I am having a CORS issue with my Django Rest Framework and React app on the same server. I am running Vagrant with an Ubuntu 18 box and NGINX installed (I am assuming this issue will translate to DigitalOcean) I apologize ahead of time if I am providing too much information. DRF is using Supervisor and Gunicorn is on port 8000. I created my React app using create-react-app. I then used npm run build to create the static files. NGINX Setup: React Conf server { listen 8080; server_name sandbox.dev; root /var/sites/sandbox/frontend/build; index index.html; client_max_body_size 4G; location / { try_files $uri $uri/ /index.html; } Django Conf upstream sandbox_server { server unix:/var/tmp/gunicorn_sanbox.sock fail_timeout=0; } server { listen 8000; server_name api.sandbox.dev; ... location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://sandbox_server; break; } Django Setup: INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', 'myapp', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] I have tried the following with no luck CORS_ORIGIN_ALLOW_ALL = True and CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ('localhost:8080',) React App.js ... fetch("http://localhost:8000/api/v1/token-auth/", { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({"email":"test@user.com", "password":"testuser"}), }) So to state the obvious CORS is correct because the Origin is … -
Is there a way to make a table from two queries of a model?
I'd like to be able to display a table with a stores current value, as well as the value from last year. Right now I query all the stores, and then for each store I loop through and get the value from the comparison date and time. But this ends up taking 60+ queries. class Stores(models.Model): storeid = models.IntegerField(default=0, primary_key=True) location = models.CharField(max_length=128) class ShowroomData(models.Model): store = models.ForeignKey(Stores, db_column="storeid", default=0, on_delete=models.CASCADE) date = models.DateField(db_index = True) # Field name made lowercase. time = models.IntegerField() # Field name made lowercase. sales = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase. tax = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase. My views.py for store in current_data: comparison_data = ShowroomData.objects.filter(store=self.store, date=comparison_date, time=self.time) if comparison_data: for record in comparison_data: store.compare_amount = record.sales + record.tax I'd like to be able to store all of these in one query set, and then loop over it in the templates instead of having to loop through in the beginning to re append the query. -
Django: Get TabularInline model objects
I am learning the basics of Django web but and I'm stuck in a problem I have the following models(simplified) at models.py : class CustomUser(AbstractUser): # Custom Admin Model def __str__(self): return self.username def __len__(self): return 1 class Task(models.Model): title = models.CharField(max_length=250, blank=False) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default=None) and also this at admin.py : class TaskInline(admin.TabularInline): model = Task class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username'] inlines = [TaskInline] fieldsets = ( (('User'), {'fields': ('username', 'email')}), ) I am currently working on a TODO web app and what I would like to do is to show the Title of Task model in an HTML. Looking for something like this: {{ user.inlines[0].title }} # This does not work Is it even possible? May I have to create a function for CustomModel that returns his inline models (ex: get_inline_models(self))? Other solutions? Thanks in advance :) -
Multipart Image Upload in DRF on CREATE
I would like to have a model for which you can upload multiple images on create(post). In DRF web view on api/animals/ in the post form I would like to add multiple images and create the new Animal with the images attached. Let us assume I have the following models: class Animal(models.Model): slug = models.CharField(max_length=20, unique=True) class AnimalImage(models.Model): animal = models.ForeignKey(Animal, on_delete=models.CASCADE) image = models.ImageField(upload_to='animal_pics/') The I have the following serializers: class AnimalImageSerializer(serializers.ModelSerializer): class Meta: model = AnimalImage fields = ('animal', 'image', ) class AnimalSerializer(serializers.HyperlinkedModelSerializer): images = AnimalImageSerializer(many=True) class Meta: model = Animal lookup_field = 'slug' extra_kwargs = { {'url': {'lookup_field': 'slug'} } fields = ('slug', 'images', ) The I have the following rest views: class AnimalViewSet(viewsets.ModelViewSet): queryset = Animal.objects.all() serializer_class = AnimalSerializer lookup_filed = 'slug' parser_classes = (JSONParser, MultiPartParser, FormParser) When I use the the drf web interface: In my javascript I would like to do something like this but Upload all files in one batch somehow during a post request with a new Animal: dropArea.addEventListener('drop', handleDrop, false); let dt = e.dataTransfer let files = dt.files files.forEach(uploadFile) function uploadFile(file){ let formData = new FormData() formData.append('file', file) fetch('api/animals/', { method: 'POST', body: formData }) } -
How to trigger jquery on bootstrap 3 modal close
I have a django project with the following hidden modal embedded in the page: <div class="modal fade" id="thanksModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" style="text-align: center"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h2>Thank you!</h2> </div> <div class="modal-body"> <h3>We'll get back to you </h3> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> I'm trying to clear the form by redirecting to my django route on closing of the modal box. Following: Open URL on Bootstrap Modal close , I added $(".modal").on("hidden.bs.modal", function () { console.log("MODAL CLOSED") // sanity check window.location = "/myroute/"; }); But nothing is happening, and I do not see MODAL CLOSED in the console. How can I get this working? -
Django application is slow when uploading files
I am working on a web application using the Django framework. Currently, I do some testing under production environments. I am using nginx as reverse proxy to gunicorn. That means in my nginx configuration file there's this content: location / { if (-f /home/mysite/maintenance_on.html) { return 503; } client_max_body_size 10M; try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/mysite/run/gunicorn.sock; } Gunicorn is started using this command: pipenv run gunicorn ${DJANGO_WSGI_MODULE}:application \ --workers 3 \ --threads 2 \ --bind=unix:/home/mysite/run/gunicorn.sock \ --log-level=warning In general, everything works, there's one problem though: When I upload a file (~ 8 MB, it takes about one minute) the whole website is slowed down. That means when I access a page, it takes several seconds until it's loaded. Also, it looks like when I click on a link, nothing happens, and only after some seconds the request is being processed. When the file upload is done, everything is fast again. While I am definitely using a low-powered VPS (~2 GB RAM; 1 core), htop does not indicate any problems with CPU or RAM. There are enough resources available. So, I believe it has something to … -
How to store the selected radio-button value of a user after filling the registration form into database in django?
I am creating a registration page for my website using django. The registration form contains the following fields: Username,E-mail,password,password confirmation, user_type. user_type can be either 'student' or 'organisation' which of radio select type. Depending on the user_type of a user he/she can perform only those specific tasks assigned for that type. So I need a way to store their user_type into the database and later check to let them do a specific task. How can I solve this problem? Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm USER_TYPE_CHOICES = ( ('student', 'Student'), ('organization', 'Organization'),) class UserRegisterForm(UserCreationForm): email = forms.EmailField() user_type = forms.ChoiceField(required=True,widget=forms.RadioSelect, choices=USER_TYPE_CHOICES) class Meta: model = User fields = ['username', 'email', 'password1', 'password2','user_type'] Views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') uType = form.cleaned_data.get('user_type') messages.success(request, 'Account created for {}, You may login now!'.format(username)) return redirect('TakeTest-Home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) Models.py is empty for this app. -
django error m2m in save methods of models
i try to create a user can connect several project, many user sharing project each other; but i want to select one only project per user; i wanna create a new project but without use a other user that he's inside other project; how can i do? class Project(models.Model): name = models.CharField(max_length=128) description = models.TextField(blank=True, null=True) users = models.ManyToManyField(DjangoUser, through='ProjectUser') wms_hosts = models.ManyToManyField(WMSHost, through='ProjectHost') devices = models.ManyToManyField( Device, through='ProjectDevice', blank=True, null=True ) active = models.BooleanField(default=True) def __str__(self): return self.name def save(self, *args, **kwargs): super(Project,self).save(*args, **kwargs) user = ProjectUser.objects.filter(is_active = True) current_user_active = self.users.filter(is_active=True) if current_user_active[0] in user: message = { "Error": 1 } print(message) -
Understanding how the Django Auth app creates its tables
In the models.py file of the Django auth app, there are models for user and group which create their respective tables in the database: class user -> auth_user class group -> auth_group There is no class user_groups, and yet something fancy happens behind the scenes to also create a table auth_user_groups which tracks which users are in which groups. (Each row contains a single user_id and group_id). Can someone help me understand how this happens? I may want to replicate this functionality in my own app, where I associate customer models with a group_id. -
django-oauth-toolkit : Customize authenticate response
I am new to Django OAuth Toolkit. I want to customize the authenticate response. My authenticate url configuration on django application is : url('authenticate/', include('oauth2_provider.urls', namespace='oauth2_provider')) https://django-oauth-toolkit.readthedocs.io/en/latest/install.html Now, when i launch this command : curl -X POST -d 'grant_type=password&username=$username&password=$password' -u "$client_id:$client_secret" http://127.0.0.1:8000/authenticate/token/ I get this response : { "access_token": "ATiM10L0LNaldJPk12drXCjbhoeDR8", "expires_in": 36000, "refresh_token": "II4UBhXhpVDEKWmsUQxDzkj3OMjW1p", "scope": "read groups write", "token_type": "Bearer" } And would like this answer : { "access_token": "ATiM10L0LNaldJPk12drXCjbhoeDR8", "expires_in": 36000, "refresh_token": "II4UBhXhpVDEKWmsUQxDzkj3OMjW1p", "scope": "read groups write", "token_type": "Bearer", "member": { "id": 1, "username": "username", "email": "email@gmail.com", .... } } I just want to override this response for add information of authenticated user. I have read the documentation of django-oauth-toolkit. And i didn't find a solution to my problem... -
Trouble with Django importing random list in base template using ´super´. What is the alternative to my work-around?
I'm trying to load an random list in the title of my webpage (base template). I was able to get this running using Super. However, at this point this is done for every view. This seems illogical. As an amateur I have trouble finding out if this is true and/or if I am even right (I have some trouble interpreting the technical descriptions..). Could someone push me in the right direction? List generation: def generatetraits(): traits = ["trait1", "trait2", "trait3", "trait4", "trait5", "trait6", "trait7", "trait8", "trait9", "trait10", "trait11"] random.shuffle(traits) traitlist = "" for i in range(0, 3): if (i == 0) or (i == 1): traitlist = traitlist + (traits[i] + " | ") else: traitlist = traitlist + (traits[i] + " ") return traitlist SomeView example: class SomeView(TemplateView): template_name = 'about.html' traitlist = generatetraits() def get_context_data(self, **kwargs): context = super(SomeView, self).get_context_data(**kwargs) context.update({'traits': self.traitlist}) return context Base template implementation: <div class="title"> <h1>Name</h1> <p> {{traits}} </p> </div> All pages/views are extended from the base. This makes it logical to me (as amateur;)) that it is just wrong to do this for every view. -
Image(jpg) files which are included in css file are not loading in Django 2.1
I included image(jpg) files in CSS file. CSS File stored in static folder(static/myapp/css) and image files stored in same static file(static/myapp/img). my Project Structure like this: settings.py """ Django settings for svcomforts_1 project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6-eaqeuu+yem7w01f=ih^!298qnmjr0e!agu=c357au02^j+1(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp1', 'myapp2', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'my_website.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { … -
I cannot install the latest version of Django
I already installed Python3.7.2. when I check python version and use python command, it show that I already used its latest version. However, I couldn't install Django. An error code is following 'Could not find a version that satisfies the requirement django==2.1.5' and also 'DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020.'These always show up. Please help, Thank you -
Authentication issue, Django
guys! Sorry for my english language, im from RU. Im write some codes (add information about my clients in database, select this info, display it's on some page on my website and function EDIT information about clients). On page with full informations about clients im display link to "edit" information about this clients. It's work, okey, but when im wrapp link to edit for: {% if user.is_authentificated %} <a href.....>edit</a> {% endif %} LINK IS NOT DISPLAYED, but im authorized! ( go to the admin panel does not require authorization) Please, tell me were am i wrong? -
How to create a CSV file in python that can be saved in memory?
I'm creating a CSV file in django that when you got to a url it downloads the CSV file, it works great the only thing is that I would like it so be saved in memory and not in hard disk. HOw do you do this with the import csv This is for django that uses list to create the csv def data_feed_file(request): open_publications = self.get_publications(user_context) with open('facebook_feed.csv', 'wb') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['id', 'title','description']) for op_pub in open_publications: filewriter.writerow([op_pub.id, op_pub.name, str(op_pub.description)]) with open('facebook_feed.csv', 'rb') as myfile: response = HttpResponse(myfile, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=facebook_feed.csv' return response -
Annotation from regex in When() conditional expression
I need too annotate the result of a regex lookup in a When() conditional expression using the then parameter, DB is Postgresql. For example you can use the SubStr() function to get a substring of a field, I want to be able to use a regular expression instead of a positional substring. I was thinking some custom function using 'REGEXP_MATCHES', I'm not sure how I'd do this though, or if it's even necessary. qs = SomeModel.objects.all() pattern = r'regex' qs = qs.annotate( match=Case( When( some_model_field__regex=pattern, then=Regex('some_model_field', pattern) ), output_field=CharField() ) ) I want the annotation to be the result of the pattern match. -
Django unittests global patch requests
Is there a standard way to patch ALL HTTP requests and print a warning if any function tries to do an actual HTTP request?