Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use decorators on overridable class methods
I have a custom class with multiple methods that all return a code. I would like standard logic that checks the returned code against a list of acceptable codes for that method and raises an error if it was not expected. I thought a good way to achieve this was with a decorator: from functools import wraps def expected_codes(codes): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): code = f(*args, **kwargs) if code not in codes: raise Exception(f"{code} not allowed!") else: return response return wrapper return decorator then I have a class like so: class MyClass: @expected_codes(["200"]) def return_200_code(self): return "200"" @expected_codes(["300"]) def return_300_code(self): return "301"" # Exception: 301 not allowed! This works fine, however if I override the base class: class MyNewClass: @expected_codes(["300", "301"]) def return_300_code(self): return super().return_300_code() # Exception: 301 not allowed! I would have expected the above overriden method to return correctly instead of raise an Exception because of the overridden decorator. From what I've gathered through reading, my desired approach won't work because the decorator is being evaluated at class definition- however I'm surprised there's not a way to achieve what I wanted. This is all in the context of a Django application and I thought Djangos method_decorator … -
Specify typing for django field in model (for pylint)
I have created custom Django model-field subclasses based on CharField but which uses to_python to ensure that the model objects returned have more complex objects (some are lists, some are dicts with a specific format, etc.) -- I'm using MySQL so some of the PostGreSql field types are not available. All is working great, but pylint believes that all values in these fields will be strings and thus I get a lot of "unsupported-membership-test" and "unsubscriptable-object" warnings on code that uses these models. I can disable these individually, but I would prefer to let pylint know that these models return certain object types. Type hints are not helping, e.g.: class MealPrefs(models.Model): user = ...foreign key... prefs: dict = custom_fields.DictOfListsExtendsCharField( default={'breakfast': ['cereal', 'toast'], 'lunch': []}, ) I know that certain built-in Django fields return correct types for pylint (CharField, IntegerField) and certain other extensions have figured out ways of specifying their type so pylint is happy (MultiSelectField) but digging into their code, I can't figure out where the "magic" specifying the type returned would be. (note: this question is not related to the INPUT:type of Django form fields) Thanks! -
Django and phpmyadmin not loading up cant get it just right
New Django and Python User here this is all new to me. I don't want anyone thinking I haven't done my research. I'm doing the best that I can at following along step by step. I've tried just about everything I've looked at 5 tutorials tried a lot of commands for some reason I'm not able to get phpmyadmin running correctly I did every step the tutorials said. I keep getting stuck when following the tutorials as soon as I get it the two or 3 steps later I find myself in a situation like I am. I normally restart a new project fresh from what I've learned. I've been doing this all week. I'm not at the last step and just like before now I'm stuck again. before I post here I try searching google, going to Stack overflow all over. I'm following this tutorial https://knowledgeofthings.com/django-on-raspberry-pi-3/ i'm currently at the last step getting into pypmyadmin. and nothing. I try to install phpmyadmin again and it won't my server is this ill leave it up http://urbanpythoncoding.com:8000/phpmyadmin I'm so confused. I don't know its so hard to just follow along with the tutorials. I am on a centos system so some … -
How to pass post request data to a separate view? (Django)
I currently have this view which sends a list of genres to a template to populate a dropdown box: class GenreSearch(generic.ListView): template_name = 'games/genresearch.html' context_object_name = 'genre_list' def get_queryset(self): return Genre.objects.order_by("name") This is the template: {% if genre_list %} <div class="btn-group"> <button class="btn btn-secondary btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Select Genre</button> <div class="dropdown-menu scrollable-menu"> {% for genre in genre_list %} <a class="dropdown-item" href="#">{{ genre.name }}</a> {% endfor %} </div> </div> {% endif %} What I want to do now is select a genre from this dropdown box, submit it, and use this view to return results based on which genre is submitted: class GamesPageByGenre(generic.ListView): template_name = 'games/allgames.html' context_object_name = 'game_list' def get_queryset(self): #Return games whose genres include the genre id x return Game.objects.filter(genres__id=10) So if the 'action' genre was selected from the dropdown box, submit this, get the ID for the genre action, then replace genres__id=10 with genres__id=genreID -
When are Django context variables loaded?
A Django-based website has a massive page with many objects. I'd like to decrease the amount of database requests by pre-loading those objects in advance. I know it's normally done with some Redis-like cache storage, but I was wondering if it's possible to implement it with Django context variables. For that I need to know when those variables are loaded: when the server starts or upon every/specific page rendering? In the latter case it wouldn't be of much use, but in the former it would save me the trouble of setting up Redis. -
Django : Save doesn't update initial data along with form
I have two forms (student_form & alumni_form), with each i pass initial data,where in my models student and alumni models are related by OneToOne and as user profiles so i need to update data using those two forms but unfortunately only user model data are updated leaving data for student and alumni not updated, but save method works well as if it save data to the database. Any Help please view.py def alumni_update(request, user_id): # user = get_object_or_404(User, pk=user_id) user = get_object_or_404(User, pk=user_id) # get student_user profile and alumni_student profile profile_student = user.student profile_alumni = profile_student.alumni initial_student = {'st_reg_no': profile_student.st_reg_no, 'st_other_name': profile_student.st_other_name, 'st_dob': profile_student.st_dob, 'st_gender': profile_student.st_gender, 'st_phone_number': profile_student.st_phone_number, 'st_nationality': profile_student.st_nationality, 'st_city': profile_student.st_city, 'programme': profile_student.programme, 'campus': profile_student.campus, } initial_alumni = { 'alumni_type': profile_alumni.alumni_type, 'graduation_year': profile_alumni.graduation_year, } if request.method == 'POST': student_form = StudentUpdateForm(request.POST, initial=initial_student, instance=user) alumni_form = AlumniUpdateForm(request.POST, initial=initial_alumni, instance=profile_student) else: student_form = StudentUpdateForm(initial=initial_student, instance=user) alumni_form = AlumniUpdateForm(initial=initial_alumni, instance=profile_student) return save_user_form(request, student_form, alumni_form, 'partials/alumni/partial_alumni_update.html') def save_user_form(request, student_form, alumni_form, template_name): data = dict() if request.method == 'POST': if student_form.is_valid() and alumni_form.is_valid(): student_form.save() alumni_form.save() data['form_is_valid'] = True users = User.objects.all().filter(is_student__exact=1).order_by('-date_joined') data['html_alumni_list'] = render_to_string('partials/alumni/partial_alumni_list.html', { 'my_user_list': users, 'current_user': request.user }) else: data['form_is_valid'] = False context = {'student_form': student_form, 'alumni_form': alumni_form} data['html_form'] = render_to_string(template_name, context, … -
How do I extend django's createsuperuser management command?
I extended my user model by adding a mandatory Company field, so that every user belongs to some company. The Company field is a foreign key to another model that defines what a company is. This works great, except for the fact that ./manage createsuperuser broke, since it doesn't know to add this custom mandatory field. Turns out that I can add REQUIRED_FIELDS = ['company'] to my custom user model, which will tell createsuperuser to ask for this field. That's better, but since the company field is a Foreign Key, it asks for an ID of the company, which has to be looked up by anyone using the createsuperuser command - not exactly user friendly. I want all admins created with the createsuperuser command to belong to the same company, and for that company to be created automatically if it doesn't exist. Reading django's documentation on createsuperuser, it mentions the exact thing I want to do, and the exact reason I want to do it: You can subclass the management command and override get_input_data() if you want to customize data input and validation. Consult the source code for details on the existing implementation and the method’s parameters. For example, it … -
Authentication with cors and django rest framework
Scenario: 2 separate django apps that use the same ldap server for authentication. App A only needs to do simple GET requests from App B. App B has django-cors-headers and django-rest-framework setup Question: How does App A authenticate to accomplish the GET request from App B? I have the xmlhttprequest setup on App A's frontend and the requests are going through fine but App B always redirects with 302 to the login page. App A: I think my headers are correct. I have withCredentials True. Do I need to send an Authorization Header in the request Authorization: 'Basic ' + btoa(user +' 'pw)? App B: CORS_ORIGIN_WHITELIST = ( '---.---.---.--:8000', #ommited ip 'localhost', ) CORS_ALLOW_CREDENTIALS = True Heres a screen shot of the request and response headers: App A is 8000 and App B is 8006 I can't find any info to help with this. Is this even possible or do I have to use some different method? I guess the short question is can App A authenticate with App B using the same credentials/session/user+pass since they are using the same ldap auth? Any help would be great. -
How can I add filter backends to function based view?
I need to expose a certain method in my Django application. This method does not involve any models or serializers and is simply computational. So I figured this would be a good place to use Function Based Views. I also want this view to show up in swagger. It does but there is no place for a user to plug in data (see screen shot): If I were using GenericAPIView's I could set the filter_backends but I don't even know if this is possible with Function Base Views. Any help is a appreciated. Thanks! -
Photos taken from Android Application are unable to load on Ubuntu 16.04 Server
I have an android application that allows the user to take a picture from the gallery or from the camera. I also have a server that allows the user to upload the image and share it with other users. The android application works without the use of internet, so in order to share, the user who took the picture uploads it to the server. The server is running on a Django web framework, so it stores the image in a media folder. When another user syncs to the server, the image is then downloaded to that device. The problem is that the image is unable to display. The file is there on the Linux machine, but when you try to open it, it gives and error: "Could not load image 'XX.jpg' Failed to open input stream for file. I have tested this on an older android device and the linux machine is able to open the images, but on this newer device, the images are unable to open. I am not sure what the problem could be. This is how I am handling saving the image: @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Bitmap … -
How can I get a count of a model from another model in Django?
I need to get the count of "Movies"(Peliculas) directed by a director. Movie and Director are different classes. I want to create a function in Director that tells me how many movies he has done but i dont know how to call "Peliculas" from "Director" class Director(models.Model): nombre = models.CharField( max_length=100 ) fecha_nacimiento = models.DateField() fecha_defuncion = models.DateField( 'Fallecido', null=True, blank=True, ) foto = models.ImageField( upload_to='images/directores/', default='images/directores/sin_foto.jpg' ) def get_num_peliculas(self): n_peliculas = Pelicula.object.all().count #NOT WORKING return n_peliculas class Pelicula(models.Model): titulo = models.CharField( max_length=100 ) url_trailer = models.CharField( max_length=100 ) fecha = models.DateField() notas_posibles = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5) ) nota = models.IntegerField( default=3, choices=notas_posibles ) sinopsis = models.TextField( max_length=400, default="Sin sinopsis" ) caratula = models.ImageField( upload_to='images/peliculas/caratulas', default='images/peliculas/caratulas/sin_caratula.jpg' ) imagen_promocional = models.ImageField( upload_to='images/peliculas/imagenes_promocionales', default='images/peliculas/imagenes_promocionales/sin_imagen.jpg' ) genero = models.ManyToManyField( Genero, blank=True, related_name='genero' ) director = models.ForeignKey( Director, on_delete=models.SET('Sin Director') ) actores = models.ManyToManyField( Actor, blank=True ) How can I acomplish this? It is driving me crazy! Ty guys! -
Django error when installing mysqlclient on Ubuntu 18.04
I installed Python 2.7.15rci and Python 3.6.7 on Ubuntu. When i did 'pip list' on virtualenv it returns me: Django (2.1.5) pip (9.0.1) pkg-resources (0.0.0) pytz (2018.9) setuptools (39.0.1) wheel (0.32.3) I'm trying to install mysqlclient (pip install mysqlclient) and returns an error. building 'MySQLdb._mysql' extension error: command 'x86:64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command d:\XXX\XXX\env\project\bin\python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-pq18uxjj/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpez7n1kzkpip-wheel- --python-tag cp36: /usr/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/MySQLdb x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC … -
How To Prevent Double Submit With Form Validation
I have been researching this problem for the last day or so. I am trying to prevent the user from double clicking on the submit button for my django project and submitting the form twice. I am also doing form validation so if the form validation fails, I don't want to disable the submit button. My form validation is preventing a double submit in this case because I have a unique field in my form which is preventing the double submit. I am also doing a redirect after the submit, but if I double or triple click the submit button the form fails and never does the redirect. I've tried various versions of the code below which I found on a similar SO issue... $(document).ready(function (){ $('form').submit(function() { $('#status').attr('disabled', true); }); }); In the case of my code, I am trying to pass a value with my submit button, and as such, using the code above prevents the value from being passed when I incorporate it. I am using HTML as shown below: <button type="submit" class="button15" name="status" id="status" value="Submitted"><h3 class="txtalgn4">Submit</h3></button> If I use the JQuery above along with the HTML shown, they seem to conflict and it still doesn't prevent … -
How to integrate channels and DRF together
I'm currently trying to create a backend server to communicate with some clients with a websocket. The clients makes some request to the backend and the backend responds directly to the client through a consumer. In addition, I've got an API that needs to send some requests to the client. It has to go through the opened socket of the consumer. I'm using Django Rest Framework for the API. So I've got 2 apps for now. One for the consumer and one for the API. I want to know if it's the correct way or not. This is actually the code I'm thinking about right now: # mybackendapp/consumers.py class MyConsumer(AsyncWebsocketConsumer): async def connect(self): self.client_id = self.scope['url_route']['kwargs']['client_id'] # This line I don't get it very well. It comes from: # [channels doc: single channels][1] # I don't know if I should create the Clients myself or if it's # created automatically Clients.objects.create(channel_name=self.channel_name, self.client_id) self.accept() async def disconnect(self): Clients.objects.filter(channel_name=self.channel_name).delete() async def receive(self, text_data): self.recv_data = json.loads(text_data) if self.recv_data[0] == CLIENT_REQUEST: self.handler = ClientRequestHandler(self.client_id, self.recv_data) await self.handler.run() self.sent_data = self.handler.response self.send(self.sent_data) elif self.recv_data[0] == CLIENT_RESPONSE: self.handler = ClientResponseHandler(self.client_id, self.recv_data) channel_layer = get_channel_layer() # Here I'm not sure but I may have several API … -
405 error after implementing new search view
Currently using Django 2.1,Python 3.6, PostgreSQL 11, and hosting the DB on Heroku. I am creating a web application that acts as a GUI database entry. I recently was provided with some search code here Django Front End Search. This code worked with a test application that has the server hosted on my machine. I am now seeing a 405 error when I try to communicate with my Heroku hosted database. Currently my web app lists donors on donor_list.html. I would like for my user's query results to be posted on the donor_list.html after they perform their query. Here is the error: Method Not Allowed (POST): /device/donor_list/ Method Not Allowed: /device/donor_list/ "POST /device/donor_list/ HTTP/1.1" 405 0 # associated urls path('donor_list/',views.DonorList.as_view(),name='donor_list'), # Donor Model class Donor(models.Model): name=models.CharField(max_length=265,blank=False) email=models.EmailField(max_length=265,blank=False) donation_house=models.ForeignKey(DonationHouse, default='1', related_name='dono_house', on_delete=models.CASCADE) def __str__(self): return self.name # Donor View class DonorList(ListView): context_object_name = 'donors' model=models.Donor # Search Code def SearchDonor(request): keywords='' if request.method=='POST': # form was submitted keywords = request.POST.get("ds", "") all_queries = None search_fields = ('name','email','donation_house__title') for keyword in keywords.split(' '): keyword_query = None for field in search_fields: each_query = Q(**{field + '__icontains': keyword}) if not keyword_query: keyword_query = each_query else: keyword_query = keyword_query | each_query if not all_queries: all_queries … -
Use the existing database table in Django Framework
Is it possible to use Django with an existing database table, Microsoft SQL in my case. I added a model as per below code but this create a table naming - XXX\qqqqq.AccountType in database however there is a table name dbo.AccountType already exist. Can you please suggest how I can use the existing table dbo.AccountType here? What setting change require? class AccountType(models.Model): class Meta: db_table = 'AccountType' Id = models.IntegerField(primary_key=True, db_column='Id') Desc = models.CharField(max_length=20, db_column='Desc') CreatedBy = models.CharField(max_length=150, db_column='CreatedBy') Created = models.DateTimeField(auto_now=True, db_column='Created') UpdatedBy = models.CharField(max_length=150, db_column='UpdatedBy') Updated = models.DateTimeField(auto_now_add=True, db_column='Updated') -
Django Request MiddleWare Not Taking Effect in View
I am working on a solution that is taking a JWT token, finding the associated user, and setting the user in the request to the found user with the token. My middleware looks like this: class UserTokenMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): header_token = request.META.get('HTTP_AUTHORIZATION', None) if header_token is not None: try: token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1] data = {'token': token} valid_data = VerifyJSONWebTokenSerializer().validate(data) user = valid_data['user'] request.user = user except Token.DoesNotExist: pass print(request.user.auth_token); return self.get_response(request) And it works! The auth_token is present! And its added at the bottom of my middleware like so: MIDDLEWARE = [ #Added Last "app.middleware.UserTokenMiddleware" ] Now here where doesn't work. I am trying to log out by deleted token, and I need the key. So I have this: @action( url_path="logout", detail=False, methods=["get"], renderer_classes=[JSONRenderer]) def endsession(self, request): result = logout(request) #request.user.auth_token.delete() print("Auth Token") print(request.user.auth_token); print(result) return Response({"logout": "successful"}) Except I always get the following error: Exception Type: AttributeError at /v1/users/logout Exception Value: 'AnonymousUser' object has no attribute 'auth_token' Any clue to why the auth_token is suddenly disappearing and reverting to AnonymousUser? -
reversing django object query with parent-child M2M relationship
in a case with three models (objects) with this type of object relationship: # Team = parent, a group or collection of people class Team(models.Model): name = models.CharField(max_length=100, unique=True) ... # Person = an individual person who belongs to a team class Person(models.Model): # relationships team = models.ForeignKey('Team', on_delete=models.CASCADE, related_name='people') projects = SortedManyToManyField('Project', related_name='people') # Project = each Person can have zero, one, or multiple Projects # multiple different teams can work on same Project class Project(TimeStampedModel): TYPES = Choices( ... ) I know I can query "People with Projects on a Team" like this: user_teams = Team.objects.filter(user=request.user, ...) people_with_projects = Person.objects.filter(team__in=user_teams, projects=True) how would I reverse that to get the queryset for "list of Projects People who are on Team Foo are working on"? (i.e., Projects by specific Team) thanks -
TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not function (wsgi.py error)
I developed this django project on ubuntu using Django 2.0 and Postgresql, then I cloned it to run on windows. After migrating the databases when I run "python manage.py runserver" it throws the following type error. Any help would be appreciated! Traceback Performing system checks... System check identified no issues (0 silenced). January 24, 2019 - 20:02:45 Django version 2.1.2, using settings 'main.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03A378A0> Traceback (most recent call last): File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\core\servers\basehttp.py", line 44, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\HP\Desktop\django\crowd-social\crowdsocial_env\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\python3\Lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\Desktop\django\crowd-social\main\main\wsgi.py", line 19, in <module> application … -
Two forms, two views, one page Django - only one form displays
I have two separate forms stemming from the same model (CustomUser). I want to have two separate forms with separate buttons to break the EditProfile form down into two forms on the same page. I created two separate forms, two views and two urls. I also added two separate actions to the forms, but I can only get the first form to display. I tried adding both the name of the url and the name of the view function in the action, but it didn't work. views.py: def EditProfileView(request): form = EditProfile() if request.method == 'POST': form = EditProfile(request.POST, instance =request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('edit_profile')) else: form = EditProfile(instance = request.user) return render(request, 'edit_profile.html', { 'form': form, }) def EditProfileDetailView(request): form = EditProfileDetail() if request.method == 'POST': form = EditProfileDetail(request.POST, instance =request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('profile')) else: form = EditProfileDetail(instance = request.user) return render(request, 'edit_profile.html', { 'form': form, }) urls.py: urlpatterns = [ path('profile/edit/', views.EditProfileView, name='edit_profile'), path('profile/edit/', views.EditProfileDetailView, name='edit_profile_detail'), ] forms.py: class EditProfile(forms.ModelForm): class Meta: model = CustomUser fields =('diff_field', 'diff_field2',) class EditProfileDetail(forms.ModelForm): class Meta: model = CustomUser fields =('skill_area1_title', 'skill_area1',) edit_profile.html: <form class="form-group booking_form" method="post" action="{% url 'edit_profile' %}"> {% csrf_token %} #form stuff </form> <form class="form-group … -
Django, Celery, Redis: AttributeError: module 'expert' has no attribute 'celery'
Tyring to start celery -A imp_expert worker -l info as per the Celery documentation (my project is not named proj, it's imp_expert) I get: Traceback (most recent call last): File "/home/expert/.virtualenvs/semion_expert/bin/celery", line 11, in <module> sys.exit(main()) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/__main__.py", line 16, in main _main() File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/base.py", line 273, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/base.py", line 479, in setup_app_from_commandline self.app = self.find_app(app) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/bin/base.py", line 501, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/home/expert/.virtualenvs/semion_expert/lib/python3.5/site-packages/celery/app/utils.py", line 370, in find_app found = sym.celery AttributeError: module 'imp_expert' has no attribute 'celery' I have in __init__.py: from __future__ import absolute_import from .celery import app as celery_app __all__ = ('celery_app',) In celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'imp_expert.config.base') app = Celery('imp_expert') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) In base.py … -
PostgreSQL with Django: should I store static JSON in a separate MongoDB database?
Context I'm making, a Django web application that depends on scrapped API data. The workflow: A) I retrieve data from external API B) Insert structured, processed data that I need in my PostgreSQL database (about 5% of the whole JSON) I would like to add a third step, (before or after the "B" step) which will store the whole external API response in my databases. For three reasons: 1) I want to "freeze" data, as an "audit trail" in case of the API changes the content (It happened before) 2) API calls in my business are expensive, and often limited to 6 months of history. 3) I might decide to integrate more data from the API later. Calling the external API again when data is needed is not possible because of 2) and 3) Please note that the raw external API responses will never be updated and read performance is not really important. To provide additional context, there is a few thousand API calls a day, which represent arround 50GB of data a year. Here comes my question(s) Should I store the raw JSON in the same PostgreSQL database I'm using for the Django web application, or in a separate … -
docker-compose with two containers: web can not connect to db
docker-compose fails to build web component because it can not connect to the previously created db component Mac OSX 10.13.6, conda 4.5.11, Python 3.6.8, Docker version 18.09.1, docker-compose version 1.23.2 django 1.8.3 gets installed with requirements.txt from Dockerfile. Not at liberty to upgrade. Several very similar discussions on SO did not help (like this one: Docker-compose with django could not translate host name "db" to address: Name or service not known). I have a docker-compose.yml with a network and two components: version: '3' networks: bridge: driver: bridge services: db: image: postgres:10 container_name: myapp-db volumes: - ./postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" environment: POSTGRES_DB: actionability-master POSTGRES_PASSWORD: postgres POSTGRES_USER: postgres networks: - bridge web: restart: unless-stopped container_name: myapp-web build: . command: /start_gunicorn.sh ports: - "8080:8080" environment: PRODUCTION: 'true' networks: - bridge In my settings.py I have DATABASES section: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': INSTANCE_NAME, 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432' }, } When I run $ docker-compose up -d, the first image (db) gets created and its container gets started. Can see it's running and listening on port 5432 with docker ps and lsof . The same thing happens if I remove web: component from docker-compose.yml file Now, the … -
Unable to install right version of mysql(8.0.13) on windows
I am a Windows user and very new with django and database. My current group project requires to use django and mysql. My teammate(macOS user) has already built a django web and I was trying to run the web by running it on virtualenv. I tried to download every required packages by typing 'pip install -r requirements.txt'. Although, it downloaded most of the packages, but it did not allow me to install mysql==8.0.13. I tried other methods such as 'pip install mysql==8.0.13' or even trying it on ubuntu bash. However, I always get this message.... (virtualenv) C:\Users\ed>pip install mysql==8.0.13 Collecting mysql==8.0.13 Could not find a version that satisfies the requirement mysql==8.0.13 (from versions: 0.0.1, 0.0.2) No matching distribution found for mysql==8.0.13 So even after many tries, I could not find a solution so when I just type 'py manage.py runserver' or 'python manage.py runserver', the results show like this.... (virtualenv) C:\kim....\projectsite>py manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by .wrapper at 0x03585618> Traceback (most recent call last): File "C:\Users\edwardkim\Envs\shkim\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\edwardkim\Envs\shkim\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\edwardkim\Envs\shkim\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return … -
modelling an ER diagram for django
I needed some help to convert to tables and later to django's models, using Django's Admin interface, two entities (Item, Prototype) where: Item can be a standalone object or be part of one prototype only Prototype exists only if it contains at least an Item A Prototype can contain many different items. The ER diagram should be this: At the Django side I wished: from the PrototypeAdmin to include any Item(s) and from ItemAdmin to assign to one prototype like in the followings pictures: I made some attempts designing different models but I'm not fully satisfied of my results (one try implies many NULLs, another gives an admin interface not very easy to use, from another one I can only add Items to protype..)