Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Action RedirectView need to go with querystring
I have a RedirectView where action redirects specific Url. But I need to filter and click action also. So when I filter the items and click action it redirects me to a specific page. But I want now that action will redirect me to current page always no matter what happens. If the current page is included in query string it redirects me with a query string. If there is no query string its redirect me without the query string, But on the current page. I am using Django FSM for state management and when I click action it changes the state. Here is my code of redirect. class OrderStateChangeView(LoginRequiredMixin,RedirectView): state_change_method: str = None reverse: str = 'orders:manager-orderfilter-search' @property def reverse_kwargs(self): return {} def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Order, pk=self.kwargs['pk']) self.obj = obj try: getattr(obj, self.state_change_method)() obj.save() except: messages.add_message( self.request, messages.ERROR, extra_tags='alert alert-error', message='Unable to process your request.' ) return reverse(self.reverse, kwargs=self.reverse_kwargs) -
Django Rest framework conditional delete
I want to add some condition when DELETE data. Here is my models.py and serializers.py [serializers.py] class articleSerializer(serializers.ModelSerializer): userkey = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) class Meta: model = article fields = ('articleNo', 'content', 'date', 'userkey', 'password') [models.py] class article(models.Model): articleNo = models.AutoField(primary_key=True) userkey = models.CharField(max_length=50, null=False) content = models.CharField(max_length=500, null=False) password = models.CharField(max_length=20, null=False, default='1234') date = models.DateTimeField(auto_now_add=True) For example, below data is in database. | articleNo | content | date | userkey |password| --------------------------------------------------------------------------------- | 33 | test article | 2018-03-11 05:00:15.428661 | a1b2c3d4 | 1234 | When "DELETE" method request, I want to compare request's password and article's password. If it is same, data will be deleted. Refer to document, I think I have to override def delete(). But I don't know exactly what should I do. How can I solve this issue? Thanks. -
How to filter 404 errors getting reported in rollbar
Is there any way to filter 404 error reporting in rollbar? I am using rollbar (0.13.18) in django (1.11). -
How to save ArrayField as set in Django
The goal is removing of duplicates from list field while saving model. For example: m = MyModel.objects.create( array_field=['123','123'], ) m.array_field # ['123'] I tried to overwrite save but it doesn't work class MyModel(models.Model): array_field = ArrayField(models.CharField(max_length=5)) def save(self, *args, **kwargs): if self.array_field: self.array_field = list(set(self.array_field)) super(MyModel, self).save(*args, **kwargs) How can I do this? -
Why other docker containers do not see the accepted migrations?
docker-compose.yml version: '3' services: # Django web server web: volumes: - "./app/back:/app" - "../front/public/static:/app/static" - "./phantomjs-2.1.1:/app/phantomjs" build: context: . dockerfile: dockerfile_django #command: python manage.py runserver 0.0.0.0:8080 #command: ["uwsgi", "--ini", "/app/back/uwsgi.ini"] ports: - "8080:8080" links: - async - ws_server - mysql - redis async: volumes: - "./app/async_web:/app" build: context: . dockerfile: dockerfile_async ports: - "8070:8070" # Aiohtp web socket server ws_server: volumes: - "./app/ws_server:/app" build: context: . dockerfile: dockerfile_ws_server ports: - "8060:8060" # MySQL db mysql: image: mysql/mysql-server:5.7 volumes: - "./db_mysql:/var/lib/mysql" - "./my.cnf:/etc/my.cnf" environment: MYSQL_ROOT_PASSWORD: root MYSQL_USER: user_b520 MYSQL_PASSWORD: buzz_17KN MYSQL_DATABASE: dev_NT_pr MYSQL_PORT: 3306 ports: - "3300:3306" # Redis redis: image: redis:4.0.6 build: context: . dockerfile: dockerfile_redis volumes: - "./redis.conf:/usr/local/etc/redis/redis.conf" ports: - "6379:6379" # Celery worker celery: build: context: . dockerfile: dockerfile_celery command: celery -A backend worker -l info --concurrency=20 volumes: - "./app/back:/app" - "../front/public/static:/app/static" links: - redis # Celery beat beat: build: context: . dockerfile: dockerfile_beat command: celery -A backend beat volumes: - "./app/back:/app" - "../front/public/static:/app/static" links: - redis # Flower monitoring flower: build: context: . dockerfile: dockerfile_flower command: celery -A backend flower volumes: - "./app/back:/app" - "../front/public/static:/app/static" ports: - "5555:5555" links: - redis dockerfile_django FROM python:3.4 RUN mkdir /app WORKDIR /app ADD app/back/requirements.txt /app RUN pip3 install -r requirements.txt … -
How To Create A Form In Django That Combines Choice and Text Data
I am working with Django to create a form for a restaurant app where I would need a user to first select type of product that it has from a list and enter the price they would like to have each item set to. This data will then be passed to an API. Right now I have something like this: class Drinks(models.Model): TYPE = ( ('Sizes', ( ('small', 'Small'), ('medium', 'Medium'), ('large', 'Large') )), drink_size = models.CharField(max_length=1, choices=TYPE) I need for the restaurant to be able to select the size of the drink and then place a value on each drink size. So I think I would need a checkbox and a way to record the value for each size. If you have any idea on how to do this, It would truly appreciated. -
Django Rest framework except specific column
I want to exclude specific column in rest framework only for view data. (not for put data) [models.py] class article(models.Model): articleNo = models.AutoField(primary_key=True) userkey = models.CharField(max_length=50, null=False) content = models.CharField(max_length=500, null=False) password = models.CharField(max_length=20, null=False, default='1234') date = models.DateTimeField(auto_now_add=True) [serializers.py] class articleSerializer(serializers.ModelSerializer): class Meta: model = article fields = ('articleNo', 'userkey', 'content', 'password', 'date') After I change fields = ('articleNo', 'content', 'date') from serializers.py, Only articleNo, content, date will be show in rest framework. But, When I PUT data to article, It doesn't inserted properly. After insert data, MySQL data is below. articleNo|content | date |userkey |password 37 | Test | 2018-03-13 08:01:07.424564 | | 1234 userkey is blank and password is default value. Maybe I have to modify serializers.py I think, But I don't know how to fix it. How can I insert data properly? -
How to save model form Data(User input) into a csv or dict in Django
I am trying to set up a Website for Employee Schedulling with Django. Since i am new to Web development, I run into some problems. I need to pass information to a solver using pyomo. For this employees should be able to pass information his availability through a model form. The information has to be saved like this: Available ={(“Employee name”, “shift”, “day”): 0, (“Employee name”, “shift”, “day”): 0, (“Employee name”, “shift”, “day”): 1} 0 means that the employee is not available on that shift on that day and 1 means he is. Right now I get my data from a csv and transform it into a dict using pandas. Is there any way to save the passed information as a csv or a dict into a database? -
Django CSS not working
settings.py STATIC_ROOT = 'static/' STATIC_URL = '/static/' STATICFILES_DIRS = ['guide/static/css', 'guide/static/js', ] base.html {% load staticfiles %} ... <link href="{% static bootstrap.css %}" rel="stylesheet" type="text/css" media="all" /> <link rel="stylesheet" href="{% static flexslider.css %}" type="text/css" media="screen" Department="" /> <link href="{% static services.css %}" rel="stylesheet" type="text/css" media="all" /> <link href="{% static ziehharmonika.css %}" rel="stylesheet" type="text/css"> <link href="{% static JiSlider.css %}" rel="stylesheet"> <link href="{% static style.css %}" rel="stylesheet" type="text/css" media="all" /> <!-- font-awesome icons --> <link href="{% static font_awesome.css %}" rel="stylesheet" type="text/css" media="all"/> Here is the project structure: guide - guide - guideapp - templates - base.html - index.html - static - css - js - fonts - db.sqlite3 - manage.py Here, index extends base.html. The content shows up, but the css does not. -
django hide form after submit
Hello i want to have a link form in my post but i want to have only one link per post so if some user add a link i want the form disabled .How can i achieve this ? model and view --> models.py class Link(models.Model): post = models.ForeignKey(Post,related_name='links',on_delete=models.CASCADE) url_link = models.URLField() created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) active = models.BooleanField(default=True) views.py if request.method == 'POST': link_form = LinkForm(data=request.POST) if link_form.is_valid(): new_link = link_form.save(commit=False) new_link.post =post new_link.save() else: link_form=LinkForm() -
Get requests are not pulling latest data from postgresql: Django and apache
I am running a django project where users are entering data through 11 different forms. It is not mandatory to fill all the 11 forms. Each form has a view data page where multiple entries submitted by the user through that form are made visible. For example, say, there are Form1, Form2, ..., Form11 forms. Suppose User1 creates 3 entries through form1, then the ViewForm1Data will show 3 entries to User1. Similarly, there is also a view page for all the data entered by a specific user. For example, if User1 creates 3 entries using Form1, 2 entires using Form3 and 5 entries using Form6, all the entries will be shown to User1 on single page, ViewAllDataUser1. Now the problem is, when user creates an entry, it is not shown immediately to the user. The page requires reload. And if ViewForm1Data is reloaded and entries are seen, it is not guarantee that the ViewAllDataUser1 page will show the entry. This page also requires reload. There seems no problem while posting the data but getting latest data is not working immediately. The project is running since 6 years and I have never faced this problem. Both Postgres and Apache are not … -
Error about bool not being callable in django project [duplicate]
This question already has an answer here: django request.user.is_authenticated is always true? 3 answers I have a djang project and I am trying to use the django authentication within my application. I am getting the following error TypeError at / 'bool' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.2 Exception Type: TypeError Exception Value: 'bool' object is not callable Exception Location: /Users/omarjandali/Desktop/MySplit/mysplit/users/views.py in user_home, line 283 Python Executable: /Users/omarjandali/anaconda3/envs/MySplit/bin/python for the following code traceback: /Users/omarjandali/Desktop/MySplit/mysplit/users/views.py in user_home if request.user.is_authenticated(): does anyone know why this is happening -
insert query using django-models
DB structure User, user has multiple events, events has multiple attendees. User Model: from django.db import models class User(models.Model): email = models.CharField(max_length=100, unique=True, null=True) firstname = models.CharField(max_length=100, null=True) lastname = models.CharField(max_length=100, null=True) org_url = models.CharField(max_length=100, null=True) office_username = models.CharField(max_length=100, null=True) office_email = models.CharField(max_length=100, null=True) isdeleted = models.BooleanField(default=False) createdon = models.DateTimeField(auto_now_add=True, null=True) modifiedon = models.DateTimeField(auto_now=True, null=True) Event Model: from django.db import models from .user import User class OEvent(models.Model): frk_user = models.ForeignKey(User, on_delete=models.CASCADE) o_event_id = models.CharField(max_length=250, null=True) location = models.CharField(max_length=250, null=True) starts_at = models.CharField(max_length=50, null=True) ends_at = models.CharField(max_length=50, null=True) event_title = models.CharField(max_length=150, null=True) isdeleted = models.BooleanField(default=False) createdon = models.CharField(max_length=50, null=True) modifiedon = models.CharField(max_length=50, null=True) Attendee Model: from django.db import models from .o_events import OEvent class OEventAttendee(models.Model): frk_o_event = models.ForeignKey(OEvent, on_delete=models.CASCADE) email = models.CharField(max_length=200, null=True) name = models.CharField(max_length=200, null=True) I can insert events against a user like this: user.oevent_set.create( o_event_id=nData['Id'], location=nData['Location']['DisplayName'], starts_at=startdt, ends_at=enddt, event_title=nData['Subject'], isdeleted=False, createdon=createdon, modifiedon=modifiedon ) What is the best, easy, short way to add attendees like this? I'm assuming that there must be something We can add event_attendees list = attendees array after modifiedon field. But couldn't find anything like that. -
Django unable to access user profile data from User object
I have a Profile model like this: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile') about = models.TextField() When I try to access UserProfile data from User instance I get this error: In [1]: In [1]: from django.contrib.auth.models import User In [5]: u = User.objects.all()[0] In [6]: u Out[6]: <User: admin> In [13]: u.profile --------------------------------------------------------------------------- RelatedObjectDoesNotExist Traceback (most recent call last) <ipython-input-13-679bed70444a> in <module>() ----> 1 u.profile ~/project/djangoedu/env/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py in __get__(self, instance, cls) 402 "%s has no %s." % ( 403 instance.__class__.__name__, --> 404 self.related.get_accessor_name() 405 ) 406 ) RelatedObjectDoesNotExist: User has no profile. In [14]: u.author --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-14-327f8c8449fd> in <module>() ----> 1 u.author AttributeError: 'User' object has no attribute 'author' In [15]: -
Can I send two forms as a variable from django render function?
So a page has two buttons. One button should take us to one form and the other to a different form. How we are doing it right now is we are passing the forms structure from the render function- return render(request, 'abc.html', {'contacts': contacts, 'form': form}) I don't think I can pass a 'form2' in render but I need something like that. The html reference is- {% include "form_abc.html" with form_title="Edit" form_btn="Save" form_id="edit" ajax="True" %} Please let know if you have any inputs. -
Django - Add attribute to serializer and order list based on Foreign Key
what I'm trying to get a data based on foreign keys. Let's say I have these models: # Model class Player(models.Model): name = models.CharField(max_length = 64) class Game(models.Model): score = models.IntegerField() player = models.ForeignKey('Player', models.DO_NOTHING, related_name='player', blank=False, null=False) class InjuredPlayer(models.Model): player = models.ForeignKey('Player', models.DO_NOTHING, blank=False, null=False) I'm using REST framework so I have this serializer. And I want to add an attribute that is the sum of all Game scores to the Player serializer. # Serializer class PlayerSerializer(serializers.ModelSerializer): # Get the sum of Game scores of the player # sum_of_scores = ________________ class Meta: model = Player # Use sum_of_scores as a field on the serializer fields = ('activity', 'logo', 'sum_of_scores') Then, what want to do is display the list of players, with their sum of scores, if they are on InjuredPlayer. So in my class: class PlayerList(APIView) The queryset should be something like: # I tried this queryset = Player.objects.filter(injuredplayer__player=id) How you do filter the objects that are not on the other table. And is it possible to order the list based on the sum_of_scores? If so, how? Thank you -
Django: Detailed and List View URLS - Call same function from views?
So basically i know i can call different functions based on urls from the urls.py in django. Now what i want to know is, can i call the same function for two different urls: Eg: urls.py urlpatterns = [ url(r'^v1/ttu/appliance/',views.get_appliances), url(r'^v1/ttu/appliance/(?P<appliance>[-.\w]+)$',views.get_appliances), ] and my get_appliances in views.py is something like this: def get_appliances(request, appliance): if appliance is None: #do something else: #do something else is this possible? Thank you. -
How to find absolute path of uploaded image - Django 1.11
I have a django form in which the user can upload an image that will then be displayed on a page. After the form request is submitted, I'm trying to return an httpresponse to the user of the uploaded image using the following code: image_data = open("/path/to/my/image.png", "rb").read() return HttpResponse(image_data, content_type="image/png") The issue is that I can't get the absolute path from image submitted in the form request. By doing the following, I can get the name of the image, but not the local path to it: name = "" for filename, file in request.FILES.iteritems(): name = request.FILES[filename] imageFileName = name I've tried using the function file_to_string() based on an SO post, but it looks like the function is deprecated now. How can I get the absolute file path so I can pass it to the open function to return the image? -
python logging with crontab not working
i have python script in django project # bar.py import logging logger = logging.getLogger(__name__) def run(): ...some logic... logger.info("success") and i want make work this script using django-extesions runscript and crontab #setting.py 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'formatter': 'verbose', 'filename': 'foo.log', }, }, 'loggers': { 'myApp': { 'handlers': ['file'], 'level': 'DEBUG' } } if i run this script in terminal with django-exteions runscript, i can get foo.log and log message "success" /path/to/venv/python /path/to/myproject/manage.py runscript bar but run this script with crontab, script is doing very well, but it wasn't make foo.log and write nothing 10 * * * * /path/to/venv/python /path/to/myproject/manage.py runscript bar how can i solve this problem? -
django-cors-headers with spotify not working
I am using the spotify API/spotipy with django and need users to log into their accounts in order to access their data. I have used "pip3 install django-cors-headers" and added the appropriate sections to settings.py. #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jazz_stuff.apps.JazzStuffConfig', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = True CSRF_TRUSTED_ORIGINS = ( 'localhost:8000', ) #views.py def callSpotify(request): if request.method == 'POST': if request.is_ajax(): sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI, scope=SCOPE,cache_path=CACHE) url = sp_oauth.get_authorize_url() return HttpResponseRedirect(url) return None Even with this, I still get the error about missing the access-control-allow-origin header, and the spotify login page does not open up. jquery.min.js:2 XHR finished loading: GET "http://localhost:8000/callSpotify/". (index):1 Failed to load https://accounts.spotify.com/authorize?client_id=14c8a7dfd5804fb5994243e69bb7606f&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback%2F&scope=user-modify-playback-state+user-top-read&show_dialog=True: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. XHR finished loading: OPTIONS "https://accounts.spotify.com/authorize?client_id=14c8a7dfd5804fb5994243e69bb7606f&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback%2F&scope=user-modify-playback-state+user-top-read&show_dialog=True". How should I proceed so that I do not get cors errors? -
Django Forms: How to reference existing object field values in form validation?
So I am creating a Django app which I hope will be used in my school. This means that I have users that are teachers and students, and different permissions for these accounts. I have set it up so that every accounts has a self.teacher attribute, which is a boolean. So for students accounts, self.teacher will be False, and for teachers, self.teacher will be True. My app also contains a profile page, and this page has an edit profile feature. In my app, I want the user to be able to edit, amongst other things, their grade. Now, I have it set up so that grade can be an option of: - 10 - 11 - 12 - N/A Students must only be able to pick a number, while teachers are allowed to select N/A. So I want to have a form validation (which validates the grade field) that checks to see if the user submitting the form is a student, and if so, checks that they have not selected N/A. If they have selected N/A, the validation should raise an error. Any thoughts on how to implement this using Django Forms? -
Build Django Model (read only) on SQL statement - as one would on a db view but
Excuse my (django orm) ignorance, but I would like to create a view based on a raw ("ENGINE": "sql_server.pyodbc" but shouldn't matter). I find many examples of basing a django model on a db view, but need to do similar or a sql statement as I cannot create a view in the database. I think I need to use the raw() manager to execute the query but am stumbling through Django for the first in a long time and cannot find any specific examples of the way to incorporate this in the model definition. Using a database view built on the sql works fine, but is not practical in production using Django 2.0 - Thanks in advance! -
Unable to save a Django Model Object to a varchar datatype field on Sql Server
I am trying to update a object field on a legacy Sql Server database and it's not working. While I was debugging I realized that my problem was only when I was trying to save to a varchar data type field. I had no problem to save to a char data type field. Here follows my code: product = Product.objects.get(id=907169) product.brand = "test_value" product.save(update_fields=['brand']) In this case the variable brand has a varchar data type on the database. So, oddly the object doesn't save and still I get no error message. Any ideas what's going on? -
Django REST Filter_Class for the ManyToManyField
I have a model with a ManyToManyField. So, I have a endpoint to retrieve the list of this ManyToManyField. But I want filter the queryset with the GET parametters (CF: FilterClass). But What is the best practice to do that ? I have already a FilterClass for this model and it's 2 different models Thank you, @detail_route( methods=['GET'], url_path='parts', ) def get_parts(self, request, set__idSet=None): my_set = self.get_object() queryset = my_set.mySetParts.all() # I want filter this queryset page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) -
How to store Users' Location in a Django/Postgres Application
I am developing a react native app which adds a user's location to the databse every time the open the app. My goal is to store as much location data for the user as possible so I can do some machine learning to calculate which posts in their normal area of movement every day will pertain most to them. I use GeoDjango and PostGis to make the application location-aware, and am struggling to determine which data structure in the database will best fit this scenario. The question comes down to whether I should give each user a location = pg_fields.ArrayField() attribute which will end up being extremely large, or use a ManyToManyField for a UserLocation object in the Location app. I know toast tables are an issue in postgres with large arrays, but are they a big enough issue where it would not be worth the stress when trying to extract the data for the user when running machine learning algorithms?